python-3.x - 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)
如果有人能告诉我这里发生了什么以及我哪里出错了,我将不胜感激。
解决方案
当你的 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 无法找到你的变量的初始化运行代码中的任何位置
推荐阅读
- ios - IOS 应用程序从 Xcode 在 iPhone 上启动时崩溃
- javascript - 通过从同一页面内的链接调用其锚 id 来扩展手风琴?
- mysql - MySQL XDevAPI 如何返回成功状态
- sql-server - 使用 SSRS MAX 函数时消除一些大值
- java - 如何从 2 个不同的 Spring Boot 应用程序访问相同的数据库
- reactjs - Apollo-Client 中的 dotenv 不起作用
- python - 在 Python 3.7/Django 3 中,如何在 Web 浏览器中获取页面的呈现 HTML?
- c# - 执行此 sql 查询时如何只获得一个值?
- r - 如何在 rmarkdown 代码块中解析文本表
- javascript - 如何使用引导程序使表格内的单选按钮看起来像一个按钮?