ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Telegram机器人接口对接api

2022-04-16 14:31:48  阅读:518  来源: 互联网

标签:handle parameters Telegram 接口 api return curl array CURLOPT


<?php
namespace app\api\controller\tg;
use app\common\controller\Api;
use app\admin\model\User;

class Tgapi extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $token = null;
    protected $url = null;

    public function _initialize()
    {
        $this->token = "5203218438:AAF-uaN7mbc_gEKBpwEAG-gfGYCK6FhrffE";//token设置机器人的TOKEN,申请机器人时获取
        $this->url = 'https://api.telegram.org/bot' . $this->token . '/';//请求Telegram的URL

    }
    //hook
    // 设置更新hook地址,对机器人进行回调Api地址的绑定,这样用户给你机器发消息就可以推送到自己服务器的接口上
    public function setWebHook()
    {
        $url = "https://***.com/api/tg/tgapi/processMessage";
        $info = $this->apiRequest('setWebhook', array(
            'url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : $url
        ));
        echo $info; // 返回true为成功
    }
    /**
     * 对机器人进行回调Api
     *
     */
    public function processMessage()
    {
        $content = file_get_contents("php://input");
        $update = json_decode($content, true);
        $message = isset($update["message"]) ? $update["message"] : $update["edited_message"];

        // process incoming message
        $message_id = $message['message_id'];
        $chat_id = $message['chat']['id'];
        if (isset($message['text'])) {
            // incoming text message
            $text = $message['text'];
            $ret =User::where(["uuid"=>$text])->update([
                "chatid"=>$chat_id
            ]);
            if($ret){
                $url = $this->url.'sendMessage';
                $res = $this->post(array(
                    'chat_id' => $chat_id,
                    "text" => '绑定成功'
                ),$url);
                return $res;
            }

        } else {
            $this->apiRequest("sendMessage", array(
                'chat_id' => $chat_id,
                "text" => 'I understand only text messages'
            ));
        }
    }
    public function apiRequestWebhook($method, $parameters)
    {
        if (! is_string($method)) {
            error_log("Method name must be a string\n");
            return false;
        }

        if (! $parameters) {
            $parameters = array();
        } else if (! is_array($parameters)) {
            error_log("Parameters must be an array\n");
            return false;
        }

        $parameters["method"] = $method;

        $payload = json_encode($parameters);
//        header('Content-Type: application/json');
//        header('Content-Length: ' . strlen($payload));
        echo $payload;

        return true;
    }
    /*
     * 发送消息
     * **/
    public function sendMessage($msgtext,$chat_id,$parse_mode = "HTML"){
        $url = $this->url.'sendMessage';
        return $this->post(array(
            'parse_mode' => $parse_mode,
            'chat_id' => $chat_id,
            "text" => $msgtext
        ),$url);
    }

    public function apiRequest($method, $parameters)
    {
        if (! is_string($method)) {
            error_log("Method name must be a string\n");
            return false;
        }

        if (! $parameters) {
            $parameters = array();
        } else if (! is_array($parameters)) {
            error_log("Parameters must be an array\n");
            return false;
        }

        foreach ($parameters as $key => &$val) {
            // encoding to JSON array parameters, for example reply_markup
            if (! is_numeric($val) && ! is_string($val)) {
                $val = json_encode($val);
            }
        }
        $url = $this->url . $method . '?' . http_build_query($parameters);

        $handle = curl_init($url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($handle, CURLOPT_TIMEOUT, 60);

        return $this->exec_curl_request($handle);
    }

    public function exec_curl_request($handle)
    {
        $response = curl_exec($handle);

        if ($response === false) {
            $errno = curl_errno($handle);
            $error = curl_error($handle);
            error_log("Curl returned error $errno: $error\n");
            curl_close($handle);
            return false;
        }

        $http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
        curl_close($handle);

        if ($http_code >= 500) {
            // do not wat to DDOS server if something goes wrong
            sleep(10);
            return false;
        } else if ($http_code != 200) {
            $response = json_decode($response, true);
            error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
            if ($http_code == 401) {
                throw new Exception('Invalid access token provided');
            }
            return false;
        } else {
            $response = json_decode($response, true);
            if (isset($response['description'])) {
                error_log("Request was successful: {$response['description']}\n");
            }
            $response = $response['result'];
        }

        return $response;
    }

    public function apiRequestJson($method, $parameters)
    {
        if (! is_string($method)) {
            error_log("Method name must be a string\n");
            return false;
        }

        if (! $parameters) {
            $parameters = array();
        } else if (! is_array($parameters)) {
            error_log("Parameters must be an array\n");
            return false;
        }

        $parameters["method"] = $method;

        $handle = curl_init($this->url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($handle, CURLOPT_TIMEOUT, 60);
        curl_setopt($handle, CURLOPT_POST, true);
        curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
        curl_setopt($handle, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json"
        ));

        return $this->exec_curl_request($handle);
    }

    public function post($data,$url){
        if (is_array($data)){
            $data = http_build_query($data, null, '&');
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
}

 

标签:handle,parameters,Telegram,接口,api,return,curl,array,CURLOPT
来源: https://www.cnblogs.com/shenqilun/p/16152733.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有