使用 discord.py 在命令之间访问变量

Access variables between commands with discord.py

我有这个(过于简化的)Discord 机器人

voting_enabled = False

@bot.command()
async def start():
    voting_enabled = True

@bot.command()
async def finish():
    voting_enabled = False

@bot.command()
async def vote():
    if voting_enabled:
        # Do something
    else:
        # Do something else

问题

当我调用 vote() 命令时,它总是通过代码的 else 部分。即使在调用 start() 命令后

我想达到的目标

我希望 vote() 命令的行为有所不同,具体取决于之前是否调用了其他两个命令

我试过的

我试过在第一行使用这样的 global 关键字

global voting_enabled
voting_enabled = False

但它什么也没做

global关键字使用不正确。

global 应在每个函数中定义。

示例:

voting_enabled = False

@bot.command()
async def start():
    global voting_enabled

    voting_enabled = True

@bot.command()
async def finish():
    global voting_enabled

    voting_enabled = False

@bot.command()
async def vote():
    global voting_enabled

    if voting_enabled:
        # Do something
    else:
        # Do something else

除非不要使用全局变量,因为它们很臭。 Discord.py 还有另一种方法可以做到这一点。

bot.voting_enabled = False

@bot.command()
async def start():
    bot.voting_enabled = True

@bot.command()
async def finish():
    bot.voting_enabled = False

@bot.command()
async def vote():
    if bot.voting_enabled:
        # Do something
    else:
        # Do something else