shardlab/discordrb

Application command handlers with string instead of a symbol do not work.

Opened this issue · 2 comments

Summary

When adding application command handlers with a string instead of a symbol, they do not respond.

image

# frozen_string_literal: true

require 'discordrb'
require 'discordrb/webhooks'

TOKEN = "add_ur_token_here"
SERVER_ID = "add_ur_server_id_here"

bot = Discordrb::Bot.new token: TOKEN, intents: [:server_messages]

bot.register_application_command('example', 'Example command', server_id: SERVER_ID) do |command|
  command.subcommand('subcommand1', 'Example subcommand with string')
  command.subcommand(:subcommand2, 'Example subcommand with symbol')
end

bot.application_command('example').subcommand('subcommand1') do |event|
  event.respond(content: "Responded to subcommand1")
end

bot.application_command(:example).subcommand(:subcommand2) do |event|
  event.respond(content: "Responded to subcommand2")
end

bot.run

No warnings are present in the logger either.

Environment

Ruby version:

ruby 3.0.3p157 (2021-11-24 revision 3fb7d2cadc) [arm64-darwin21]

Discordrb version:

gem 'discordrb', github: 'shardlab/discordrb', branch: 'main'

The docs for Discordrb::Bot#application_command (which is included from Discordrb::EventContainer) state that the name argument shall be a symbol, so I would expect that it is intended to not work with strings.

A dive into the source code confirms that:
The application command is called here.

@application_commands[event.command_name]&.call(event)

event is a Discordrb::Events::ApplicationCommandEvent, as can be seen a few lines above that one. The initializer of that class turns any command name received from Discord into a symbol.
@command_name = command_data['name'].to_sym

This symbolized command name is then used to look up the block in a Hash, but the key is the name String you passed, so the lookup fails.

Assuming that it is a common mistake to not read the docs properly, this is probably not the first nor the last time someone has this issue. An improvement could be to convert the command name argument of #application_command to a symbol and maybe even add String as a valid argument type to its documentation (in addition to Symbol).

The example for slash commands uses strings, so if only symbols are supported, that should be fixed...