Programming a Discord bot in Python- How do I make an embed have a random color?

Viewed 3818

I'm trying to make it so that whenever the bot sends an embed, the color for it is random. Here's my code:

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)

It gives me this error: TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.

Not sure how to fix this, any tips?

2 Answers

I guess, it must be

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

As your error message suggests, the class discord.Embed does not accept a string as a valid input for the color keyword argument. It must instead be an instance of the class: discord.Color.

There are several ways to accomplish your task then:

  • pass the color as an integer discord.Colour(value)
  • pass the color as separate r, g, b values: discord.Colour.from_rgb(r, g, b)
  • hsv: discord.Colour.from_hsv(h, s, v)
  • or use the built-in random color function: discord.Colour.random()

It is also acceptable to just pass the integer directly to discord.Embed rather than creating a discord.Color object, but the other options will not be available then.

example:

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

Related