【问题标题】:Absolutely baffling issue with Discord.py botDiscord.py 机器人的绝对令人困惑的问题
【发布时间】:2018-03-17 04:37:30
【问题描述】:

我正在竭尽全力尝试调试和解决此错误。基本上,我有一个变量(maxID),当它非常清楚地在检查前后都认为它没有初始化时。它似乎只在我的 add 方法中执行此操作,因为它在我尝试过的所有其他方法中都很好(我在我的代码中留下了一个调试打印,我可以确认在证明 maxID 的 ping 方法中确实有效已初始化)。相关代码如下:

import discord
import asyncio
from discord.ext import commands

class Quote:
    def __init__(self, id, msg):
        self.id = id
        self.msg = msg

bot = commands.Bot(command_prefix = '-')

q = open("maxID.txt","r")
maxID = int(q.read())
q.close()

print(maxID)

temp = [0 for x in range(len(quotes))]
for i in range(0, len(quotes)):
    temp[i] = Quote(ids[i],quotes[i])
quotes = temp

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.event
async def on_message(message):
    await bot.process_commands(message)

@bot.command(pass_context=True)
async def ping(ctx):    
    await ctx.channel.send('Pong!')
    print(maxID)

@bot.command(pass_context=True)
async def add(ctx, *, arg):
    quotes.append(Quote(maxID, arg))
    maxID = maxID + 1
    await ctx.channel.send('Added Quote #' + str(len(quotes)))

旁注:在上述引用中提到 maxID 的任何时候,在 add 之外,我都可以确认工作正常,没有我可以看到的问题.

我从 add 方法得到的确切错误:

Ignoring exception in command add:
Traceback (most recent call last):
  File "C:\Users\Acemcbean\AppData\Roaming\Python\Python36\site-packages\discord\ext\commands\core.py", line 62, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "C:\IzunaBot\run.py", line 51, in add
    quotes.append(Quote(maxID, arg))
UnboundLocalError: local variable 'maxID' referenced before assignment

【问题讨论】:

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


    【解决方案1】:

    add 命令中的maxID 被解释为局部变量而不是全局变量。

    This thread(特别是this answer)可能对您有用。

    您可以更新您的 add 命令以包含将 maxID 定义为非局部变量的行作为修复:

    @bot.command(pass_context=True)
    async def add(ctx, *, arg):
        nonlocal maxID
        quotes.append(Quote(maxID, arg))
        maxID = maxID + 1
        await ctx.channel.send('Added Quote #' + str(len(quotes)))
    

    【讨论】:

    • 我试过这个,但它似乎不起作用。我收到以下错误:SyntaxError: no binding for nonlocal 'maxID' found
    • @Acemcbean 试试global maxID
    • 是的,我昨晚在发送消息后做了,它成功了,但我在之后(大约是凌晨 4 点)就睡觉了,不过谢谢你的帮助,我很感激
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    相关资源
    最近更新 更多