How to create a telegram bot using PHP and IPv6 VPS

Posted on

This tutorial should work on any Operating System as we focus on Web Server and PHP, also the same method can be implemented to other web based programming languages.

  1. If you dont have a VPS yet, you can create a free ipv6 VPS on Hax.co.id,  this is my free VPS from hax:
  2. Check this tutorial for how to connect to ipv6 vps
  3. Then follow this tutorial to install a web server to Ubuntu, Centos and Debian
  4. At this point you should have a working domain and web server, You can verify by visiting the domain which should show the default page for Apache. Next, install curl and php curl, please change apt according to your OS ( I use Ubuntu 20)
    apt-get install curl -y
    apt-get install php-curl  -y

    restart your web server

    service apache2 restart
  5. Send a private message to @BotFather, and type command /newbot then follow the instructions until you get a bot token as the screenshot below
    Please save that bot token
  6. Login to your server and go to root path of your web server
     cd /var/www/html/
  7. Create a new file, bot.php (or rename as you like) and copy the php code below. dont forget to change $token value to your bot token (step 5)

    apt install nano -y
    nano bot.php

    then put this code

    <?php
    $token = "111111111:xxxxxxxxxxxxxxxxxxxxxxxxxx";
    $content=file_get_contents("php://input");
    $content = json_decode($content,TRUE);
    $message = $content["message"]["text"];
    $from = $content["message"]["from"]["id"];
    
    if($message == '/start'){
        $response = "Hi there :) \n example bot hax.co.id";
    }elseif($message == '/getid'){
    	$response = "Your telegram ID is:".$from;
    }elseif($message == '/getchatid') {
    	$response = "Your Chat ID is:".$content["message"]["chat"]["id"];
    }
    
    $params = array(
    	 'chat_id'   => $content["message"]["chat"]["id"],
    	 'text'   =>  $response,
    	 'action'     => 'typing'
    );
    
    $url = 'https://api.telegram.org/bot'.$token."/sendMessage";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $result=curl_exec ($ch);
    

    This simple code will create basic commands like /start, /getid, /getchatid

  8.  Connect your bot to telegram api using this tool
    write your full url to “Bot Full Path” and paste token from step to “Bot Token”

  9. Your bot is ready now! You can send private messages to your bot and send basic commands as in code: /start, /getid, and /getchatid. Feel free to modify this code as per your requirement
See also  How to Install OpenVPN on IPv6 VPS