使用Ruby的Discordrb库无法设置正确的十六进制角色颜色
问题分析与解决方案
你的核心问题是错误地将RGB数组元素直接拼接成整数,这完全不符合Discord角色颜色的参数要求。
问题根源
当输入#25107A时,ColorConverter.rgb(clr)返回的RGB数组是[37, 16, 122],你直接join.to_i得到3716122,但这个数值并不是Discord需要的颜色编码。Discord要求的颜色值是将RGB三个分量按红(R)左移16位、绿(G)左移8位、蓝(B)保留低位合并后的整数,正确计算方式为:
r, g, b = ColorConverter.rgb(clr) correct_color = r * 65536 + g * 256 + b # 或者用位运算:r << 16 | g << 8 | b
以#25107A为例,正确计算结果是37*65536 + 16*256 + 122 = 2490490,而不是你拼接出来的3716122,这就是颜色显示错误的原因。
修复后的代码片段
替换你原有的颜色转换代码:
clr = event.options['color'] # 处理输入可能带的#号,确保ColorConverter能正确解析 clr = clr.delete('#') r, g, b = ColorConverter.rgb(clr) passthrough = r << 16 | g << 8 | b # 正确的颜色值计算
完整修复代码
require 'discordrb' require "color_converter" bot = Discordrb::Bot.new(token:'token_goes_here', intents: [:server_messages, :guilds]) bot.ready do |event| puts "Logged in as #{bot.profile.username}" end bot.register_application_command(:booster, 'Example commands', server_id: ENV.fetch('SLASH_COMMAND_BOT_SERVER_ID', nil)) do |cmd| cmd.subcommand_group(:role, 'Fun things!') do |group| group.subcommand('claim', 'Claim your custom booster role!') do |sub| sub.string('name', 'Provide a name for your role.', required: true) sub.string('color', 'Provide a HEX color for your role.', required: true) sub.string('icon', 'Provide a role icon for your role. Currently, you can only use a server emoji as an icon.', required: false) end end end bot.application_command(:booster).group(:role) do |group| group.subcommand('claim') do |event| nme = event.options['name'] clr = event.options['color'] # 清理输入的#号,避免解析失败 clr = clr.delete('#') # 正确提取RGB分量并计算Discord所需的颜色整数 r, g, b = ColorConverter.rgb(clr) correct_color = r << 16 | g << 8 | b event.server.create_role( name: nme, colour: correct_color, hoist: false, mentionable: false, permissions: 0, reason: 'Server Booster claimed role.' ) event.respond( content: 'Your role has been successfully created. Please feel free to edit your role at any time using the ``/booster role edit`` command.', ephemeral: true ) end end bot.run
额外建议
- 添加输入格式校验:比如检查用户输入的十六进制是否为6位(带或不带#),避免
ColorConverter解析出错 - 可以捕获
ColorConverter的异常,当用户输入无效颜色时返回错误提示
内容的提问来源于stack exchange,提问作者Droid
相关产品推荐
相关产品推荐

