首页 > 解决方案 > 如何通过不和谐用户输入十六进制颜色以嵌入消息

问题描述

我正在尝试通过不和谐的用户十六进制颜色输入以在嵌入消息后放入,但他像字符串一样理解它,我该怎么做?现在,当我为颜色创建新变量时,我有了代码,代码很多。

@client.command()
async def embed(ctx):
    embed_question = discord.Embed(
        title="Enter a title of embed message: ",
        description="||This request will be canceled in 10 seconds!||"
    )
    embed1 = await ctx.send(embed=embed_question)
    try:
        msg = await client.wait_for("message", check=lambda message: message.author == ctx.author, timeout=10)
        msg_color = await client.wait_for("message", check=lambda message: message.author == ctx.author, timeout=10)
        r = msg_color.content.split(",", 3)[0]
        g = msg_color.content.split(",", 3)[1]
        b = msg_color.content.split(",", 3)[2]
        embed_question_answer = discord.Embed(
            title=msg.content.split("|", 1)[0],
            description=msg.content.split("|", 1)[1],
            color=discord.Color.from_rgb(int(r), int(g), int(b))
        )
        await ctx.send(embed=embed_question_answer)
        await msg_color.delete()
        await msg.delete()
        await embed1.delete()
        await ctx.message.delete()
    except asyncio.TimeoutError:
        timeout_embed = discord.Embed(
            title="",
            description="***Cancelling due to timeout.***",
            color=0x2f3136
        )
        await ctx.send(embed=timeout_embed, delete_after=5)
        await msg.delete()
        await embed1.delete()
        await ctx.message.delete()

标签: pythondiscord.py

解决方案


commands.ColourConverter您可以使用该类来实现这一点。虽然它是一个用于类型提示的转换器,但您可以调用 convert 方法来做同样的事情。

conv = commands.ColourConverter()
colour_object = await conv.convert(ctx, '#ffffff')

在这里,conv变量是可选的。#ffffff 可以是任何东西,甚至是变量,甚至是 msg_color.content。它接受您可以在文档中看到的多种格式的颜色,如果您太懒,这里是一个屏幕截图: 截屏

如您所见,commands.BadArgument如果转换失败,则会引发此问题。您可能也想抓住它并通知用户他们发送的颜色无效


推荐阅读