用Python编写Discord机器人- 如何使嵌入具有随机颜色?

3

我想让机器人发送嵌入式消息时,颜色是随机的。这是我的代码:

colors = ['0xFFE4E1', '0x00FF7F', '0xD8BFD8', '0xDC143C', '0xFF4500', '0xDEB887', '0xADFF2F', '0x800000', '0x4682B4', '0x006400', '0x808080', '0xA0522D', '0xF08080', '0xC71585', '0xFFB6C1', '0x00CED1']

@client.command(help='Shares a meme')
async def meme(ctx):
    subreddit = reddit.subreddit("dankmemes")
    all_subs = []
    top = subreddit.top(limit = 75)

    for submission in top:
      all_subs.append(submission)
  
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    em = discord.Embed(title = name, color = random.choice(colors))

    em.set_image(url = url)
    await ctx.send(embed = em)

我遇到了这个错误:TypeError: 预期 discord.Colour、int 或 Embed.Empty,但实际收到的是 str。

不确定如何修复它,有什么提示吗?

3个回答

5

我猜,一定是这样

colors = [0xFFE4E1, 0x00FF7F, 0xD8BFD8, 0xDC143C, 0xFF4500, 0xDEB887, 0xADFF2F, 0x800000, 0x4682B4, 0x006400, 0x808080, 0xA0522D, 0xF08080, 0xC71585, 0xFFB6C1, 0x00CED1]

我简直不敢相信我没想到这个哈哈。它起作用了,谢谢你的帮助! - Carter Michaelis
这是因为Python将十六进制字面量解释为整数,这是discord.Color类的默认输入,所以它可以正常工作。 - Aaron

5
正如您的错误信息所示,类discord.Embed不接受字符串作为color关键字参数的有效输入。它必须是类的实例:discord.Color
有几种方法可以完成您的任务:
  • 将颜色作为整数传递discord.Colour(value)
  • 将颜色作为单独的r、g、b值传递:discord.Colour.from_rgb(r, g, b)
  • hsv:discord.Colour.from_hsv(h, s, v)
  • 或使用内置的随机颜色函数:discord.Colour.random()
直接将整数传递给discord.Embed也是可以的,而不是创建一个discord.Color对象,但这样做就无法使用其他选项了。
示例: em = discord.Embed(title = name, color = discord.Colour.random())

0

随机颜色rgb

我不知道它是否有效

也许你可以使用这个:

def random_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)

    rgbl = [r, g, b]
    return tuple(rgbl)

你需要导入random

它是:

em = discord.Embed(title = name, color = random.choice(colors))

更改:

em = discord.Embed(title = name, color = random_color())

我使用它从聊天机器人中获取随机颜色: 例如 (173, 435, 243)。

discord.py库本身有一个生成随机颜色的方法。请查看Colour.random - Hazzu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接