Skip to content
This repository has been archived by the owner on Jun 20, 2023. It is now read-only.

Using webhooks

Luis Mayoral edited this page Jun 28, 2015 · 1 revision

If you plan to integrate the bot functionality inside your web application you will prefer to use webhooks. After setting a webhook, your application will receive every message sent to your bot serialized as a JSON object in the URL you specified.

To set up a webhook for your bot you can do something like this (in this example we want to receive messages for our bot in the URL https://www.example.com/updates/handle-update):

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')

# Setting the webhook
response = bot.set_webhook("https://www.example.com/updates/handle")
# <Telegrammer::ApiResponse:0x007ff4b9a73658 @body="{\"ok\":true,\"result\":true,\"description\":\"Webhook was set\"}", @success=true, @result=true>

# If we want to delete the webhook
response = bot.set_webhook("")
# <Telegrammer::ApiResponse:0x007ff4bb0814b8 @body="{\"ok\":true,\"result\":true,\"description\":\"Webhook was deleted\"}", @success=true, @result=true>

# If we try to delete a webhook for a bot without webhook set, we will receive the following response
response = bot.set_webhook("")
# <Telegrammer::ApiResponse:0x007ff4bb07be00 @body="{\"ok\":true,\"result\":true,\"description\":\"There is no webhook to delete\"}", @success=true, @result=true>

Please note, as long an outgoing webhook is set up for your bot, you will note be able to receive updates using get_updates. If you need to use again get_updates you'll first need to delete the webhook.

After setting the webhook, you'll need to prepare your app to receive these messages. If you use Rails, you can add a route to your config/routes.rb:

  post "/updates/handle" => "updates#handle"

Then, in your controller, you can do something like:

class UpdatesController < ApplicationController
  # You have to disable authenticity token verification for the action that handles the bot updates
  skip_before_action :verify_authenticity_token, only: [:my_action]

  def handle
    update = Telegrammer::DataTypes::Update.new(
      update_id: params[:update_id],
      message: params[:message]
    )

    # Here goes what you want to do with this update
  end
end
Clone this wiki locally