首页 > 解决方案 > 尝试接收在不同命令中创建的特定通道内的所有消息

问题描述

我目前正在编写一个机器人,它允许两个人在全球范围内、在服务器内、在单个帐户上或对机器人下棋。目前,我这样做的方法涉及一个匹配算法(这不是最复杂的),然后它创建一个供玩家输入消息的通道,或者在全球游戏的情况下,在不同的服务器上创建两个带有 webhook 的通道。我的问题是:每当在这些渠道之一中发送消息时,我将如何运行代码?具体来说,我需要通过全球游戏中的 webhook 将在一个通道中发送的每条消息的副本发送到另一个通道,以便双方玩家可以交流并检查输入消息是否为移动格式,在这种情况下bot 会进行移动并将消息复制到另一个频道。我曾想过使用

@bot.event
async def on_message(mes)

但我不能在全局范围内这样做,因为在全局范围内不知道检查消息的通道,而且我不知道它是否可以在函数中以可以检查通道的方式定义。谢谢!

标签: pythonpython-3.xdiscord.pydiscord.py-rewrite

解决方案


@bot.event
async def on_message(message):
    if message.channel.id in my_list_of_channel_ids:
        # It's a chess channel
        # Now you can check if the message contains a valid move

或者你可以使用bot.wait_for

# The `is_game_over` var indicates if the game is over
while not is_game_over:
    def check(message):
        """Checks if the message contains a valid move,

        you should also check if `message.author == `ctx.author` 
        if you're doing this in a command

        and if message.channel is the same as the channel you created before"""

        return message.content.upper() in ['A1', 'A2', 'A3'] # Put all the valid moves here

    message = await bot.wait_for('message', check=check)
    # from here do your thing, add the moves, check if someone won the game, etc...

如果没有您当前拥有的代码片段,就无法更具体


推荐阅读