Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

python - Access variables between commands with discord.py

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Except don't use globals because they stinky. Discord.py has another way to do this.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...