TelegramAPI-PHP/Telegram.class.php
2019-10-04 09:33:10 +02:00

350 lines
5.8 KiB
PHP

<?php
/*
* PHP Telegram API implementation
* Daniele Callari
* Daxtech.net
*
*/
class TelegramBot
{
#
# version
#
const Version = '1.2';
#
# limit of http retry
#
const RetryMax = 5;
#
# Bot token
#
private $Token = null;
#
# bool param - TODO
#
private $Async = false;
#
# messages methods collection
#
private $actions = array();
#
# debug mode
#
public $debug = false;
#
# ids whitelist
#
private $PermittedSenders = array();
#
# init class
#
function __construct($token)
{
#
# set token as private
#
$this->Token = $token;
#
# check curl module
#
if( !function_exists ('curl_init') )
{
header("Content-type:application/json");
die(json_encode(array('error' => true, 'message' => 'php-curl module not installed/enabled')));
}
}
#
# Set async calls
#
public function SetAsync($bool)
{
$this->Async = $bool;
}
#
# add id to whitelist
#
public function PermitFromId($userId)
{
$this->PermittedSenders[] = $userId;
}
#
# do http call
#
private function _httpSend($method, $data)
{
#
# init curl
#
$ch = curl_init("https://api.telegram.org/bot$this->Token/$method");
#
# set options
#
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
#
# do http call with retry
#
$TryCounter = 0;
$Result = false;
while( $TryCounter < self::RetryMax )
{
#
# do call
#
$Result = curl_exec($ch);
#
# manage retry
#
if($Result === false) $TryCounter++;
else $TryCounter = self::RetryMax;
}
#
# parse response
#
$j = @json_decode($Result, true);
#
# output if debug
#
if($this->debug) print_r($j);
#
# return response from api.telegram
#
return ($Result)?$j:json_encode([]);
}
#
# https://core.telegram.org/bots/api#sendChatAction
#
public function SendChatAction($destination, $action)
{
return $this->_httpSend('sendChatAction', array(
'chat_id' => $destination,
'action' => $action
));
}
#
# https://core.telegram.org/bots/api#sendMessage
#
public function SendMessage($destination, $textMessage)
{
return $this->_httpSend('sendMessage', array(
'text' => $textMessage,
'chat_id' => $destination,
'parse_mode'=> 'HTML'
));
}
#
# https://core.telegram.org/bots/api#sendcontact
#
public function SendContact($destination, $number, $firstName, $lastName=null)
{
return $this->_httpSend('sendContact', array(
'chat_id' => $destination,
'phone_number' => $number,
'first_name' => $firstName,
'last_name' => $lastName
));
}
#
# Send location
#
public function SendLocation($destination, $lat, $long)
{
return $this->_httpSend('sendLocation', array(
'chat_id' => $destination,
'latitude' => $lat,
'longitude' => $long
));
}
#
# send document
#
public function SendDocument($destination, $url)
{
if( strpos('http', $url) === 0 )
{
return $this->_httpSend('sendDocument', array(
'chat_id' => $destination,
'photo' => $url
));
}else{
return $this->_httpSend('sendDocument', array(
'chat_id' => $destination,
'photo' => new CURLFile($url)
));
}
}
#
# send image
#
public function SendImage($destination, $url)
{
if( strpos('http', $url) === 0 )
{
return $this->_httpSend('sendPhoto', array(
'chat_id' => $destination,
'photo' => $url
));
}else{
return $this->_httpSend('sendPhoto', array(
'chat_id' => $destination,
'photo' => new CURLFile($url)
));
}
}
#
# add method in queue
#
public function AddMessageHandler($x)
{
$this->actions[] = $x;
}
#
# listen recevied messages 4 bot
#
public function Listen()
{
#
# last message readed cache
#
$offset = 0;
#
# infinite loop
#
while(true)
{
try
{
#
# build query
#
$ApiCall = "https://api.telegram.org/bot$this->Token/getUpdates?".http_build_query(array(
'offset' => $offset
));
#
# do query
#
$result = file_get_contents($ApiCall);
#
# parse response
#
$x = json_decode($result);
#
# length
#
$count = count((array)$x->result);
if( $count )
{
#
# each messages
#
foreach( $x->result as &$message )
{
#
# message type helpers
#
$message->message->IsText = isset($message->message->text);
$message->message->IsDocument = isset($message->message->document);
$message->message->IsPhoto = isset($message->message->photo);
$message->message->IsVoice = isset($message->message->voice);
#
# check whitelist
#
if( count($this->PermittedSenders))
{
if(!in_array($message->message->from->id, $this->PermittedSenders))
{
#
# debug
#
if($this->debug) echo "*** Discarded message from ".$message->message->from->id." ***\n";
#
# set as read
#
$offset = $message->update_id+1;
#
# jump
#
continue;
}
}
#
# debug
#
if($this->debug) print_r($message);
#
# iterate actions
#
foreach( $this->actions as $action )
{
#
# execute anonymous action (as function)
#
$action($message->message, $this);
}
#
# update offset 4 next http call - we comunicate at api.telegram that we have readed the message
#
$offset = $message->update_id+1;
}
}
}
catch(Exception $e)
{
if($this->debug) echo $e->getMessage()."\n";
}
finally {
#
# loop standby
#
usleep(1000);
}
}
}
public static function Contains($x,$y)
{
return strpos( strtolower($y), strtolower($x) ) !== false;
}
}
?>