telegram创建机器人,接口调用机器人

【开发云】年年都是折扣价,不用四处薅羊毛


一、创建机器人

浏览器打开 https://t.me/botfather,进入客户端显示如下图
在这里插入图片描述

二、使用步骤

1.输入创建机器人消息/newbot

在这里插入图片描述
以次输入名称和用户即可创建成功

2.机器人命令列表

在这里插入图片描述

3.查看我的机器人

在这里插入图片描述
在消息输入命令 回车即可
在这里插入图片描述
出现刚才创建的机器人,证明创建成功

4.php接口调用机器人

<?php

/**
 * @desc Telegram机器人接口对接api
 * Class Tgapi
 */
class Tgapi
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

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

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

    }

    /**
     * @desc 设置更新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为成功
    }

    /**
     * @desc 对机器人进行回调Api-api/tg/tgapi/processMessage 机器人回调信息方法
     * @return mixed|string
     */
    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;
    }
}

配置好token,设置webhook,发消息给机器人就可以回调到自己服务器了


CSDN开发云

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值