Hey everyone! I’m working on a Ruby Telegram bot and I’m stuck with a couple of things. I’m using a gem for the bot, but I won’t name it to avoid any promo.
First, I’ve set up a custom keyboard for a lottery feature:
How do I handle the user’s response? For example, if they pick ‘1’, I want to send a message like:
if user_choice == '1'
bot.api.send_message(chat_id: chat.id, text: 'You picked 1!', reply_markup: number_pad)
end
Also, I’m trying to implement a feature where users can send messages to each other through the bot. How can I parse a command like ‘/message @user1’ and have the bot respond with ‘@user1, you’ve got a message from @sender’?
I’ve faced similar challenges with Telegram bots in Ruby. For handling user responses to the custom keyboard, you can utilize a state machine or a simple flag to track the context. Here’s a basic approach:
@awaiting_lottery_pick = false
bot.listen do |message|
if @awaiting_lottery_pick && message.text =~ /^[0-9]$/
bot.api.send_message(chat_id: message.chat.id, text: "You picked #{message.text}!")
@awaiting_lottery_pick = false
elsif message.text == '/lottery'
@awaiting_lottery_pick = true
# Your existing lottery keyboard code here
end
end
For the messaging feature, you could implement it like this:
when /^\/message @(\w+)\s+(.+)/
recipient = $1
content = $2
sender = message.from.username
bot.api.send_message(chat_id: message.chat.id, text: "@#{recipient}, message from @#{sender}: #{content}")
end
This captures both the recipient and the message content. Remember to add error handling and user verification as needed.
For handling user responses to the custom keyboard, you’ll want to set up a message handler in your main bot loop. Something like:
bot.listen do |message|
case message.text
when '1'..'9', '0'
bot.api.send_message(chat_id: message.chat.id, text: "You picked #{message.text}!")
end
end
As for the messaging feature, you can use regular expressions to parse the command:
when /^\/message @(\w+)/
recipient = $1
sender = message.from.username
bot.api.send_message(chat_id: message.chat.id, text: "@#{recipient}, you've got a message from @#{sender}")
This assumes the recipient’s username exists in your bot’s user database. You might need additional logic to verify and handle user existence.