You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中能否将Embed存入函数复用?调用显示对象而非嵌入内容

解决discord.py中复用Embed对象时显示内存地址的问题

你遇到的问题核心是错误传递了Embed对象的字符串表示,而非直接使用Embed对象本身。以下是具体修正方案:

错误代码示例(还原常见问题场景)

_embeds.py(错误写法)

import discord

def get_welcome_embed():
    embed = discord.Embed(title="欢迎", description="欢迎加入服务器!", color=discord.Color.blue())
    return str(embed)  # 错误:返回了对象的字符串形式,而非Embed对象本身

main.py(错误调用)

import discord
from discord.ext import commands
from _embeds import get_welcome_embed

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.command()
async def welcome(ctx):
    await ctx.send(get_welcome_embed())  # 错误:直接发送字符串,而非通过embed参数传递对象

正确代码实现

_embeds.py(正确写法)

确保函数直接返回原始的discord.Embed对象,不要做字符串转换:

import discord

def get_welcome_embed():
    embed = discord.Embed(title="欢迎", description="欢迎加入服务器!", color=discord.Color.blue())
    embed.add_field(name="重要提示", value="请先阅读#服务器规则频道内容")
    embed.set_footer(text="祝你在服务器玩得开心!")
    return embed  # 直接返回Embed对象

main.py(正确调用)

调用send()方法时,必须通过embed=参数传入Embed对象:

import discord
from discord.ext import commands
from _embeds import get_welcome_embed

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.command()
async def welcome(ctx):
    # 获取复用的Embed对象,通过embed参数发送
    await ctx.send(embed=get_welcome_embed())

关键注意事项

  1. 返回对象而非字符串:复用函数的核心是返回discord.Embed实例,任何str(embed)或repr(embed)的转换都会导致发送内存地址字符串。
  2. 使用embed参数传递:ctx.send()的第一个参数是普通文本内容,Embed对象必须通过embed=关键字参数传递,否则会被当作普通文本处理。

进阶:动态生成可复用Embed

可以让函数接受参数,实现更灵活的复用:

# _embeds.py
def get_user_info_embed(user: discord.Member):
    embed = discord.Embed(title=f"{user.display_name}的个人信息", color=discord.Color.green())
    embed.set_thumbnail(url=user.avatar.url)
    embed.add_field(name="用户ID", value=user.id)
    embed.add_field(name="加入服务器时间", value=user.joined_at.strftime("%Y-%m-%d %H:%M:%S"))
    return embed

# main.py调用
@bot.command()
async def userinfo(ctx, member: discord.Member=None):
    member = member or ctx.author
    await ctx.send(embed=get_user_info_embed(member))

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:04:56