【问题标题】:Creating and changing global variable with async in Discord.py在 Discord.py 中使用异步创建和更改全局变量
【发布时间】:2020-06-21 12:10:13
【问题描述】:

有什么方法可以 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")

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

【问题讨论】:

    标签: python python-3.x discord discord.py discord.py-rewrite


    【解决方案1】:

    是的。您可以创建模块级变量并使用“global”关键字访问它们,就像非异步函数一样。标准变量范围规则适用于任何其他 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()
    

    【讨论】:

    • 我试图将其加入我的代码中,但它仍然显示local variable 'baseNumberID' referenced before assignment
    • 您是否将global baseNumberID 包含在所有尝试重新分配它的函数的顶部?顺便说一句,我注意到baseNumberID =+ 1 只是将+1 分配给变量。递增是baseNumberID += 1
    • 如果需要,我稍后会展示一些,但如果您制作一个不和谐的机器人,您应该将任何您想要的作为全局变量作为bot 的属性。您应该检查一下它的使用情况,这样做也可以大大简化您的代码。 Here is the link
    • @EthanM-H - 这是对 OP 的 discord 代码的一个很好的观察。我只是关注一般的异步问题。
    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    相关资源
    最近更新 更多