【问题标题】:How do I get a counter to work within a discord.py command function?如何让计数器在 discord.py 命令函数中工作?
【发布时间】:2018-09-10 02:30:02
【问题描述】:
如何在命令函数中使计数器增加?例如:
global counter
counter = 0
@client.command(pass_context=True)
async def pick(ctx):
counter += 1
每次我尝试这样做时,都会出现以下错误:
UnboundLocalError:赋值前引用了局部变量“counter”
我已经尝试了很多方法来让它发挥作用,但我无法想办法挽救我的生命以及我所爱的人。
【问题讨论】:
标签:
python-3.6
discord
discord.py
【解决方案1】:
您可以尝试使用 self.counter 创建带有类的 cog。为此,您可以创建一个包含该类的单独文件,在底部创建一个setup 函数,然后在运行机器人的主代码中使用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))
【解决方案2】:
发生错误的原因是 Python 试图在 pick 命令内的本地范围内定义 counter。为了访问全局变量,您需要在本地上下文中将其“重新定义”为全局变量。将 pick 命令更改为此将修复它:
@client.command(pass_context=True)
async def pick(ctx):
global counter
counter += 1
【解决方案3】:
有几种方法可以实现你想要的。
对于一个你可以,正如希望sacleanwet的回答中提到的,只是全局变量名,这样你就可以在全局范围内访问变量名,而不是在本地范围内。
@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))
你甚至可以将计数器绑定到机器人
client.counter = 0
@client.command()
async def pick():
bot.counter += 1
我建议你阅读python's namespaces