
在 discord.py 机器人开发中,将 Discord Embed 消息的创建逻辑封装到单独的函数或模块中是一种推荐的做法。这种模块化设计带来了多重好处:
开发者在尝试将函数返回的 discord.Embed 对象发送到 Discord 频道时,常会遇到一个问题:消息中显示的是 <discord.embeds.Embed object at 0x00000219A7514CA0> 这样的对象字符串,而不是渲染后的精美 Embed 消息。
这通常发生在以下情况:
# _embeds.py (假设这是一个独立文件,用于定义Embed创建函数)
import discord
from datetime import datetime
def setting_update_success(setting, value):
embed = discord.Embed(title="成功!",
description=f"设置 `{setting}` 已更新为 `{value}`。",
colour=0x19e63b,
timestamp=datetime.now())
# 示例中的作者和页脚可以根据实际需求添加或省略
# embed.set_author(name="Chix", icon_url="attachment://chix_full.png")
# embed.set_footer(text="发送成功")
return embed
# main.py (在主程序中调用)
import discord
# 假设 messages 是 _embeds.py 模块的别名
# from _embeds import setting_update_success as messages # 实际导入方式
# 或者直接导入整个模块
import _embeds as messages
async def send_message_incorrectly(channel: discord.TextChannel):
# 错误示例:直接将函数调用结果作为 channel.send() 的第一个参数
await channel.send(messages.setting_update_success("通知", "开启"))上述代码的问题在于 channel.send() 方法的第一个参数默认是用于发送普通文本消息的。当您传入一个 discord.Embed 对象时,Python 会将其转换为字符串表示形式,而不是将其作为 Embed 消息发送。
discord.py 的 TextChannel.send() 方法提供了一个名为 embed 的关键字参数,专门用于发送 discord.Embed 对象。要正确发送 Embed 消息,您需要将函数返回的 Embed 对象赋值给这个参数。
# main.py (在主程序中调用)
import discord
import _embeds as messages # 假设 _embeds.py 模块已导入
async def send_message_correctly(channel: discord.TextChannel):
# 正确示例:使用 embed 关键字参数
await channel.send(embed=messages.setting_update_success("通知", "开启"))通过使用 embed= 参数,discord.py 知道您要发送的是一个嵌入式消息,并会正确地对其进行处理和渲染。
为了更好地展示如何组织代码,以下是一个更完整的示例,包括一个独立的 _embeds.py 文件和一个 main.py 文件。
_embeds.py 文件内容:
import discord
from datetime import datetime
def create_success_embed(setting: str, value: str) -> discord.Embed:
"""
创建一个表示设置更新成功的 Embed 消息。
Args:
setting (str): 被更新的设置名称。
value (str): 设置更新后的值。
Returns:
discord.Embed: 构建好的 Embed 对象。
"""
embed = discord.Embed(
title="操作成功!",
description=f"设置 `{setting}` 已成功更新为 `{value}`。",
colour=discord.Colour.green(), # 使用 discord.Colour 枚举更清晰
timestamp=datetime.now()
)
# 可以添加作者、缩略图、图片、字段等
# embed.set_author(name="机器人助手", icon_url="URL_TO_YOUR_BOT_AVATAR")
# embed.add_field(name="详情", value="更多信息可以在这里添加。", inline=False)
return embed
def create_error_embed(error_message: str) -> discord.Embed:
"""
创建一个表示操作失败的 Embed 消息。
Args:
error_message (str): 错误信息。
Returns:
discord.Embed: 构建好的 Embed 对象。
"""
embed = discord.Embed(
title="操作失败!",
description=f"发生错误:{error_message}",
colour=discord.Colour.red(),
timestamp=datetime.now()
)
return embedmain.py 文件内容:
import discord
from discord.ext import commands
import _embeds # 导入包含 Embed 函数的模块
# 假设您的机器人令牌
TOKEN = "YOUR_BOT_TOKEN"
# 创建一个 Bot 实例
intents = discord.Intents.default()
intents.message_content = True # 如果需要读取消息内容
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Bot 已登录为 {bot.user}')
@bot.command(name='set')
async def set_command(ctx, setting: str, value: str):
"""
一个示例命令,用于模拟设置更新并发送成功或失败的Embed。
使用方法: !set <设置名称> <值>
"""
try:
# 模拟一些业务逻辑,例如将设置保存到数据库
print(f"尝试更新设置: {setting} 为 {value}")
# 假设更新成功
success_embed = _embeds.create_success_embed(setting, value)
await ctx.send(embed=success_embed) # 正确发送 Embed
except Exception as e:
# 假设更新失败
error_embed = _embeds.create_error_embed(f"无法更新设置:{e}")
await ctx.send(embed=error_embed) # 正确发送 Embed
@bot.command(name='test_error')
async def test_error_command(ctx):
"""
测试发送错误 Embed 的命令。
"""
error_embed = _embeds.create_error_embed("这是一个模拟的错误信息。")
await ctx.send(embed=error_embed)
# 运行机器人
if __name__ == '__main__':
bot.run(TOKEN)在这个示例中,main.py 通过 import _embeds 导入了包含 Embed 创建函数的模块。然后,在命令处理函数中,我们调用 _embeds.create_success_embed() 或 _embeds.create_error_embed() 来获取 Embed 对象,并使用 await ctx.send(embed=...) 来正确发送它们。
将 discord.Embed 对象的创建逻辑封装到函数中是提高 discord.py 机器人代码质量的有效方法。核心要点在于,当您从函数中获取一个 discord.Embed 对象并希望将其发送到 Discord 频道时,务必使用 channel.send() 方法的 embed 关键字参数。通过遵循这一简单而关键的原则,您可以确保您的机器人能够清晰、专业地展示信息,从而提升用户体验。
以上就是discord.py 中函数返回 Embed 对象的正确发送方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号