用过telegram的人都知道telegram的bot很好玩,前几天我自己也写了一个,顺便分享一下的心得。
想看官方文档的可以去Telegram API,我这里写一个简短的说明。
首先,去telegram的botfather,和它开始一个会话
输入/newbot创建一个机器人,它会提示你输入机器人的基本信息,然后你会得到一个token,你需要通过这个token来对你的tgbot执行操作。
先去设置一下webhook以便tg的信息能发送到你的服务器

https://api.telegram.org/bot你的token/setWebhook?url=脚本地址

这样当你的tgbot收到信息,telegram就会“转发”到设置的脚本地址。
以下过程以PHP为例,此外还可以用python等,其实也可以php调用python实现功能

你可能会为到底怎么获取telegram给你服务器发的请求内容而烦恼,我也琢磨了老半天,这里提供解决方案

$post = file_get_contents("php://input");
$post = "[" . $post . "]";
$data = json_decode($post,true);

这里的data数组里放的就是telegram给你的信息,里面的内容是这样的:

[
{
    "update_id": 946895223,
    "message": {
      "message_id": 22521,
      "from": {
        "id": 947890567,
        "is_bot": false,
        "first_name": "cxbsoft",
        "username": "cxbsoft",
        "language_code": "zh-hans"
      },
      "chat": {
        "id": -426558199,
        "title": "cxtestgroup",
        "type": "group",
        "all_members_are_administrators": true
      },
      "date": 1584407807,
      "text": "/song@cx_test_bot name grrrls",
      "entities": [
        {
          "offset": 0,
          "length": 17,
          "type": "bot_command"
        }
      ]
    }
  }
]

那么我们就可以提取这个数组里面的信息

//发送的信息
$message = $data[0]['message']['text'];
//chat_id 相当如群号
$chat_id = $data[0]['message']['chat']['id'];
//用户id 相当如用户账号
$userid = $data[0]['message']['from']['id'];
//messageid 信息标识
$message_id = $data[0]['message']['message_id'];

接下来我们就可以处理这个信息
我们可以通过分割字符串成数组来获取命令(/ping,/song之类的),那么我们就要用到PHP自带函数:explode,这个函数的工作原理就是在一个字符串中找一个字符然后根据这个字符来分割字符串,改函数返回一个数组
函数用法 :explode("关键字符","原字符串")
那么我们提取tg的指令就用

$data = explode(" ",$message);
$command = $data[0] //这个数组的第一个元素就是命令,它可以是/command@botname 也可以是/command
$isbotcom = isset($data[0]['message']['entities'][0]['type']); //通过这个来判断是否为机器人指令,是的话返回true,若不是,返回false

那么我们来对具体的指令来分析

if($isbotcom){
    $command = str_replace("@botname","",$command) //若有@则去掉
    $mg = new message_mg(你的token);//message_mg类是我自己写的一个类,将会在下文提供
    switch($command){
        case '/ping':
            $mg -> send_message($chat_id,"Pong!"); 
            break;
    }
}

message_mg类:

class message_mg{
    function __construct($token){
        $this -> token = $token;
        
    }
    function trimall($str)//删除空格
    {
        $oldchar=array(" "," ","\t","\n","\r");
        $newchar=array("","","","","");
        return str_replace($oldchar,$newchar,$str);
    }
    
    function help_content($command){
        $this -> content = "";
        switch($command){
            case "/":
                $this -> content = "全局帮助\n/help - 获取帮助\n/ohayo - 早安\n/oyasumi - 晚安\n/signin - 签到";
            case 'signin':
                $this -> content = "/signin\n用法:\n无参数";
            default:
                $this -> content = "全局帮助\n/help - 获取帮助\n/ohayo - 早安\n/oyasumi - 晚安\n/signin - 签到";
        }
        return $this -> content;
    }
    
    function get_file_by_id($file_id){
        $token = $this -> token;
        $this -> requesturl = "https://api.telegram.org/bot$token/getFile";
        $pars = array(
            
            "file_id" => "$file_id"
            
            );
        $result = $this -> send_req($this -> requesturl,$pars);
        $result = json_decode($result,true);
        $remote_file_path = "https://api.telegram.org/file/bot$token/" . $result['result']['file_path'];
        $remote_content = file_get_contents($remote_file_path);
        return $remote_content;
        //$f = fopen("1.oga","wb");
        //fwrite($f,$remote_content);
        //fclose($f);
        
    }
    
    function get_text($pars,$times=2){
        $this -> resulttext = "";
        if($times == 1){
            
        }
        else{
           array_shift($pars); 
        }
        array_shift($pars);
        foreach($pars as $item){
            $this -> resulttext .= " " . $item ; 
        }
        $resulttext = $this -> resulttext;
        
        return $this -> resulttext;
        
    }
    
    function get_music_url($id){
        $result = $this -> send_req("http://music.163.com/api/song/enhance/player/url?br=128000&ids=[$id]&id=$id",array());
        $result = json_decode($result,true);
        $this -> debug_txt("hello.txt",$this -> result['data'][0]['url']);
        $this -> addr = $result["data"][0]["url"];
        $addr = $this -> addr;
        return $this -> addr;
    }
    function debug_txt($filename,$value){
        $f = fopen($filename,'w');
        fwrite($f,$value);
        fclose($f);
    }
    function curl_request($url,$post = '',$cookie = '', $returnCookie = 0) {
      $ip_long = array(
        array('607649792', '608174079'), //36.56.0.0-36.63.255.255
        array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
        array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
        array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
        array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
        array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
        array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
        array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
        array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
        array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
      );
      $rand_key = mt_rand(0, 9);
      $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][3]));
      //随机ip
      $header = array(
        "CLIENT-IP: $ip",
        "X-FORWARDED-FOR: $ip",
        "X-Real-IP: $ip"
      );
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_USERAGENT, 'User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11');
      curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
      curl_setopt($curl, CURLOPT_REFERER, "https://music.163.com");
      if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
      }
      if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
      }
      curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
      curl_setopt($curl, CURLOPT_TIMEOUT, 10);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      $data = curl_exec($curl);
      if (curl_errno($curl)) {
        return curl_error($curl);
      }
      curl_close($curl);
      if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie'] = substr($matches[1][0], 1);
        $info['content'] = $body;
        return json_decode($info,true);
      } else {
        return json_decode($data,true);
      }
    }
    function send_req($url,$pars){
        $ch = curl_init();
        //指定URL
        curl_setopt($ch, CURLOPT_URL, $url);
        //设定请求后返回结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //声明使用POST方式来进行发送
        curl_setopt($ch, CURLOPT_POST, 1);
        //curl_setopt($curl, CURLOPT_USERAGENT, 'Chrome 42.0.2311.135');
        //发送什么数据呢
        curl_setopt($ch, CURLOPT_POSTFIELDS, $pars);
        //忽略证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //忽略header头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        //发送请求
        
        $output = curl_exec($ch);
        //关闭curl
        ;
        curl_close($ch);
        
        return $output;
    }
    function send_message($chatid,$message,$reply="",$inlinep = ""){
        $token = $this -> token;
        $this -> url = "https://api.telegram.org/bot$token/sendMessage";
        if($reply == ""){
            $this -> req = array(
                
                "chat_id" => $chatid,
                "text" => $message,
                "disable_web_page_preview" => true,
                "reply_markup" => $inlinep
                );
        }
        else{
            $this -> req = array(
                
                "chat_id" => $chatid,
                "text" => $message,
                "disable_web_page_preview" => true,
                "reply_to_message_id" => $reply,
                "reply_markup" => $inlinep
            
                );
        }
        $this -> result = json_decode($this -> send_req($this -> url,$this -> req),true);
        return $this -> result;
    }

    function editmes($chatid,$message_id,$content){
        $token = $this -> token;
        $this -> url = "https://api.telegram.org/bot$token/editMessageText";
        $this -> req = array(
                
                "chat_id" => $chatid,
                "message_id" => (int)$message_id,
                "text" => "$content"
                );
        $this -> result = $this -> send_req($this -> url,$this -> req);
        return $this -> result;
    }
    
    function deletemes($chatid,$message_id){
        $token = $this -> token;
        $this -> url = "https://api.telegram.org/bot$token/deleteMessage";
        $this -> req = array(
                
                "chat_id" => $chatid,
                "message_id" => (int)$message_id
                );
        $this -> result = $this -> send_req($this -> url,$this -> req);
        return $this -> result;
    }
    
    function sendaudio($id_name,$chatid,$message_id="",$file_id="",$inlinep=""){
        $token = $this -> token;
        $url = "https://api.telegram.org/bot$token/sendAudio";
        //$id_name = urlencode($id_name);
        if($file_id == ""){
            if($message_id == ""){
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "audio" => "https://bot.bsot.cn/$token/temp/music/$id_name.mp3",
                    "reply_markup" => $inlinep
                                        
                );
                
            }
            else{
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "audio" => "https://bot.bsot.cn/$token/temp/music/$id_name.mp3",
                    "reply_to_message_id" => (int)$message_id,
                    "reply_markup" => $inlinep
                                    
                );
            }
        }
        else{
            if($message_id == ""){
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "audio" => "$file_id",
                    "reply_markup" => $inlinep
                                        
                );
                
            }
            else{
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "audio" => "$file_id",
                    "reply_to_message_id" => (int)$message_id,
                    "reply_markup" => $inlinep
                                    
                );
            }
        }
        return json_decode($this -> send_req($url,$audioad),true);
        
    }
    
    function sendqrcode($photoname,$chatid,$message_id="",$file_id=""){
        $token = $this -> token;
        $url = "https://api.telegram.org/bot$token/sendPhoto";
        $id_name = urlencode($id_name);
        if($file_id == ""){
            if($message_id == ""){
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "photo" => "https://bot.bsot.cn/$token/temp/qrcode/$photoname.png"
                                        
                );
                
            }
            else{
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "photo" => "https://bot.bsot.cn/$token/temp/qrcode/$photoname.png",
                    "reply_to_message_id" => (int)$message_id
                                    
                );
                
            }
        }
        else{
            if($message_id == ""){
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "photo" => "$file_id"
                                        
                );
                
            }
            else{
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "photo" => "$file_id",
                    "reply_to_message_id" => (int)$message_id
                                    
                );
            }
        }
        
        return json_decode($this -> send_req($url,$audioad),true);
        
    }
    
    function sendvoice($id_name,$chatid,$message_id="",$file_id=""){
        $token = $this -> token;
        $url = "https://api.telegram.org/bot$token/sendAudio";
        $id_name = urlencode($id_name);
        if($file_id == ""){
            if($message_id == ""){
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "audio" => "https://bot.bsot.cn/$token/temp/voice/$id_name.mp3"
                                        
                );
                
            }
            else{
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "audio" => "https://bot.bsot.cn/$token/temp/voice/$id_name.mp3",
                    "reply_to_message_id" => (int)$message_id
                                    
                );
                
            }
        }
        else{
            if($message_id == ""){
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "audio" => "$file_id"
                                        
                );
                
            }
            else{
                $audioad = array(
                                    
                    "chat_id" => $chatid,
                    "audio" => "$file_id",
                    "reply_to_message_id" => (int)$message_id
                                    
                );
            }
        }
        return json_decode($this -> send_req($url,$audioad),true);
        
    }
    
}

如有疑问,欢迎联系我
QQ :3319066174
邮箱 : admincai@cxbsoft.top
Telegram : @cxbsoft

这里有一个DEMO bot:xbot

最后修改:2020 年 03 月 17 日
如果觉得我的文章对你有用,请随意赞赏