Webhook & Updates

Working with Webhook Updates & Manually Fetching Updates (Long-polling).

Getting Updates

There are two mutually exclusive ways of receiving updates for your bot — the getUpdates method on one hand and Webhooks on the other. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.

Regardless of which option you choose, you will receive JSON-serialized Update objects as a result.

Getting Updates Via Webhook

In order to receive updates via a Webhook, You first need to tell your webhook URL to Telegram. You can use setWebhook method to specify a url and receive incoming updates via an outgoing webhook.

Once you set the webhook using the setWebhook method, You can then use the below function to retrieve the updates that are sent to your Webhook URL. The function returns an array of Update objects.

use Telegram\Bot\Api;

$telegram = new Api('BOT TOKEN');

$updates = $telegram->getWebhookUpdates();
// Put this inside either the POST route '/<token>/webhook' closure (see below) or 
// whatever Controller is handling your POST route
$updates = Telegram::getWebhookUpdates();

// Example of POST Route:
Route::post('/<token>/webhook', function () {
    $updates = Telegram::getWebhookUpdates();

    return 'ok';
});

// !!IMPORTANT!!
/* 
You need to add your route in "$except" array inside the app/Http/Middleware/VerifyCsrfToken.php file in order to bypass the CSRF Token verification process that takes place whenever a POST route is called.

Example:

protected $except = [
	'/<token>/webhook'
];
*/

Laravel (IMPORTANT!)

You need to add your route in $except array inside the app/Http/Middleware/VerifyCsrfToken.php file in order to bypass the CSRF Token verification process that takes place whenever a POST route is called.

Here's an example based on the above case scenario:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/<token>/webhook'
    ];
}

Removing Webhook

To remove a webhook (if it was set before). Use the SDK's removeWebhook helper method.

Getting Updates Manually (Long-Polling)

You can use getUpdates method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.