Telegram Bot

I built a Telegram Bot, to keep diary on GitHub. Also Telegram is great and works across all platforms. So I would like to do more through Telegram. You can get bot API token by interacting with @BotFather account. The up-to-date Telegram API Ruby Client I found: telegram-bot-ruby.

The example from the client is using long polling, and I want to use Webhooks. It seems not obvious on the internet, let me show an example using Webhooks with Rails here.

First create an rails app on Heroku that accepts POST request:

# config/routes.rb
post(
  %(/webhooks/telegram/#{ENV.fetch("TELEGRAM_BOT_TOKEN")}),
  to: "telegram_events#create"
)

The controller and the event handler:

# app/controllers/telegram_events_controller.rb
class TelegramEventsController < ApplicationController
  skip_before_action :verify_authenticity_token, only: [:create]

  def create
    TelegramEvent.new(params: request_body).process
    head :ok
  end

  private

  def request_body
    JSON.parse(request.raw_post)
  end
end

# app/models/telegram_event.rb
require "telegram/bot"

class TelegramEvent
  def initialize(params:)
    @params = params
  end

  def process
    telegram_api.send_message(
      chat_id: params["message"]["chat"]["id"],
      text: "Hello, #{params["message"]["text"]}",
    )
  end

  private

  def telegram_api
    Telegram::Bot::Client.new(ENV.fetch("TELEGRAM_BOT_TOKEN")).api
  end
end

Then opens up rails console, set the webhook url for your bot to POST when she received messages from you:

require "telegram/bot"
token = ENV.fetch("TELEGRAM_BOT_TOKEN")
Telegram::Bot::Client.new(token).api
api.set_webhook(url: "https://yourapp.herokuapp.com/webhooks/telegram/#{token}")

Now if you send a World! to your bot, you will receive following message back:

"Hello, World!"

Hope this helps you.

You are wonderful!