Telegram API

As we know that Telegram is a messaging app identifies users by their mobile number. Fortunately, Telegram has its own API -Ruby has a wrapper gem for Telegram’s Bot API called telegram-bot-ruby - which allows you to Integrate with other services, create custom tools, build single- and multiplayer games, build social services, do virtually anything else; Do you smell anything evil here?

  • Install telegram-bot gem

    1. gem install telegram-bot-ruby
  • Basic usage

As many APIs, you have to get a token to deal with your bot. Here a basic usage

  1. require 'telegram/bot'
  2. token = 'YOUR_TELEGRAM_BOT_API_TOKEN'
  3. Telegram::Bot::Client.run(token) do |bot|
  4. bot.listen do |message|
  5. case message.text
  6. when '/start'
  7. bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}")
  8. when '/stop'
  9. bot.api.send_message(chat_id: message.chat.id, text: "Bye, #{message.from.first_name}")
  10. when '/rubyfu'
  11. bot.api.send_message(chat_id: message.chat.id, text: "Rubyfu, where Ruby goes eveil!")
  12. end
  13. end
  14. end

Once your run it, go to your telegram and find the bot and start chat with /start, try to send /rubyfu.

Telegram API - 图1

  • Inline bots

If you got that evil smile from above example, you may thinking about interacting with your bots inline to call/@mention your bots and request more action from the bot(s).

  1. require 'telegram/bot'
  2. bot.listen do |message|
  3. case message
  4. when Telegram::Bot::Types::InlineQuery
  5. results = [
  6. Telegram::Bot::Types::InlineQueryResultArticle
  7. .new(id: 1, title: 'First article', message_text: 'Very interesting text goes here.'),
  8. Telegram::Bot::Types::InlineQueryResultArticle
  9. .new(id: 2, title: 'Second article', message_text: 'Another interesting text here.')
  10. ]
  11. bot.api.answer_inline_query(inline_query_id: message.id, results: results)
  12. when Telegram::Bot::Types::Message
  13. bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}!")
  14. end
  15. end

Resources