Access variables between commands with discord.py

后端 未结 2 721
执念已碎
执念已碎 2020-12-12 05:47

I have this (overly simplified) Discord bot

voting_enabled = False

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

@bot.command()
async def fin         


        
相关标签:
2条回答
  • 2020-12-12 06:16

    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
    
    0 讨论(0)
  • 2020-12-12 06:21

    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
    
    0 讨论(0)
提交回复
热议问题