atipugin / telegram-bot-ruby

Ruby wrapper for Telegram's Bot API
https://core.telegram.org/bots/api
Do What The F*ck You Want To Public License
1.35k stars 218 forks source link

Best way to create commands with arguments? #252

Closed Gregory280 closed 2 years ago

Gregory280 commented 2 years ago

What is the correct way to create commands that require arguments? I have stumble on creating a command that requires an argument to use through an API. I could successfully save the user input, but I think thats not the correct way.

Telegram::Bot::Client.run(token) do |bot|
      bot.listen do |message|
        case message
        when Telegram::Bot::Types::Message
          code = message.text.delete('^0-9')
          case message.text
          when "/code #{code}" 
            # do something
          end

Thats works but I'm saving something everytime that has a new message. And how works if multiple commands that requires arguments? Would I do the same ?

Gregory280 commented 2 years ago

I came up with a solution using regex. This way I can retrieve the argument just when its matching a command '/code' in the message.

when \/\code/
   code = message.text.delete('^0-9')
   if message.text == "/code #{code}"
       # do something
   end

And to prevent calling the command in any message that contains this regex I used a if statement. Its that a good way of doing things?

atipugin commented 2 years ago

Hey @Gregory280,

Using regex is totally fine. You can go further and match code value right in when ... statement:

case message.text
when /^\/code ([0-9]+)$/
  puts "Code is #{$1}" # $1 refers matched group
else
  puts "No match"
end
Gregory280 commented 2 years ago

This work like a charm thanks.
I can't use this on other commands that requires words for arguments like "/meme programming". How would you recommend in this case?

atipugin commented 2 years ago

Why not, just change regexp to match your needs. For /meme programming something like this would work: ^\/meme\s+(\w+)$

Gregory280 commented 2 years ago

Thanks. I got review regex.