How to make simple Telegram bot with TelegramBotAPI

24.08.2017
By

Very good article (Russian) by Aftamat4ik.ru about installation of Simple Telegram bot with TelegramBotAPI example.

How to make cloudflare SSH free certification is here: https://www.lifeofgeek.com/setup-free-ssl-cloudflare/

I have already installed https and skiped this part of article.

Also I have used Putty SSH client and asked for SSH login and password for access to hosting.

In my case php has 5.3 version default. thats why I have used such style of php call:

/usr/local/php/php-5.6/bin/php -r «copy(‘https://getcomposer.org/installer’, ‘composer-setup.php’);»

I have put this index.php (by Alexander Shtockman) to my bot directory at the server. Remember – You need to change bot token.

<?php
/**
 * revcom_bot template (modified)
 *
 * @author - Alexander Shtockman
 * translation - toborobot.ru
 */
header('Content-Type: text/html; charset=utf-8');
// loading API
require_once("vendor/autoload.php");

// debug
if(true){
	error_reporting(E_ALL & ~(E_NOTICE | E_USER_NOTICE | E_DEPRECATED));
	ini_set('display_errors', 1);
}

// creating bot variable
$token = "your tocken here";
$bot = new \TelegramBot\Api\Client($token,null);

//if($_GET["bname"] == "revcombot"){
//	$bot->sendMessage("@burgercaputt", "Тест");
//}

// if bot have not registeredyet - do it now
if(!file_exists("registered.trigger")){
	/**
	 *  registered.trigger file will be created after bot registration.
	 *  if this file have not existed after first install.php execution
         * bot is not registered at Telegram
	 */

	// URl of index.php
	$page_url = "https://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	$result = $bot->setWebhook($page_url);
	if($result){
		file_put_contents("registered.trigger",time()); // creating file to stop registration again
	} else die("registration mistake happen!");
}

// Bot commands
// Test command "ping"
$bot->command('ping', function ($message) use ($bot) {
	$bot->sendMessage($message->getChat()->getId(), 'pong!');
});

// Must have. bot start command
$bot->command('start', function ($message) use ($bot) {
    $answer = 'Welcome!';
    $bot->sendMessage($message->getChat()->getId(), $answer);
});

// help command
$bot->command('help', function ($message) use ($bot) {
    $answer = 'Commands:
/help - help';
    $bot->sendMessage($message->getChat()->getId(), $answer);
});

// picture
$bot->command('getpic', function ($message) use ($bot) {
	$pic = "http://aftamat4ik.ru/wp-content/uploads/2017/03/photo_2016-12-13_23-21-07.jpg";

    $bot->sendPhoto($message->getChat()->getId(), $pic);
});

// document
$bot->command('getdoc', function ($message) use ($bot) {
	$document = new \CURLFile('shtirner.txt'); // file shtirner.txt need to be inside start directory

    $bot->sendDocument($message->getChat()->getId(), $document);
});

// Message Buttons
$bot->command("ibutton", function ($message) use ($bot) {
	$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
		[
			[
				['callback_data' => 'data_test', 'text' => 'Answer'],
				['callback_data' => 'data_test2', 'text' => 'Answer1']
			]
		]
	);

	$bot->sendMessage($message->getChat()->getId(), "тест", false, null,null,$keyboard);
});

// processing message button
$bot->on(function($update) use ($bot, $callback_loc, $find_command){
	$callback = $update->getCallbackQuery();
	$message = $callback->getMessage();
	$chatId = $message->getChat()->getId();
	$data = $callback->getData();

	if($data == "data_test"){
		$bot->answerCallbackQuery( $callback->getId(), "This is Ansver!",true);
	}
	if($data == "data_test2"){
		$bot->sendMessage($chatId, "Это ответ!");
		$bot->answerCallbackQuery($callback->getId()); // sending empty message to stop "timeTable" at the button
	}

}, function($update){
	$callback = $update->getCallbackQuery();
	if (is_null($callback) || !strlen($callback->getData()))
		return false;
	return true;
});

// inline processing
$bot->inlineQuery(function ($inlineQuery) use ($bot) {
	mb_internal_encoding("UTF-8");
	$qid = $inlineQuery->getId();
	$text = $inlineQuery->getQuery();

	// this is base inline
	$str = "Что другие?
Свора голодных нищих.
Им все равно...
В этом мире немытом
Душу человеческую
Ухорашивают рублем,
И если преступно здесь быть бандитом,
То не более преступно,
Чем быть королем...
Я слышал, как этот прохвост
Говорил тебе о Гамлете.
Что он в нем смыслит?
<b>Гамлет</b> восстал против лжи,
В которой варился королевский двор.
Но если б теперь он жил,
То был бы бандит и вор.";
	$base = new \TelegramBot\Api\Types\Inline\InputMessageContent\Text($str,"Html");

	// this is inline list
	// inline for poem
	$msg = new \TelegramBot\Api\Types\Inline\QueryResult\Article("1","С. Есенин","Отрывок из поэмы `Страна негодяев`");
	$msg->setInputMessageContent($base); // show that need to start poem

	// inline for picture
	$full = "http://aftamat4ik.ru/wp-content/uploads/2017/05/14277366494961.jpg"; // picture url
	$thumb = "http://aftamat4ik.ru/wp-content/uploads/2017/05/14277366494961-150x150.jpg"; // and the icon

	$photo = new \TelegramBot\Api\Types\Inline\QueryResult\Photo("2",$full,$thumb);

	// music inline
	$url = "http://aftamat4ik.ru/wp-content/uploads/2017/05/mongol-shuudan_-_kozyr-nash-mandat.mp3";
	$mp3 = new \TelegramBot\Api\Types\Inline\QueryResult\Audio("3",$url,"Монгол Шуудан - Козырь наш Мандат!");

	// inline for video
	$vurl = "http://aftamat4ik.ru/wp-content/uploads/2017/05/bb.mp4";
	$thumb = "http://aftamat4ik.ru/wp-content/uploads/2017/05/joker_5-150x150.jpg";
	$video = new \TelegramBot\Api\Types\Inline\QueryResult\Video("4",$vurl,$thumb, "video/mp4","service","here can be desctiption");

	// send procedure
	try{
		$result = $bot->answerInlineQuery( $qid, [$msg,$photo,$mp3,$video],100,false);
	}catch(Exception $e){
		file_put_contents("rdata",print_r($e,true));
	}
});

// Reply Buttons
$bot->command("buttons", function ($message) use ($bot) {
	$keyboard = new \TelegramBot\Api\Types\ReplyKeyboardMarkup([[["text" => "All the power to the Soviet!"], ["text" => "WoW!"]]], true, true);

	$bot->sendMessage($message->getChat()->getId(), "тест", false, null,null, $keyboard);
});

// waiting for any messages + reply button execution
$bot->on(function($Update) use ($bot){

	$message = $Update->getMessage();
	$mtext = $message->getText();
	$cid = $message->getChat()->getId();

	if(mb_stripos($mtext,"Сиськи") !== false){
		$pic = "http://aftamat4ik.ru/wp-content/uploads/2017/05/14277366494961.jpg";

		$bot->sendPhoto($message->getChat()->getId(), $pic);
	}
	if(mb_stripos($mtext,"власть советам") !== false){
		$bot->sendMessage($message->getChat()->getId(), "Death to Rich!");
	}
}, function($message) use ($name){
	return true; // when here true - commands executed
});

// start execution
$bot->run();

echo "Bot works";

Добавить комментарий