【问题标题】:global variable not defined inside async function全局变量未在异步函数中定义
【发布时间】:2020-05-31 11:13:41
【问题描述】:

我有一个异步函数,它应该将反应添加到列表中,直到按下某个反应,然后它将添加所有适当的角色。为此,我有一个全局变量“reactions = []”,当按下“ok”反应时,它会被重置。 VS Code 在 "for react in reactions:" : "reactions is used before it is defined. Move the definition before." 行上告诉我这一点,这令人困惑,因为roleEmojis 是另一个全局变量,但它工作正常。 这是我的代码:

import os
import discord
import time
from discord.utils import get
from discord.ext import commands

token = "TOKEN"
BOT = commands.Bot("£")
reactions_list = []

@BOT.event
async def on_reaction_add(reaction , user):
    if reaction.emoji in roleEmojis.keys() and user != BOT.user:
        if reaction == get(reaction.message.guild.emojis, name = "OK"):
            for react in reactions_list:
                await user.add_roles(roleEmojis[react.emoji])
            reactions_list = []
        else:
            reactions_list.append(reaction)

BOT.run(token)

旁注:我还没有弄清楚如何检测某人何时对消息“未反应”,感谢那里的任何帮助

【问题讨论】:

    标签: python python-asyncio discord.py


    【解决方案1】:

    使用 global reactions 在你的本地方法中使用全局变量

    根据您提到的错误,您的错误在于 for 循环,我在代码片段中看不到。在 python 中,如果您使用全局变量,则需要明确提及。 (除非它是一个列表并且您通过函数参数或任何其他使用地址的数据类型使用它)。

    前-

    a=0
    def b():
        a=1
    b()
    print(a)
    

    结果为 0

    a=0
    def b():
        global a
        a=1
    b()
    print(a)
    

    结果为 1

    【讨论】:

      【解决方案2】:

      除了全局变量之外,您还可以创建可从任何地方访问的变量,如下所示:

      BOT = commands.Bot("£")
      BOT.reactions_list = []
      
      @BOT.event
      async def on_reaction_add(reaction , user):
          print(BOT.reactions_list) # proves it's accessible from anywhere
          # rest of your code
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 2011-08-12
        • 2022-11-22
        • 1970-01-01
        相关资源
        最近更新 更多