Search code examples
pythonpython-3.xdiscord.pyglobal-variables

I've problems with Python global


My problem is similar to this, but it's not into a class.

My code is this (after removing some ininfluent lines):

@Bot.command()
async def Limonate(ctx, secondi, menzione=None):
    global attesa
    global canale
    attesa = float(secondi)
    canale = ctx.channel

This is a command, and I need that part to do this:

@Bot.event
async def on_ready():
    attesa = 100
    while (True):
        frase = choice(frasi_ad_effetto)
        await sleep(attesa)
        global canale # Here's the problem
        global menzione
        await canale.send(menzione + ', ' + frase) # 

So the problem is that, if the Bot has just started (and the command Limonate was never executed), the canale variable is empty.

Do you know any way to solve my problem?


Solution

  • in function Limonate, you need to declare canale as a global variable before setting it to the value.

    @Bot.command()
    async def Limonate(ctx, secondi, menzione = None):
        global attesa, canale
        attesa = float(secondi)
        canale = ctx.channel