0

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.

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

I tried to incoperate this into my code, and it still says local variable 'baseNumberID' referenced before assignment
Did you include global baseNumberID at the top all functions that try to reassign it? As an aside, I noticed baseNumberID =+ 1 which just assigns +1 to the variable. Incrementing is baseNumberID += 1.
I will show some later if wanted, but if your making a discord bot you should make anything you want as a global variable an attribute of bot. You should check this out for usage on it, doing it this way also simplifies your code a fair bit. Here is the link
@EthanM-H - that's a good observation for OP's discord code. I was just focusing on the general async question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.