Telegram Bot 教學

從零開始的 Telegram Bot
<?php
class Telegram {
    public $data;
    public $ChatID;
    public $FromID;
    public $MsgID;
    public $BOT;
    public $botName;

    public $_CONFIG;

    private $_BAN = [
    ];
    private $_sentDebug = false;
    private $curl = false;


    public function __construct(bool $getData = false) {
        $this->_CONFIG = require('config.php');

        $this->curl = curl_init();

        if (!$getData)
            return;

        if (!isset($_GET['bot']))
            exit('No Bot Name');

        $this->BOT = $_GET['bot'];

        if (!array_key_exists($this->BOT, $this->_CONFIG))
            exit('Not Isset This Bot');

        if ($_GET['Token'] != sha1($this->_CONFIG[$this->BOT]['Token']))
            exit('Are you hacking me?');

        $data = file_get_contents('php://input');
        $this->data = json_decode($data, true);

        $this->botName = $this->_CONFIG[$this->BOT]['Name'];
        $this->ChatID = $this->data['message']['migrate_to_chat_id'] ??
            $this->data['message']['chat']['id'] ??
            $this->data['edited_message']['chat']['id'] ??
            $this->data['inline_query']['from']['id'] ??
            $this->data['chosen_inline_result']['from']['id'] ??
            $this->data['callback_query']['message']['chat']['id'] ??
            $this->data['callback_query']['message']['from']['id'] ??
            $this->data['callback_query']['chat']['id'] ??
            $this->data['callback_query']['from']['id'] ??
            $this->data['channel_post']['chat']['id'] ??
            $this->data['edited_channel_post']['chat']['id'] ??
            109780439;

        $this->FromID = $this->data['message']['from']['id'] ??
            $this->data['edited_message']['from']['id'] ??
            $this->data['inline_query']['from']['id'] ??
            $this->data['chosen_inline_result']['from']['id'] ??
            $this->data['callback_query']['from']['id'] ??
            $this->data['channel_post']['from']['id'] ??
            $this->data['edited_channel_post']['from']['id'] ??
            109780439;

        $this->MsgID = $this->data['message']['message_id'] ??
            $this->data['edited_message']['message_id'] ??
            $this->data['inline_query']['id'] ??
            $this->data['chosen_inline_result']['id'] ??
            $this->data['callback_query']['message']['message_id'] ??
            $this->data['callback_query']['inline_message_id'] ??
            $this->data['callback_query']['id'] ??
            $this->data['channel_post']['message_id'] ??
            $this->data['edited_channel_post']['message_id'] ??
            0;

        file_put_contents("/temp/tg-log/" . date("Y-m-d") . "-received-{$this->BOT}", json_encode($this->data, JSON_PRETTY_PRINT) . "\n\n", FILE_APPEND);

        if (in_array($this->FromID, $this->_BAN))
            exit;
    }

    public function getTelegram(string $method, array $query = []): array {
        if (isset($query['bot']) && isset($this->_CONFIG[$query['bot']]['Token']))   # if assign to specific bot
            $bot = $this->_CONFIG[$query['bot']];
        else if (isset($this->_CONFIG[$this->BOT]['Token']))
            $bot = $this->_CONFIG[$this->BOT];
        else
            $bot = 'Sean';

        $botToken = $bot['Token'];

        $json = json_encode($query);

        $url = "https://api.telegram.org/bot{$botToken}/{$method}";

        curl_setopt_array($this->curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $json."\n",
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json; charset=utf-8'
            ]
        ]);
        $data = curl_exec($this->curl);

        $result = json_decode($data, true);
        if (is_null($result))
            $result = $data;

        file_put_contents("/temp/tg-log/" . date("Y-m-d") . "-getTelegram-{$bot['Name']}", $method . json_encode($query, JSON_PRETTY_PRINT) . "\n" . json_encode($result, JSON_PRETTY_PRINT) . "\n\n\n", FILE_APPEND);

        if (!$result['ok'] && !isset($query['ignore_error']) && $result['error_code'] != 429 && $data['error_code'] != 403) {   # Too Many Request, shouldn't send more debug message
            $this->_debug($result);
        }

        return $result;
    }

    public function getPWRT(string $method, array $query = []): array {
        if (isset($query['bot']) && isset($this->_CONFIG[$query['bot']]['Token']))   # if assign to specific bot
            $bot = $this->_CONFIG[$query['bot']];
        else if (isset($this->_CONFIG[$this->BOT]['Token']))
            $bot = $this->_CONFIG[$this->BOT];
        else
            $bot = 'Sean';

        $botToken = $bot['Token'];

        $fields = '';
        foreach ($query as $key => $val) {
            $fields .= $key . '=' . json_encode($val) . '&';
        }

        $url = "https://api.pwrtelegram.xyz/bot{$botToken}/{$method}";

        curl_setopt_array($this->curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $fields."\n",
        ]);
        $data = curl_exec($this->curl);

        $result = json_decode($data, true);

        file_put_contents("/temp/tg-log/" . date("Y-m-d") . "-getTelegram-{$bot['Name']}", $method . json_encode($query, JSON_PRETTY_PRINT) . "\n" . json_encode($result, JSON_PRETTY_PRINT) . "\n\n\n", FILE_APPEND);

        if (!$result['ok'] && $result['error_code'] != 429) {   # Too Many Request, shouldn't send more debug message
            $this->_debug($result);
        }

        return $result;
    }

    public function sendMsg(array $option): array {
        if (!isset($option['text']))
            return [];

        if (!isset($option['chat_id']))
            if (isset($this->ChatID))
                $option['chat_id'] = $this->ChatID;
            else
                return [];

        return $this->getTelegram('sendMessage', $option);
    }

    public function deleteMsg(int $chat, int $msg): array {
        return $this->getTelegram('deleteMessage', [
            'chat_id' => $chat,
            'message_id' => $msg,
        ]);
    }

    public function sendPhoto(array $query): array {
        return $this->getTelegram('sendPhoto', $query);
    }

    public function editMarkup(array $query): array {
        return $this->getTelegram('editMessageReplyMarkup', $query);
    }

    public function enHTML(string $str = ''): string {
        $search =  array('&', '"', '<', '>');
        $replace = array('&amp;', '&quot;', '&lt;', '&gt;');
        $str = str_replace($search, $replace, $str);
        return $str;
    }


    public function _debug($data = NULL) {
        if (!$this->_sentDebug) {
            $result = $this->sendMsg([
                'bot' => 'Sean',
                'chat_id' => -1001071715330,
                'text' => $this->BOT . substr(json_encode($this->data, JSON_PRETTY_PRINT), 0, 4000)
            ]);
            $this->_sentDebug = $result['result']['message_id'];
        }

        if (isset($data))
            $this->sendMsg([
                'bot' => 'Sean',
                'chat_id' => -1001071715330,
                'reply_to_message_id' => $this->_sentDebug,
                'text' => $this->BOT . substr(json_encode($data, JSON_PRETTY_PRINT), 0, 4000)
            ]);
    }
}