【问题标题】:UnboundLocalError: local variable referenced before assignment Discord.pyUnboundLocalError:在分配 Discord.py 之前引用的局部变量
【发布时间】:2021-06-07 23:54:38
【问题描述】:

我不断收到此错误,想知道如何解决它:

@bot.event
async def on_message(message):
    if isinstance(message.channel, discord.channel.DMChannel) and message.author != bot.user:
         async with message.channel.typing():
             responses = ["word", "car"]
    await asyncio.sleep(1)
    await message.channel.send(f'{random.choice(responses)}')

我得到的错误是: 忽略 on_message 中的异常

Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\endle\Documents\MyDiscordBot\bot.py", line 112, in on_message
    await message.channel.send(f'{random.choice(responses)}')
UnboundLocalError: local variable 'responses' referenced before assignment

有人可以帮忙吗?

【问题讨论】:

  • 如果if isinstance(message.channel, discord.channel.DMChannel) . . . 检查为假,responses 会是什么?
  • responses 是我用来随机选择一个字符串并发送它的变量
  • responses 仅在第一个 if 语句为真时作为变量存在。如果为 false,则不会创建变量并且您会收到错误消息。
  • John Gordon,我在哪里使我的 if 语句为真,对不起,我不是最好的 python

标签: python python-3.x discord.py


【解决方案1】:

您需要else。没有这个,你实际上不会每次都定义变量responses,所以当它进入代码的最后一行时,你是从一个不存在的列表中选择一个随机元素。

在就 Stack Overflow 提问之前,您可能应该了解基本的 Python。有些人可能不是最友好的!

Here 是来自 Rapptz 的 discord.py 文档。

【讨论】:

    【解决方案2】:

    添加一个 else: 语句以便始终定义响应。

    因为你说你对 python 不是超级熟悉,所以实现它的快速示例:

    if isinstance(message.channel, discord.channel.DMChannel) and message.author != bot.user:
        async with message.channel.typing():
            responses = ["word", "car"]
    elif message.author != bot.user:
        responses = ["insert thing here"]
    else:
        responses = None
    

    【讨论】:

    • 我的机器人一直在回复自己,如果你能解决这个问题,那就太好了。对不起
    • 它再次给出未绑定的本地错误
    • 我很蠢,一秒钟,你必须在尝试调用它之前检查响应是否为无,但如果你这样做,这应该可以解决它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 2020-01-16
    • 2019-12-05
    • 2017-09-19
    • 2020-09-26
    • 2022-01-02
    相关资源
    最近更新 更多