EchoTheAlpha
EchoTheAlpha

Reputation: 422

Creating and changing global variable with async in Discord.py

Is there a way that I can 1. Create a variable that can be used by different async def command(ctx, *, arg commands? such as

import discord
import asyncio
from discord.ext import commands


@bot.command(pass_context=True)
async def on_ready():
    print('Bot is online and ready.')
    #creates the global variable called like "baseNumberID"
async def command(ctx, *, arg):
    baseNumberID =+ 1
bot.run("TOKEN")

So what i want, is to have a variable created on launch that can then be changed/edited and/or added on to.

Upvotes: 0

Views: 1264

Answers (1)

tdelaney
tdelaney

Reputation: 77407

Yes. You can create module level variables and access them with the "global" keyword just like a non-asyncio function. The standard variable scoping rules apply like any other python function. Since your question isn't specific to discord and I don't happen to have discord, I've just updated a standard asyncio "hello world" program.

import asyncio

foo = 0

async def say(what, when):
    await asyncio.sleep(when)
    global foo
    foo += 1
    print(what, foo)

loop = asyncio.get_event_loop()
loop.run_until_complete(say('hello world', 1))
loop.close()

Upvotes: 1

Related Questions