Search code examples
pythonvariablesdiscordundefinedexists

Python variable exists undefined?


I am having trouble creating a simple on/off switch. I am beginner and am writing a discord bot for fun and to learn. My bot is on more than one server and that is why a global variable isn't an option (running it on one server also changes it for others). Putting a variable inside the command isn't an option because every time I run the command, it defines it. I need something that exists but can only be defined by subprocesses.

@bot.command()
async def xxx(ctx):

    # global x # doesn't work correctly
    # x = "" # doesn't work correctly

    if x != True:
        x = True
        await ctx.send("X is on!")
 
    else:
        x = False
        await ctx.send("X is off!")


    while x == True:
        #some code calculations here, blablabla

    await asyncio.sleep(60)

What is a solution to my problem? Thank you.


Solution

  • I assume that server means ctx.guild - so you can use dictionary to keep values for different servers - x[ctx.guild.name] or x[ctx.guild].

    You don't have to create all servers at start but you can check in function if server is in dictionary and add default value.

    # global dictionary
    x = dict()
    
    @bot.command()
    async def xxx(ctx):
        # dictionary doesn't need `global x` in function
    
        server_name = ctx.guild.name
        
        # set default value if used first time on server/guild
        if server_name not in x:
            x[server_name] = False
            
        if not x[server_name]:
            x[server_name] = True
            await ctx.send("X is on!")
        else:
            x[server_name] = False
            await ctx.send("X is off!")
    
        while x[server_name]:
            #some code calculations here, blablabla
    
        await asyncio.sleep(60)
    

    You can also switch True/False using not

    x[server_name] = not x[server_name]
    
    if x[server_name]:
        await ctx.send("X is on!")
    else:
        await ctx.send("X is off!")