【问题标题】:How to make Discord.py respond to a single message event twice如何让 Discord.py 两次响应单个消息事件
【发布时间】:2021-06-02 19:29:38
【问题描述】:

我有一个不和谐的机器人,它可以读取频道中的所有消息,并将每条消息添加到 .txt 文件中的一行,然后回复确认。然后我想让机器人等待 10 秒,然后删除原始消息和响应。我有可以使这项工作的代码。我在我的测试机器人上按预期一起工作。但是,当我将代码复制到我的主机器人时,它无法工作,我的测试机器人也不再工作。我发布的代码是测试机器人,现在它只按预期删除原始消息。如果您遗漏第二个@bot.event 块,它会按预期响应并记录消息。我怎样才能让这两个发生在同一个机器人上? (请求通道位来自失败的尝试让代码指定机器人在哪个通道中操作,而不是仅仅在不和谐中单独关闭每个通道)。两个机器人都在不同的渠道中,所以我不认为是机器人的行为相互干扰?

import discord
from discord.ext import commands
import asyncio

requestsChannelID = 'CHANNELID'

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    with open('requests.txt', 'a') as f:
        print(repr(message.content), file=f)
    await message.channel.send('Got it!')
    
@bot.event
async def on_message(message):
    await asyncio.sleep(10)
    if str(message.channel) == "requests" and message.content != "":
        await message.channel.purge(limit=1)

bot.run('TOKEN')

【问题讨论】:

  • 我认为您必须将 on_message 的逻辑组合到一个函数中,因为现在看起来您有 2 个同名函数。
  • 我有过这样的想法。我如何将其合并到现有的 ```if```` 语句中。因为我希望机器人在响应和日志记录方面忽略自己,但将自己包含在删除中。并且删除需要在 if 语句之后进行。这种混乱就是它分离出来的原因。感谢您的帮助!
  • 我看到的一件事是你应该拥有await bot.process_commands(message)discordpy.readthedocs.io/en/latest/…
  • 您可以通过检查 ID 来限制机器人对自身的响应。 注意 Bot 没有这个问题 discordpy.readthedocs.io/en/latest/api.html#discord.on_message 这表明你不必检查bot.user
  • 在第二个on_message事件中,如果消息不为空,您正在检查内容是否为空,这没有任何意义,discord不允许您发送空消息跨度>

标签: python python-3.x discord discord.py bots


【解决方案1】:

您可以使用discord.Message.delete 专门删除请求和回复,无需使用清除(当在 10 秒的时间范围内有多条消息时,这很快变得非常复杂)

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    # ignore all channels but the specified one
    if message.channel.id == requestsChannelID:
        # record request
        with open('requests.txt', 'a') as f:
            print(repr(message.content), file=f)
        reply = await message.channel.send('Got it!')

        # wait for 10 seconds, then delete message and reply
        await asyncio.sleep(10)
        await message.delete()
        await reply.delete()
    else:
        # process other commands (if there are none, delete this line)
        await bot.process_commands(message)

请注意,此实现假定请求通道中没有命令(无论如何,据我了解,这就是您的意图)

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 2021-11-28
    • 2018-10-17
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2021-08-23
    相关资源
    最近更新 更多