我如何在Discord.py命令函数中进行计数器工作



如何获得命令功能中增加的计数器?例如:

global counter
counter = 0
@client.command(pass_context=True)
   async def pick(ctx):
   counter += 1

每当我尝试这样做时,它都会给我这个错误: Unboundlocalerror:分配前引用的本地变量'计数器'我已经尝试了很多方法来使它起作用,但是我无法弄清楚它和亲人一样挽救我的生命。

有几种方法可以实现您想要的东西。

,您可以,如Hopethatsacleanwet的答案中所述,只需全局变量名称,因此您可以访问全局范围中的一个,而不是本地范围。

@client.command()
async def pick():
    global counter
    counter += 1

您也可以使用Benjin的答案中提到的,使用COG将变量绑定到范围,该函数可以访问。

class MyCog:
    def __init__(self, bot):
        self.bot = bot
        self.counter = 0
    @commands.command()
    async def pick(self):
        self.counter += 1
def setup(bot):
    bot.add_cog(MyCog(bot))

您甚至可以将计数器绑定到bot

client.counter = 0
@client.command()
async def pick():
    bot.counter += 1

我推荐您阅读Python的名称空间

您可以尝试使用类和使用self.counter创建COG。您可以通过创建一个包含类的单独文件,在底部创建一个setup函数,然后在运行bot的主代码中使用load_extension。下面的示例代码。

bot.py

from discord.ext import commands
client = commands.Bot(command_prefix='!')
client.load_extension('cog')
client.run('TOKEN')

cog.py

from discord.ext import commands
class TestCog:
    def __init__(self, bot):
        self.bot = bot
        self.counter = 0
    @commands.command()
    async def pick(self):
        self.counter += 1
        await self.bot.say('Counter is now %d' % self.counter)

def setup(bot):
    bot.add_cog(TestCog(bot))

发生错误的原因是因为Python试图在pick命令中的本地范围中定义counter。为了访问全局变量,您需要将其"重新定义"为本地上下文中的全局。更改pick命令将修复它:

@client.command(pass_context=True)
async def pick(ctx):
    global counter
    counter += 1

最新更新