如何使用discord.py/py-cord发送可后续修改的消息?
解决Discord机器人发送可修改消息的AttributeError问题
你遇到的问题根源是Discord.py的send()方法是异步协程,直接赋值给message得到的是协程对象,而非实际的Message实例,自然没有edit或delete这类方法。
修复需要两个关键调整:
- 在调用异步方法时必须使用
await关键字,获取实际的消息对象 - 不能用阻塞式的
time.sleep(),要改用异步的asyncio.sleep()避免卡住机器人事件循环
修复后的代码示例:
import asyncio async def send_editable_message(bot, channel_id): channel = bot.get_channel(channel_id) # 用await获取实际的Message对象 message = await channel.send("deleting in 5s") # 异步等待,不阻塞事件循环 await asyncio.sleep(5) # 现在可以正常调用edit或delete方法 await message.edit(content="即将删除...") await asyncio.sleep(2) await message.delete()
另外要注意,这个函数必须在异步上下文中调用,比如在机器人的命令或事件回调里(这些本身就是异步函数)。示例如下:
import discord from discord.ext import commands bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @bot.command() async def test(ctx): message = await ctx.send("deleting in 5s") await asyncio.sleep(5) await message.edit(content="修改后的内容") await asyncio.sleep(2) await message.delete() bot.run("你的机器人令牌")
内容的提问来源于stack exchange,提问作者Pilonyen
相关产品推荐
相关产品推荐

