简体   繁体   中英

How do I convert a hex value that is stored as a string into a hex value in python?

I have a discord bot, and the command I am working on will send an embed at the user's discretion using user provided arguments. This means that the hex code for the embed colour is stored as a string, not hex. I've tried numerous methods including converting to a base16 int using int(variable, 16) and then using hex(variable) , using utf-8 encoding to convert between the two but nothing has worked as of yet. My current code is this:

@commands.command(description='Send an embed message with Title, Colour, Footer and Field customization.')
  async def embed(self, ctx, *, args=None):
    if args == None:
      #code that explains how to use the command
    else:
      embedConfig=args.split(" | ")
      if (len(embedConfig)-1) > 3:
        await ctx.send("Too many arguments!")
      else:
        embedConfig[1] = embedConfig[1].lstrip("#")
        embedConfig[1] = ("0x" + embedConfig[1])
        embedConfig[1] = int(embedConfig[1], 16)
        embedConfig[1] = hex(embedConfig[1])
        embed=discord.Embed(title=embedConfig[0], description=embedConfig[2], color=embedConfig[1])
        embed.set_footer(text=embedConfig[3])
        embed.timestamp = datetime.now()
        await ctx.send(embed=embed)

I'm using the discord.py rewrite with the commands extension. The command above is in a cog and the valid syntax would be the following: fa!embed Hi | #ffffff | Hi | Made by me fa!embed Hi | #ffffff | Hi | Made by me fa!embed Hi | #ffffff | Hi | Made by me . Thanks!

@Tim Roberts suggested this method:

Remove my conversions and call int(embedConfig[1][1:],16) as the colour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM