【问题标题】:Delete all the bot's messages in a channel删除频道中所有机器人的消息
【发布时间】:2018-05-16 09:00:30
【问题描述】:

我正在尝试在我的机器人中创建一个仅删除所有机器人消息的命令。有没有办法遍历所有频道的消息,如果它是机器人发送的消息,机器人会删除它?我已经理解delete_message,但我不知道如何遍历所有频道的消息,如果可能的话。 以下代码不会遍历所有频道的消息,但如果作者 ID 为 383804325077581834,它将删除该消息:

@bot.event
async def on_message(message):
    if message.author.id == '383804325077581834':
        await bot.delete_message(message) 

383804325077581834 是我的机器人 ID。所以我想知道如何遍历所有频道消息并删除那些由我的机器人发送的消息。非常感谢!

编辑:尝试这样做:

@bot.command(pass_context=True)
async def delete(ctx, number):
    msgs = []
    number = int(number)
    async for msg in bot.logs_from(ctx.message.channel, limit=number):
        if msg.author.id == '383804325077581834':
            msgs.append(msg)
        await bot.delete_messages(msgs)

但我收到错误 discord.ext.commands.errors.MissingRequiredArgument: number is a required argument that is missing.

【问题讨论】:

    标签: python-3.x discord.py


    【解决方案1】:
    @bot.command(pass_context=True)
    async def delete(ctx):
        msgs = []
        async for msg in bot.logs_from(ctx.message.channel):
            if msg.author.id == '383804325077581834':
                msgs.append(msg)
            await bot.delete_messages(msgs)
    

    您尝试使用的命令需要一个数字参数,该参数将从频道中删除该数量的消息。
    如果没有传入限制,logs_from 函数将删除该通道中的所有消息。

    编辑:忘记删除号码,哎呀。

    【讨论】:

    • 谢谢。但现在我收到错误UnboundLocalError: local variable 'number' referenced before assignment
    • 如果您想删除所有消息,则不需要该号码,这样您就可以摆脱该行。
    猜你喜欢
    • 2018-06-29
    • 2018-04-29
    • 1970-01-01
    • 2020-03-08
    • 2020-12-23
    • 2021-05-14
    • 2020-10-26
    • 1970-01-01
    • 2020-08-24
    相关资源
    最近更新 更多