Skip to content

Instantly share code, notes, and snippets.

@421p
Last active January 12, 2019 13:38
Show Gist options
  • Save 421p/e99ee7afbaee90bb35bceb122d1c3b25 to your computer and use it in GitHub Desktop.
Save 421p/e99ee7afbaee90bb35bceb122d1c3b25 to your computer and use it in GitHub Desktop.
Script for pulling telegram bot updates and forwarding to your webhook.
#!/usr/bin/env php
<?php
class Forwarder
{
private $offset = 0;
private $limit = 100;
private $timeout = 120;
private $botToken;
private $webHook;
public function __construct($botToken, $webHook)
{
$this->botToken = $botToken;
$this->webHook = $webHook;
}
public function process()
{
$payload = json_encode([
'offset' => $this->offset,
'limit' => $this->limit,
'timeout' => $this->timeout,
]);
$getUpdatesUrl = sprintf('https://api.telegram.org/bot%s/getUpdates', $this->botToken);
list($response) = $this->request($getUpdatesUrl, $payload);
$updates = json_decode($response, true);
foreach ($updates['result'] as $update) {
echo 'Forwarding update: '.json_encode($update, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE).PHP_EOL;
list($webhookResponse, $code) = $this->request($this->webHook, json_encode($update));
echo sprintf('Webhook responded: [%d] %s', $code, $webhookResponse).PHP_EOL;
$this->offset = $update['update_id'] + 1;
}
}
private function request($url, $payload)
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Content-Length: '.strlen($payload),
],
]);
$response = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$err = curl_error($curl);
if ($err) {
error_log($err);
}
curl_close($curl);
return [$response, $code];
}
}
function main($argc, $argv)
{
if (!isset($argv[1])) {
error_log('You must specify telegram bot token and webhook url');
exit(1);
}
if (!isset($argv[2])) {
error_log('You must specify webhook url');
exit(1);
}
$botToken = $argv[1];
$webHook = $argv[2];
$forwarder = new Forwarder($botToken, $webHook);
while (true) {
$forwarder->process();
}
}
main($argc, $argv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment