【发布时间】:2018-10-03 06:59:14
【问题描述】:
您好,我在写作时遇到了一个 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)
如果有人能告诉我这里发生了什么以及我哪里出错了,我将不胜感激。
【问题讨论】:
-
如果反应不是星星之一,那么
emoji_count将没有那个if的值。您也可以通过reaction.message.guild获得公会的反馈。你不需要遍历所有你知道的公会。 -
对不起,我有点困惑,你可以给我一个例子。
-
如果我的代码中有
if False: x = 1,然后我尝试print(x),你认为会发生什么? -
我将如何解决此错误或如何传递数字。
#if 0 then 1 counts是添加到消息中的默认值。我认为 0 值意味着如果消息有0 emoji_count(没有表情符号),那么 1 星反应将添加到消息右舷。我很抱歉我对 py 很陌生。
标签: python-3.x attributes discord discord.py discord.py-rewrite