5

I'm making a Discord bot in Python using discord.py. I'd like to set/modify a global variable from an async thread.

message = ""

@bot.command()
async def test(ctx, msg):
    message = msg

However this doesn't work. How can I achieve something that does this?

Máté Varga
  • 121
  • 2
  • 11
  • What exactly do you mean by it doesn't work ? In another function the value is not reflected that you are setting in test ? The global variables should be available in async functions and the value would change. Most likely its getting overwritten somewhere else. – PraveenB Mar 17 '20 at 19:07
  • Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Ture Pålsson Mar 17 '20 at 19:07
  • @TurePålsson thanks for pointing it out and obviously you have to use the keyword global in all the functions wherever you are changing it . – PraveenB Mar 17 '20 at 19:17

1 Answers1

17

As I said in the comment you have to use the keyword global in the functions wherever you are modifying the global variable. If you are just reading it in function than you don't need it.

message = ""

@bot.command()
async def test(ctx, msg):
    global message
    message = msg
PraveenB
  • 1,042
  • 8
  • 11