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

如何更简洁规范地编写discord.py的embed嵌入消息代码

优化discord.py Embed代码整洁度的方案

方案1:拆分构造参数 + 链式调用属性设置

discord.py的Embed对象支持链式调用单独设置各个字段,不需要把所有参数都塞进构造函数里,长内容可以单独换行写,可读性很高:

import discord

embed = discord.Embed(
    title="Ping",
    colour=discord.Colour.blue()
)
# 长描述单独设置,内容可以用Python括号隐式换行随意拆分
embed.description = (
    "my ping is currently something very long "
    "and it will take a lot of space for me to write "
    "all this information down"
)
# 后续加其他字段也可以分开处理
embed.add_field(name="服务器延迟", value="12ms", inline=False)

这种写法适合绝大多数常规场景,每个属性单独管理,修改某一项内容时不需要翻找构造函数里的参数,也不需要加冗余的字符串拼接符。

方案2:字典解包传参

如果Embed的内容是动态生成、或者字段特别多,可以先把所有参数存在字典里,再用**解包传入构造函数,代码结构会非常清晰:

import discord

embed_params = {
    "title": "Ping",
    "colour": discord.Colour.blue(),
    "description": (
        "my ping is currently something very long "
        "and it will take a lot of space for me to write "
        "all this information down"
    ),
    "fields": [
        {"name": "服务器延迟", "value": "12ms", "inline": False},
        {"name": "本地延迟", "value": "8ms", "inline": False}
    ]
}
embed = discord.Embed(**{k:v for k,v in embed_params.items() if k != "fields"})
for field in embed_params["fields"]:
    embed.add_field(**field)

这种写法尤其适合内容从配置文件、数据库、接口等外部来源读取的场景,所有内容可以统一存在字典里做校验、修改,再统一生成Embed,避免零散的赋值逻辑。

方案3:封装复用模板

如果有大量同类型的Embed,可以直接封装成工具函数,后续调用只需要传动态内容即可,能省大量重复代码:

import discord

def build_embed(title: str, description: str, **kwargs) -> discord.Embed:
    embed = discord.Embed(
        title=title,
        description=description,
        colour=discord.Colour.blue(),
        **kwargs
    )
    # 可以统一加公共内容,比如页脚、作者信息等
    embed.set_footer(text="公共页脚内容")
    return embed

# 调用的时候只需要传核心内容就行
embed = build_embed(
    title="Ping",
    description=(
        "my ping is currently something very long "
        "and it will take a lot of space for me to write "
        "all this information down"
    )
)

如果项目里有几十上百个同样式的Embed,用这种封装方法可以统一管理所有Embed的默认样式,后续改样式只需要改函数里的逻辑就行,不需要逐个修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:00:04