【问题标题】:discord.py on_member_update activity timediscord.py on_member_update 活动时间
【发布时间】: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


【解决方案1】:

在 if 语句中分配 start 变量,但在 elif 语句中使用 start 变量而不分配它。

您可能应该在第一行启动变量,例如“start = 0”

【讨论】:

  • 因为if game_after 总是在elif game_before 之前运行,我希望开始时间是game_after 的时间
  • 那么给 start 一个初始值就不会有问题了,因为初始值不会被使用。正如上面的评论所说,您还可以将变量定义为 None
  • 我在第一行启动了变量,但如果成员更改活动 start = 0 将每次运行
猜你喜欢
  • 2021-05-22
  • 2021-06-10
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多