【发布时间】:2021-04-26 09:18:03
【问题描述】:
我正在努力抽出时间参加一项活动(玩英雄联盟)。
但我不断收到此错误UnboundLocalError: local variable 'start' referenced before assignment
@commands.Cog.listener()
async def on_member_update(self, before, after):
game_after = [i for i in after.activities if str(i.type) == "ActivityType.playing" and str(i.name) == "League of Legends"]
game_before = [i for i in before.activities if str(i.type) == "ActivityType.playing" and str(i.name) == "League of Legends"]
if game_after:
print(game_after)
start = time.time()
elif game_before and not game_after:
end = time.time()
total = end - start
print(total)
我试过这样做,但现在如果一个成员开始玩联赛,start = time.time() 运行,然后当他们停止玩时,它会运行start = 0 然后elif game_before 所以total 将与结束时间相同
async def on_member_update(self, before, after):
game_after = [i for i in after.activities if str(i.type) == "ActivityType.playing" and str(i.name) == "League of Legends"]
game_before = [i for i in before.activities if str(i.type) == "ActivityType.playing" and str(i.name) == "League of Legends"]
start = 0
if game_after:
start = time.time()
elif game_before:
end = time.time()
total = end - start
hours, rem = divmod(total, 3600)
minutes, seconds = divmod(rem, 60)
print("{:0>2}:{:0>2}:{:0>2}".format(int(hours),int(minutes),seconds))```
【问题讨论】:
-
start仅在game_after为 True 时被引用。尝试将start设置为 None 或 if 之外的默认值。此外,您不需要在 elif 检查中将not game_after作为它的 elif,并且只有在第一个 if 不为真时才会执行。另一件事,我看到您正在尝试打印用户玩游戏的时间。您必须将start保存到 json 文件、数据库或使其成为全局,以便在用户更改活动时再次使用它。 -
是的,因为我希望
start在他们开始活动时出现。
标签: python-3.x discord.py