You need to enable JavaScript to run this app. Discord.py中使用变量设置Embed颜色的类型错误问题
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py中使用变量设置Embed颜色的类型错误问题

报错原因与修复方法

报错根源

你从消息中读取的value是字符串类型,但discord.py的Embed.color参数仅接受三类合法值:discord.Colour实例、对应RGB色值的整数、discord.Embed.Empty空值,直接传入十六进制格式的字符串会触发类型校验错误。

具体修复步骤

  1. 格式转换:将用户输入的十六进制颜色字符串转换为库可识别的整数或discord.Colour实例
    可自动适配用户常见的输入场景,比如带#前缀、不带前缀、带0x前缀的hex格式,先清洗字符串前后的空白、去掉可选的前缀标识,再用内置方法转成16进制整数:
    raw_input = message.content.strip()
    # 清洗字符串,去掉可能存在的#或0x前缀
    clean_color_str = raw_input.lstrip('#').lstrip('0x')
    try:
        color_value = int(clean_color_str, 16)
    except ValueError:
        # 捕获非法输入,避免机器人崩溃
        await output.edit(content="请输入合法的十六进制颜色值,例如 #FF5733", embed=None)
        return
    
  2. 传入转换后的合法值初始化Embed
    embed = discord.Embed(
        title='Hey',
        description="How are you?",
        color=color_value
    )
    await output.edit(content=None, embed=embed)
    

简化方案(适配discord.py 2.0+版本)

高版本discord.py内置了字符串转颜色的工具方法,不需要手动写清洗逻辑,直接调用即可:

try:
    color_value = discord.Colour.from_str(message.content.strip())
except ValueError:
    await output.edit(content="颜色格式错误,请输入合法hex值", embed=None)
    return
embed = discord.Embed(title='Hey', description="How are you?", color=color_value)
await output.edit(content=None, embed=embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 01:24:08