首页 > 解决方案 > UnboundLocalError:在分配局部变量“emoji_count”之前引用

问题描述

嗨,我在写作时遇到了一个 cog(机器人模块)的琐碎问题,我不断收到UnboundLocalError: Referenced before assignment我知道这是一个非常常见的问题,但我没有看到这个问题。

该模块可以工作,但是每次对帖子做出反应时,都会在控制台中抛出此错误。

错误是:

starboard.py", line 22, in on_reaction_add if emoji_count > 0: #if 0 then 1 counts UnboundLocalError: local variable 'emoji_count' referenced before assignment

我正在研究的更具体的领域是:

async def on_reaction_add(self, reaction, user):

    for guild in self.bot.guilds:
        chan = get(guild.channels, name="starboard")
        if chan:
            if reaction.message.author == user:
                return
            if reaction.emoji == '⭐' or reaction.emoji == '':
                if not chan:
                    return
                emoji_count = reaction.message.reactions[0].count
                msg = f"{reaction.message.author.mention} your post was posted to starboard." 
                em = discord.Embed(color=discord.Color(random.randint(0x000000, 0xFFFFFF)))
                display = f"""{reaction.message.content}"""
                em.description = display
                em.set_author(name=reaction.message.author.name, icon_url=reaction.message.author.avatar_url)
                em.set_footer(text=f"Posted in: #{chan.name}")
                em.timestamp = dt.datetime.utcnow()
            try:
                img_url = reaction.message.attachments[0].url
            except IndexError:
                img_url = None
            if not img_url:
                try:
                    img_url = reaction.message.embeds[0].url
                except IndexError:
                    img_url = None
            if img_url:
                em.set_image(url=str(img_url))
            if emoji_count > 0: #if 0 then 1 counts
                if not chan:
                    return
                await chan.send(msg)
                await chan.send(embed=em)

如果有人能告诉我这里发生了什么以及我哪里出错了,我将不胜感激。

标签: python-3.xattributesdiscorddiscord.pydiscord.py-rewrite

解决方案


当你的 if 语句条件if reaction.emoji == '⭐' or reaction.emoji == '':不返回True时, emoji_count 不会被初始化
emoji_count = reaction.message.reactions[0].count
所以当你尝试使用它时,它下面的几行if emoji_count > 0:会导致
local variable 'emoji_count' referenced before assignment,这正是它所说的,python 无法找到你的变量的初始化运行代码中的任何位置


推荐阅读