Hey there, fellow Ruby enthusiast! Ready to dive into the world of Telegram bots? You're in for a treat. Telegram's API is a powerhouse for creating interactive and engaging bots, and with the telegram-bot-ruby
gem, we're going to make it a breeze. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get that gem installed:
gem install telegram-bot-ruby
Easy peasy, right?
Now, let's breathe life into our bot:
require 'telegram/bot' token = 'YOUR_BOT_TOKEN' Telegram::Bot::Client.run(token) do |bot| bot.listen do |message| case message.text when '/start' bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}!") when '/stop' bot.api.send_message(chat_id: message.chat.id, text: "Bye, #{message.from.first_name}!") end end end
Look at that! You've got a bot responding to /start
and /stop
commands. You're practically a bot whisperer already.
Want to add some clickable buttons? Say no more:
kb = [[Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Go to Google', url: 'https://google.com')]] markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb) bot.api.send_message(chat_id: message.chat.id, text: 'Make your choice', reply_markup: markup)
Spice things up with some media:
bot.api.send_photo(chat_id: message.chat.id, photo: Faraday::UploadIO.new('path/to/image.jpg', 'image/jpeg'))
For those fancy inline buttons:
when Telegram::Bot::Types::CallbackQuery bot.api.answer_callback_query(callback_query_id: message.id, text: "You clicked #{message.data}!")
Want to level up? Let's set up a webhook:
require 'sinatra' post '/webhook' do request.body.rewind update = Telegram::Bot::Types::Update.new(JSON.parse(request.body.read)) # Handle your update here end
Don't forget to set your webhook URL with Telegram!
Keep your bot robust:
begin # Your bot logic here rescue Telegram::Bot::Exceptions::ResponseError => e logger.error "Telegram API Error: #{e.message}" end
When you're ready to unleash your bot on the world, consider:
ENV['TELEGRAM_BOT_TOKEN']
)And there you have it! You're now armed with the knowledge to create some seriously cool Telegram bots with Ruby. Remember, the best way to learn is by doing, so get out there and start coding. The Telegram bot world is your oyster!
Want to dive deeper? Check out the telegram-bot-ruby documentation and the Telegram Bot API docs.
Now go forth and bot like a boss! 🚀