Discord机器人如何接收用户输入的hex颜色值设置embed消息颜色
要实现hex颜色值解析、同时简化冗余代码,你可以直接使用discord.py内置的颜色转换方法,不需要手动拆分RGB值,优化后的实现如下:
完整优化代码
import discord import asyncio from discord.ext import commands client = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @client.command() async def embed(ctx): embed_question = discord.Embed( title="请输入embed消息的标题和描述,用|分隔:", description="||该请求将在10秒后自动取消||" ) prompt_msg = await ctx.send(embed=embed_question) try: # 接收标题+描述输入 content_msg = await client.wait_for("message", check=lambda m: m.author == ctx.author and "|" in m.content, timeout=10) # 拆分一次就可以复用结果,不需要重复split title, desc = content_msg.content.split("|", 1) # 接收颜色输入 color_prompt = discord.Embed(title="请输入颜色值,支持hex格式(如#ff0000、ff0000)或RGB格式(如255,0,0)", description="||该请求将在10秒后自动取消||") color_prompt_msg = await ctx.send(embed=color_prompt) color_msg = await client.wait_for("message", check=lambda m: m.author == ctx.author, timeout=10) # 直接用内置方法解析颜色,自动适配hex、rgb格式 embed_color = discord.Color.from_str(color_msg.content.strip()) # 生成最终embed final_embed = discord.Embed( title=title.strip(), description=desc.strip(), color=embed_color ) await ctx.send(embed=final_embed) # 清理临时消息 await content_msg.delete() await color_msg.delete() await color_prompt_msg.delete() await prompt_msg.delete() await ctx.message.delete() except asyncio.TimeoutError: timeout_embed = discord.Embed( title="", description="***请求超时,已自动取消***", color=0x2f3136 ) await ctx.send(embed=timeout_embed, delete_after=5) # 超时场景按需清理已存在的消息,避免报错 for msg in [prompt_msg, ctx.message]: try: await msg.delete() except: pass
优化说明
- 核心使用
discord.Color.from_str()方法自动解析颜色字符串:该方法原生支持带/不带#的hex颜色格式,也兼容你原来的逗号分隔RGB格式,不需要单独定义r/g/b三个冗余变量,也不用手动做类型转换 - 减少重复的字符串拆分操作:同一个输入内容只拆分一次,复用结果降低冗余
- 增加了基础输入校验:要求标题描述输入必须包含分隔符
|,避免后续拆分报错 - 优化了异常处理逻辑:超时场景清理消息时增加容错,避免未收到对应消息时抛出二次异常
内容的提问来源于stack exchange,提问作者Witalik Zarscikov
相关产品推荐
相关产品推荐

