在 Discord.py 中使用异步创建和更改全局变量
Creating and changing global variable with async in Discord.py
有什么方法可以 1. 创建一个可以被不同 async def command(ctx, *, arg
命令使用的变量?比如
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")
所以我想要的是在启动时创建一个变量,然后可以 changed/edited and/or 添加到。
是的。您可以创建模块级变量并使用“全局”关键字访问它们,就像非异步函数一样。标准变量范围规则适用于任何其他 python 函数。由于您的问题并非特定于 discord
而我碰巧没有 discord
,我刚刚更新了一个标准的异步“hello world”程序。
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()
有什么方法可以 1. 创建一个可以被不同 async def command(ctx, *, arg
命令使用的变量?比如
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")
所以我想要的是在启动时创建一个变量,然后可以 changed/edited and/or 添加到。
是的。您可以创建模块级变量并使用“全局”关键字访问它们,就像非异步函数一样。标准变量范围规则适用于任何其他 python 函数。由于您的问题并非特定于 discord
而我碰巧没有 discord
,我刚刚更新了一个标准的异步“hello world”程序。
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()