Simple Telegram echo Bot (Apache + PHP)

Install LAMP:

sudo apt-get install lamp-server^

Setup site for your bot. Create new file “your_bot_name-ssl.conf” at “/etc/apache2/sites-available”.


<IfModule mod_ssl.c>
	<VirtualHost _default_:88>
		ServerName my_new_bot
		ServerAlias my_new_bot

		DocumentRoot /var/www/my_new_bot

		ErrorLog ${APACHE_LOG_DIR}/error.log
		CustomLog ${APACHE_LOG_DIR}/access.log combined
		SSLEngine on
		SSLCertificateFile	/etc/apache2/ssl/apache.pem
		SSLCertificateKeyFile /etc/apache2/ssl/apache.key
		<FilesMatch "\.(cgi|shtml|phtml|php)$">
				SSLOptions +StdEnvVars
		<Directory /usr/lib/cgi-bin>
				SSLOptions +StdEnvVars


# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Now edit file “/etc/apache2/ports.conf”, change port 443 on 88.

Activate mod_ssl:

sudo a2enmod ssl

Activate HTTPS:

sudo a2ensite taskbot-ssl.conf

Install php-curl:

sudo apt-get install php-curl

Generate self signed certificate:

openssl req -newkey rsa:2048 -sha256 -nodes -keyout /etc/apache2/ssl/apache.key -x509 -days 3650 -out /etc/apache2/ssl/apache.pem -subj "/C=RU/ST=Krasnodar/L=YOUR_CITY/O=./CN=YOUR_IP"

Create at “/var/www/my_new_bot” script “index.php” for your bot:

$access_token = 'your_access_token';
$api = ''.$access_token;
$output = json_decode(file_get_contents('php://input'), TRUE);
$chat_id = $output['message']['chat']['id'];
$first_name = $output['message']['chat']['first_name'];
$message = $output['message']['text'];
$userID = $output['message']['from']['id'];
$userFirstName = $output['message']['from']['first_name'];
$userLastName = $output['message']['from']['last_name'];
$userUserName = $output['message']['from']['username'];

sendMessage($chat_id, $message );

 //$chat_id - chat id
 //$message - message text
 function sendMessage($chat_id, $message) {
   file_get_contents($GLOBALS['api'] . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message)  . '&parse_mode=HTML');

Restart apache:

sudo service apache2 restart

Check at web browser https://YOUR_IP:88. At this moment your web server must be accessible from internet. If you have any problems with access, check previous steps and go to the next step only when your web server be accessible!

Setup webhook:

curl -F "url=https://YOU_IP:88/" -F "certificate=@/etc/apache2/ssl/apache.pem"

The end. Check your bot work at the telegram app.

Categories: PHP

1 Comment

Leave a Comment