0

So, I´m making a discord.py bot and i want to create a /daily command. But I need to use a variable inside a function declared outside of the function. Here's my code so far:

global d
d = 0
@tree.command(name = "daily", description = "Daily sallary.")
async def daily(interaction: discord.Interaction):
    if d == 0:
        await interaction.response.send_message("Yes")
        d = 1
        await asyncio.sleep(86400)
        d = 0
    else:
        await interaction.response.send_message("No")

The d variable is not working inside of the function and it throws out this error: UnboundLocalError: cannot access local variable 'd' where it is not associated with a value Anyone has an idea of how to do this?

I have tried this:

global d
d = 0
@tree.command(name = "daily", description = "Daily sallary.")
async def daily(interaction: discord.Interaction, **d=d**):
    if d == 0:
        await interaction.response.send_message("Yes")
        d = 1
        await asyncio.sleep(86400)
        d = 0
    else:
        await interaction.response.send_message("No")

but.... It doesn't work and again there's an error: TypeError: parameter 'd' is missing a type annotation in callback 'daily'

TheLiveYT
  • 3
  • 1
  • 1
    Out of context, but why are you not using the cooldown decorator the library provides? `await asyncio.sleep(86400)` is just a bad approach in this case. You will also have it much easier if you store everything in a dict if you only need it temporarily (`{user_id: last_usage}` -> or something else) – Dominik May 30 '23 at 15:27
  • I don't think that is a good idea, because it would reset the timer every time the user uses it. But something else should work. – TheLiveYT Jun 02 '23 at 11:24
  • The cooldown decorator does not reset, rather returns the time left until the 24 hours for the specific user are over! – Dominik Jun 02 '23 at 17:35

1 Answers1

0

You need to move global d to inside the function definition

d = 0
@tree.command(name = "daily", description = "Daily sallary.")
async def daily(interaction: discord.Interaction):
    global d
    if d == 0:
        await interaction.response.send_message("Yes")
        d = 1
        await asyncio.sleep(86400)
        d = 0
    else:
        await interaction.response.send_message("No")
JRiggles
  • 4,847
  • 1
  • 12
  • 27