Source: telegram-bot.phps - download
<?php
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* telegram-bot.php 0.1
* by daif alotaibi (http://daif.net)
* daif@daif.net
*
* Link:
* http://daif.net/script/telegram-bot.phps
*
*/
// set bot token
define('BOT_TOKEN', '12345678:powquepouwqeopwquepowque');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
define('BOT_NAME', '@NameOfTheBot');
// get the request from telegram callback service
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if($update) {
$chat_id = $update["message"]['chat']['id'];
$chat_type = $update["message"]['chat']['type'];
$text = @trim($update["message"]['text']);
// user name for the user
if(isset($update["message"]['from']['first_name'])) {
$from_user = $update["message"]['from']['first_name'];
} else {
$from_user = $update["message"]['from']['username'];
}
// if someone is chatting to the bot
if($chat_type == 'private') {
//if the sent text is a command, start with /
if(preg_match('#/(.+)\s*#', $text, $cmd)) {
if($cmd[1] == 'start') {
$message = "مرحبا.";
} elseif ($cmd[1] == 'hello') {
$message = "مرحبا: ".$from_user;
} else {
$message = "الامر غري معروف.";
}
} else {
if($text == 'start') {
$message = "مرحبا.";
} elseif ($text == 'hello') {
$message = "مرحبا: ".$from_user;
} else {
$message = "الامر غري معروف, يمكن ارسال hello";
}
}
// else it is a message in group
} else {
// if someone add the bot to group, display welcome message
if(isset($update["message"]['new_chat_participant']) && $update["message"]['new_chat_participant']['username'] == BOT_NAME ) {
$message = "شكرا على اضافتي للمجموهة.";
}
// if someone in the group talk to the bot
if(preg_match('/@'.BOT_NAME.'\s*(.+)/i', $text, $msg)) {
$message = "لا يوجد أي معلومات لدي.";
}
}
// if chat id and message set , send back the message to user or group
if($chat_id && $message)
{
SendMessageTo($chat_id, $message);
}
}
function SendMessageTo($chat_id, $message) {
$request = array('chat_id'=>$chat_id, 'text'=>$message);
$url = API_URL.'sendMessage?'.http_build_query($request);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$response = curl_exec($ch);
if($response) {
$response = json_decode($response, true);
$response = $response['result'];
}
return $response;
}
?>