【问题标题】:How to make bot respond to a certain msg?如何让机器人响应某个消息?
【发布时间】:2018-10-17 08:50:27
【问题描述】:

所以,我一直试图让我的机器人响应特定的关键字,但是当我这样做时,机器人要么不响应,要么给我一堆错误。我已经尝试了一些方法来做到这一点,但我没有太多运气。如果有人能让它发挥作用,我会很高兴这是我尝试使用的方法之一。

    if message.content == "keyword":
    await client.send_message(message.channel, "Response {0.author.mention}")

【问题讨论】:

    标签: discord.py


    【解决方案1】:

    您可以通过命令扩展或在on_message 事件中使用以下两种方式之一来执行此操作。

    以下是如何执行此操作的示例。在此示例中,当用户键入“!ping”时,机器人将响应“Pong”。如果消息中包含单词“foo”,那么机器人将响应“bar”。

    from discord.ext import commands
    
    client = commands.Bot(command_prefix='!')
    
    @client.event
    async def on_ready():
        print('client ready')
    
    @client.command()
    async def ping():
        await client.say('Pong')
    
    @client.event
    async def on_message(message):
        if client.user.id != message.author.id:
            if 'foo' in message.content:
                await client.send_message(message.channel, 'bar')
    
        await client.process_commands(message)
    
    client.run('TOKEN')
    

    【讨论】:

    • 这太棒了!但是,当我使用此示例时,机器人会自行响应。例如我做了@client.event async def on_message(message): if 'test' in message.content: await client.send_message(message.channel, 'testing') bot 自己响应,一个接一个地重复创建垃圾邮件文本有没有办法解决这个问题?
    • on_message 事件触发每条消息,包括从机器人发送的消息。如果它是来自机器人的消息,则必须检查代码不执行的位置。我用一个例子更新了我的代码。
    • 我真的很抱歉问了太多问题:P 但我对编码真的很陌生,所以请在这里与我裸露,我尝试了你的示例并将 message.author.id 替换为我的机器人id,但是我有点卡住了。我确实 await client.delete_message(message) 所以它会删除它。但它再次做同样的事情,我的问题是,我应该让我的机器人做什么?
    • 您无需更换任何东西即可使上述工作。 client.user.id 已经是您的机器人 ID。然后,代码会根据message.author.id(发送消息的用户的 ID)对其进行检查。如果两者不相等(使用!=),则意味着bot没有发送消息,因此它可以继续执行其余代码
    猜你喜欢
    • 2021-07-19
    • 2019-11-23
    • 1970-01-01
    • 2021-04-09
    • 2017-08-28
    • 2021-11-28
    • 2021-04-09
    • 2020-11-26
    • 2019-10-29
    相关资源
    最近更新 更多