Access variables between commands with discord.py

有些话、适合烂在心里 提交于 2019-12-25 17:25:11

问题


I have this (overly simplified) Discord bot

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

The problem

When I call call the vote() command, it always goes through the else part of the code. Even after calling the start() command

What I want to achieve

I want that the vote() command behave differently depending on if the other two commands where called previously

What I tried

I tried using the global keyword like this on the first line

global voting_enabled
voting_enabled = False

But it did nothing


回答1:


The global keyword was not used correctly.

global should be defined within every function.

Example:

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


来源:https://stackoverflow.com/questions/47955125/access-variables-between-commands-with-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!