discord.py机器人如何在on_ready事件中通过消息ID编辑embed并解决报错
报错问题修复
你遇到的AttributeError: 'Bot' object has no attribute 'get_message'报错是因为discord.py v1.0之后就移除了Bot实例的get_message方法,正确的获取指定ID消息的方式是先获取消息所在的频道对象,再调用频道的fetch_message协程方法请求API获取消息。
修复后的基础代码如下:
import os # 你原代码漏了导入os,否则调用os.environ会报错 from discord.ext import commands import discord # 注意要根据需求开启对应意图,读消息需要开启消息内容意图,可在Discord开发者后台配置 bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.event async def on_ready(): # 替换为你的消息所在的频道ID channel = await bot.fetch_channel(你的频道ID) # 获取目标消息 msg = await channel.fetch_message(892788147287654471) em = discord.Embed(title="lik",description="kjk") await msg.edit(embed=em) print(f"已登录为 {bot.user}") bot.run(os.environ['token'])
实现长期运行的后台函数
你可以使用discord.py内置的tasks.loop装饰器实现后台循环运行的任务,任务会一直运行直到机器人程序终止,非常适合定时更新embed这类需求。
示例代码如下(以每5分钟更新一次embed为例):
import os import asyncio from discord.ext import commands, tasks # 导入tasks模块 import discord bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # 定义循环任务,可自定义运行间隔,支持seconds/minutes/hours参数 @tasks.loop(minutes=5) async def update_embed_task(): channel = await bot.fetch_channel(你的频道ID) msg = await channel.fetch_message(892788147287654471) # 可自定义动态生成embed的逻辑 new_embed = discord.Embed(title="动态更新标题", description=f"当前更新时间:{discord.utils.utcnow()}") await msg.edit(embed=new_embed) @bot.event async def on_ready(): # 机器人完全启动后再启动任务,避免资源未加载完成导致报错 update_embed_task.start() print(f"已登录为 {bot.user},embed更新任务已启动") bot.run(os.environ['token'])
补充注意事项
- 如果不需要定时间隔,要任务连续运行,可以在任务函数内写
while True逻辑,注意必须加await asyncio.sleep(xx)避免阻塞机器人事件循环,否则机器人会无响应。 - 需要停止任务时调用
update_embed_task.stop()方法即可。
内容的提问来源于stack exchange,提问作者thinker 010
相关产品推荐
相关产品推荐

