为什么未定义目标

时间:2020-06-16 18:40:15

标签: python discord.py

我正在使用discord.py编码一个不和谐的经济机器人,但是我的share命令不起作用:

if message.content.startswith('bott share'):
        try:
            target, amount = message.content.split(' ')[1:]
            amount = int(amount)
        except ValueError:
            await message.channel.send('Invalid Arguments')
        target = target[2:-1]
        if target[0] == '!':
            target = target[1:]
        target = int(target)
        if amount > getcoins(user):
            await message.channel.send('ARE YOU TRYING TO HJACK THE SYSTEM?')
        elif amount < 0:
            await message.channel.send('ARE YOU TRYING TO HJACK THE SYSTEM?')
        setcoins(user, getcoins(user)-amount)
        setcoins(target, getcoins(target)+amount)
        await message.channel.send(f'You gave {target} {amount}, and now you have {getcoins(user)}.')

运行时它说:

Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/runner/.local/lib/python3.8/site-packages/discord
/client.py", line 312, in _run_event
    await coro(*args, **kwargs)  File "main.py", line 601, in on_message
    target = target[2:-1]
UnboundLocalError: local variable 'target' referenced before as
signment

1 个答案:

答案 0 :(得分:1)

运行时

 target, amount = message.content.split(' ')[1:]

会有错误,那么它将不会创建变量targetamount,但是在捕获到此错误之后,您将运行target[2:-1],然后尝试从不存在的变量中获取价值

您可以将所有内容放入try / except

if message.content.startswith('bott share'):
    try:
        target, amount = message.content.split(' ')[1:]
        amount = int(amount)
            target = target[2:-1]
        if target[0] == '!':
            target = target[1:]
        target = int(target)
        if amount > getcoins(user):
            await message.channel.send('ARE YOU TRYING TO HJACK THE SYSTEM?')
        elif amount < 0:
            await message.channel.send('ARE YOU TRYING TO HJACK THE SYSTEM?')
        setcoins(user, getcoins(user)-amount)
        setcoins(target, getcoins(target)+amount)
        await message.channel.send(f'You gave {target} {amount}, and now you have {getcoins(user)}.')
    except ValueError:
        await message.channel.send('Invalid Arguments')

或者您可以在try/except之前或except内部设置一些默认值

    target = None
    amount = None

    try:
        target, amount = message.content.split(' ')[1:]
        amount = int(amount)
    except ValueError:
        await message.channel.send('Invalid Arguments')

    if target is not None and amount is not None:
       target = target[2:-1]
       # ... rest ...

或最终-但如果target为空字符串或amount0,则if将给出False

    if target and amount:
       target = target[2:-1]
       # ... rest ...

如果您在函数中运行此代码,则可以使用return完成函数

    try:
        target, amount = message.content.split(' ')[1:]
        amount = int(amount)
    except ValueError:
        await message.channel.send('Invalid Arguments')
        return  # finish function