You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在discord.py中删除机器人发送的消息

嘿,我来帮你搞定这个问题!其实删除机器人自己发送的消息,核心就是先保存机器人发消息时返回的消息对象引用,之后等冷却时间到了,用这个引用调用删除方法就行,和删除用户消息的逻辑本质是相通的~

具体实现步骤(以discord.py为例)

1. 保存机器人发送的消息对象

当机器人通过ctx.send()或者channel.send()发送消息时,这些方法会返回一个Message对象——这个对象就是机器人刚发出去的那条消息,一定要把它存下来,这是后续删除的关键。

2. 等待冷却时间后执行删除

asyncio.sleep()等待你设定的冷却时长,之后调用消息对象的delete()方法就能删掉机器人自己的消息了。

完整代码示例

import asyncio
import discord
from discord.ext import commands

# 初始化机器人,记得开启必要的intents
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@bot.command(name="send_random")
async def send_random_message(ctx):
    # 发送消息并保存返回的Message对象
    bot_sent_msg = await ctx.send("这是一条机器人随机发送的消息,10秒后会自动删除~")
    
    # 等待设定的冷却时间(这里是10秒)
    await asyncio.sleep(10)
    
    # 删除机器人自己的消息
    await bot_sent_msg.delete()

# 处理消息已被手动删除的异常情况(可选但推荐)
@bot.command(name="send_safe")
async def send_safe_message(ctx):
    bot_sent_msg = await ctx.send("这条消息即使被手动删了,机器人也不会报错~")
    await asyncio.sleep(10)
    try:
        await bot_sent_msg.delete()
    except discord.NotFound:
        # 消息已经不存在,跳过删除操作
        print("消息已被提前删除,无需执行删除")

bot.run("你的机器人令牌")

其他场景的适配

如果是在非命令上下文的场景(比如定时发送消息到某个频道),逻辑也是一样的:

# 假设你已经获取到目标频道的channel对象
target_channel = bot.get_channel(123456789012345678)
bot_sent_msg = await target_channel.send("频道定时消息,15秒后删除")
await asyncio.sleep(15)
await bot_sent_msg.delete()

内容的提问来源于stack exchange,提问作者christopherson

火山引擎 最新活动