Search code examples
pythondiscord.pypycord

Use variables of imported files


So I have this file with the following code

async def check_server_restriction(ctx):
    restriction = await get_restriction()
    global check
    
    if restriction[str(ctx.channel.id)]["Server"] == 1:
        await ctx.send("This command is restricted. You can use it in the #bot-commands channel")
        check = True

And I have another file that looks like this:

from channel_restrictions_functions import test_187, new_restriction, get_restriction, check_server_restriction, check
class whois(commands.Cog):

    def __init__(self, client):
        self.client = client


    @commands.command()
    async def whois(self, ctx, member:discord.Member = None):
        await test_187()
        await new_restriction(ctx)
        await check_server_restriction(ctx)
        
        #print(check)
        if check == True:
            print("Nicht perint")
            return

So basically I import the function and try to import the variable too. The problem is now when the imported function gets activated and turns check (the variable) True (in theory) nothing happens. It should work like this when the thing is in the list it should send "This command is restricted" and set check true so that in my command the if statement works and it will return.

I dont get whats the mistake. I think it says check = False every time but it should be true

I hope you can understand my problem and you know how to fix it thx for the help


Solution

  • Even global variables are not truly global, they are global only within the scope of their own module. There are ways to get around this restriction and share a variable between modules, if you absolutely have to, see e.g. here. It is recommended to put all global variables into a separate module and import from there, however, see the Python docs for more on this.


    That said, why would you want to do this with a global variable? It's simpler and less error prone (in the sense that the restriction status would be shared between commands if global, which might lead to commands being falsely restricted) to just have check_server_restriction return True or False and then check the return value of the function something like this:

    async def check_server_restriction(ctx):
        restriction = await get_restriction()
        
        if restriction[str(ctx.channel.id)]["Server"] == 1:
            await ctx.send("This command is restricted. You can use it in the #bot-commands channel")
            return True
        return False
    

    In your code, you'd then use this modified function like so:

    if await check_server_restriction(ctx):  # the == True can be omitted
        print("Nicht perint")
        return