【问题标题】:check if a specific message is still in the channel? - Discord.py检查特定消息是否仍在频道中? - 不和谐.py
【发布时间】:2021-11-28 01:03:11
【问题描述】:

我一直在为我的 discord 机器人创建一个 connect 4 游戏,游戏本身运行良好, 但是如果有人删除了包含棋盘和用户玩游戏的反应的消息,游戏将开始中断并且无法正常运行,直到有人重新启动机器人:

turn = 0 #switches between 0 and 1 during the game

game_over = False
while not game_over:
    try:

        reaction, user = await client.wait_for("reaction_add", check = check)
        if turn == 0:
            #do stuff depending on what the emoji reaction is
            if winning move():
                game_over = True
        else:
            #do stuff depending on what the emoji reaction is
            if winning_move():
                game_over = True
        #more things that aren't necessary to show

在有人删除消息和/或检查消息是否已被删除并通过它将变量更改为 True 后,我有没有办法将 game_over 更改为 True? 例如:

#If the board's not in the channel:
  await message.channel.send("Board was not found")
  game_over = True

任何帮助将不胜感激!

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    您可以使用asyncio.wait() 函数。 请参阅下面的示例,其中我实现了简单的小游戏逻辑。

    @client.command()
    async def mini_game(ctx):
        message = await ctx.send("test message")  # send first message
        done, pending = await asyncio.wait(
            [
                asyncio.create_task(client.wait_for("reaction_add", check=your_check)),  # specify `your_check` function
                asyncio.create_task(client.wait_for("message_delete", check=lambda m: m == message))
            ],
            return_when=asyncio.FIRST_COMPLETED,
            timeout=30  # you can specify timeout here
        )
        if done == set():
            pass  # if time limit exceeded
        else:
            coro = done.pop().result()
            try:
                reaction, member = coro  # if user `member` has added `reaction`
            except TypeError:
                pass  # if message has been deleted
    

    您可以调整此代码以满足您的需要。

    【讨论】:

      【解决方案2】:

      您可以通过简单地尝试获取带有删除前 id 的消息来检查消息是否已被删除。如果这返回 NotFound 错误,则该消息已被删除:

      def is_message_deleted(ctx, message_id):
          try:
              await ctx.fetch_message(message_id) #try to fetch the message
              return False
          except discord.error.NotFound: #if a NotFound error appears, the message is either not in this channel or deleted
              return True
      

      然后你可以在你的代码中包含这个函数:

      if is_message_deleted(ctx, board_message.id):
          await message.channel.send("Board was not found")
          game_over = True
      

      参考资料:

      【讨论】:

        猜你喜欢
        • 2019-11-05
        • 2021-01-19
        • 1970-01-01
        • 1970-01-01
        • 2021-04-15
        • 1970-01-01
        • 1970-01-01
        • 2021-07-01
        • 2020-11-06
        相关资源
        最近更新 更多