* 先準備 2 支手機(在本筆記,2 支手機都是 Android),telegram 沒法建立一人群組(應該說我沒試成功)
* 2 支手機都安裝 telegram,並建立一個群組
* 在尋找聯絡人輸入 @botfather,找到後,將 botfather 加入聯絡人
* 進入 botfather 的聊天室,會看到 botfather 的招呼語【What can this bot do?】
* 輸入【/start】,botfather 會列出一堆跟 bot 有關的指令
* 輸入【/newbot】
* botfather 會請您為您的 bot 取名字,因為後續的互動會是 json 格式,所以建議這次先以英文命名,較容易在 json 字串中辨識、找到。
* 接下來,botfather 請您設定您的 bot 的 id,bot 的 id 必須以 【bot】結尾,ex:TetrisBot 或 tetris_bot,這個 id 必須是在 telegram 唯一的,所以若您設定的名字已經有別人先用了,botfather 會請您改名字。
* 建立您的 bot 後,可輸入【/help】進一步了解
* 輸入【/mybots】,會得到您的 bot 的 token,格式是 【一串數字:大小寫英數字混合字串】很重要!請好好保存。
* 將 bot 加入群組
→ 由群組中的任一人發送一個訊息到群組
→ 點擊標題欄,可以看到這個群組的成員,並且下方有個標題為【Links】的區塊,點擊第一個連結(最後面以 【/getUpdates】結尾),就會看到一段 json 字串,將這段 json 字串複製出來,並尋找其中
... ... "chat":{"id":-0123456789, "title":"mytest", "type":"group", "all_members_are_administrators":false } ... ...這個就是群組的 id,通常是負數,type 是 group
如果找不到群組 id,請多試幾次(群組某人發送訊息,然後看 json 字串),甚至將 bot 踢出群組再重加入。
寫個測試的 PHP 程式
<?php date_default_timezone_set('Asia/Taipei'); $sToken = "0123456789:AAG9Sxwv3zc9YblablablaiBBJ3ZOUO4lFY"; // bot 的 token $sGroupId = "-9876543210"; // 群組 id // 訊息內容 $sMsg = "Hello, this is oldgrayduck's telegram Bot test, ".date('Y-m-d H:i:s'); $url = "https://api.telegram.org/bot$sToken/sendMessage"; $data = [ 'chat_id' => $sGroupId, 'text' => $sMsg ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); // 顯示回應 echo $result; ?>
群組就會收到訊息了。
沒有留言:
張貼留言