Discord.py — How would i make a variable server-specific?

Question:

In discord.py, a variable is module-specific, not server specific. How would I make it so that a variable value only applies to a specific server?

My code:

@client.command()
async def enable(ctx):
    await ctx.message.delete()
    global Toggle
    Toggle = True
    embed=discord.Embed(title="Enabled!", color=0x5e0000)
    embed.set_footer(text="To disable, do !disable.")
    user = ctx.author
    await user.send(embed=embed)
    
@client.command()
async def disable(ctx):
    await ctx.message.delete()
    global Toggle
    Toggle = False
    embed=discord.Embed(title="Disabled!", color=0x5e0000)
    embed.set_footer(text="To enable, do !enable.")
    user = ctx.author
    await user.send(embed=embed)

@client.command(pass_context=True)
async def isenabled(ctx):
    await ctx.message.delete()
    if Toggle == True:
        await ctx.send("!enable has been ran!")
    else:
        embed=discord.Embed(title="Error: !enable must be ran first.", color=0x5e0000)
        user = ctx.author
        await user.send(embed=embed)

When I go into server 1 and do !enable, and go into server 2 and do !disable, both servers return "Error: !enable must be ran first." If I do !disable first, both servers return "Enable has been ran!". How would I make it so that if I do !enable in one server, it goes through in only that server, and if I do !disable in the other, it returns an error in only that server?

Asked By: 4m w31rd

||

Answers:

Try using a dictionnary:

toggle_dict = {}

@client.command()
async def enable(ctx):
await ctx.message.delete()
    global toggle_dict
    toggle_dict[ctx.guild.id] = True
    Toggle = True
    embed=discord.Embed(title="Enabled!", color=0x5e0000)
    embed.set_footer(text="To disable, do !disable.")
    user = ctx.author
    await user.send(embed=embed)
    
@client.command()
async def disable(ctx):
    await ctx.message.delete()
    global toggle_dict
    toggle_dict[ctx.guild.id] = False
    embed=discord.Embed(title="Disabled!", color=0x5e0000)
    embed.set_footer(text="To enable, do !enable.")
    user = ctx.author
    await user.send(embed=embed)

@client.command(pass_context=True)
async def isenabled(ctx):
    await ctx.message.delete()
    id = ctx.guild.id
    if id in toggle_dict and toggle_dict[id] == True:
        await ctx.send("!enable has been ran!")
    else:
        embed=discord.Embed(title="Error: !enable must be ran first.", color=0x5e0000)
        user = ctx.author
        await user.send(embed=embed)
Answered By: Clement Genninasca
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.