在 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")

所以我想要的是在启动时创建一个变量,然后可以更改/编辑和/或添加该变量。

是的。您可以创建模块级变量并使用"global"关键字访问它们,就像非异步函数一样。标准变量范围规则与任何其他 python 函数一样适用。由于您的问题不是特定于discord的,而且我碰巧没有discord,因此我刚刚更新了一个标准的asyncio"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()

最新更新