2025-02-16

【PHP】以 Telegram bot 取代 LINE notify

* 先準備 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:TetrisBottetris_bot,這個 id 必須是在 telegram 唯一的,所以若您設定的名字已經有別人先用了,botfather 會請您改名字。

* 建立您的 bot 後,可輸入【/help】進一步了解

* 輸入【/mybots】,會得到您的 bottoken,格式是 【一串數字:大小寫英數字混合字串】很重要!請好好保存


* 將 bot 加入群組

→ 由群組中的任一人發送一個訊息到群組

→ 點擊標題欄,可以看到這個群組的成員,並且下方有個標題為【Links】的區塊,點擊第一個連結(最後面以 【/getUpdates】結尾),就會看到一段 json 字串,將這段 json 字串複製出來,並尋找其中

  1.  
  2. ...
  3. ...
  4.  
  5. "chat":{"id":-0123456789,
  6. "title":"mytest",
  7. "type":"group",
  8. "all_members_are_administrators":false
  9. }
  10.  
  11. ...
  12. ...
  13.  
這個就是群組的 id,通常是負數typegroup
如果找不到群組 id,請多試幾次(群組某人發送訊息,然後看 json 字串),甚至將 bot 踢出群組再重加入。

寫個測試的 PHP 程式

  1.  
  2. <?php
  3. date_default_timezone_set('Asia/Taipei');
  4.  
  5. $sToken = "0123456789:AAG9Sxwv3zc9YblablablaiBBJ3ZOUO4lFY"; // bot 的 token
  6. $sGroupId = "-9876543210"; // 群組 id
  7. // 訊息內容
  8. $sMsg = "Hello, this is oldgrayduck's telegram Bot test, ".date('Y-m-d H:i:s');
  9. $url = "https://api.telegram.org/bot$sToken/sendMessage";
  10. $data = [
  11. 'chat_id' => $sGroupId,
  12. 'text' => $sMsg
  13. ];
  14. $ch = curl_init();
  15. curl_setopt($ch, CURLOPT_URL, $url);
  16. curl_setopt($ch, CURLOPT_POST, 1);
  17. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
  18. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  19. $result = curl_exec($ch);
  20. curl_close($ch);
  21.  
  22. // 顯示回應
  23. echo $result;
  24. ?>
  25.  


群組就會收到訊息了。

沒有留言:

張貼留言