I’m developing a Telegram bot using Ruby and I’m looking for assistance on how to capture user input from commands. For instance, when a user types /invite John, I want the bot to extract the name “John” and include it in the response.
when "/invite"
bot.api.send_message(chat_id: message.chat.id, text: "Inviting user")
Currently, the bot handles the basic commands but I’m unsure how to retrieve the parameter. My goal is that when a user sends /invite Sarah, the bot responds with “Inviting Sarah” and also logs the command in a text file.
In summary, I need to:
Capture the name from the command
Use it in the response
Record the entire command into a file
Is there a method to analyze the message text and extract just the parameter?
You can also use regex for parameter extraction - it’s way more flexible when commands have weird spacing or multiple parameters.
when "/invite"
if match = message.text.match(/\/invite\s+(.+)/)
name = match[1].strip
bot.api.send_message(chat_id: message.chat.id, text: "Inviting #{name}")
# Append to log file
File.open("bot_commands.txt", "a") { |f| f.puts "#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}: #{message.text}" }
else
bot.api.send_message(chat_id: message.chat.id, text: "Usage: /invite [name]")
end
end
The regex handles whitespace variations way better than basic string ops. The (.+) grabs everything after the command as one chunk, so “John Smith” works fine. Also throw timestamps in your log entries - makes tracking much easier.
just use message.text.gsub('/invite ', '') to strip the command and grab what’s left. works great when you need something quick without overcomplicating it.
Parse the message text directly to grab parameters. The message object has the full text with command and parameters. Here’s what I do in my bots:
when "/invite"
command_parts = message.text.split(' ', 2)
if command_parts.length > 1
username = command_parts[1]
response_text = "Inviting #{username}"
# Log to file
File.open("commands.log", "a") do |file|
file.puts "#{Time.now}: #{message.text}"
end
bot.api.send_message(chat_id: message.chat.id, text: response_text)
else
bot.api.send_message(chat_id: message.chat.id, text: "Please specify a name to invite")
end
end
Use split(' ', 2) - it separates command from parameter but keeps any spaces in the parameter. Always check if the parameter exists so you don’t get errors when users send incomplete commands.