如何發訊息到 Telegram 機器人

2024-04-17

透過 Telegram api 發訊息到指定的 telegram機器人

sh 版本 script:

修改自:https://github.com/andrewintw/telegram-notify

#! /bin/bash
# Author: <https://github.com/andrewintw>
# Copyright (C) 2023 <https://github.com/andrewintw>
# https://github.com/andrewintw/telegram-notify
#
# 使用方式:
# telegram_notify.sh <訊息>
#

token="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" # Replace it with your bot token
chat_id="743690000"  #訊息接收者的 id

msg="$1"


show_usage() {
    local cmd=`basename $0`
    cat << EOF

USAGE: $cmd <MESSAGE>

NOTE: Please refer to the following guide to create a new bot 
      and generate an authentication token for your new bot.
      https://core.telegram.org/bots/features#botfather

EOF
}

send_message() {
    if [ "$token" = "" ]; then
        echo "ERROR: Token is null"
        show_usage
        exit 1
    fi

    if [ "${msg}" = "" ]; then
        show_usage
        exit 1
    fi


    local text="${msg}"
    curl --silent --request POST "https://api.telegram.org/bot${token}/sendMessage?chat_id=${chat_id}\&text=${text}" 1>/dev/null

}

send_message


php 版本 script:

<php

$msg = "你好,這是文字訊息";

$token = "105645000:AAFAXIm8KXeBV_e7JsJLGyxxxxxxx";
$API_URL = "https://api.telegram.org/bot$token/";

 $parameters["method"] = 'sendMessage';
 $parameters["chat_id"] = '743690000';
 $parameters["text"] = $msg;

  $handle = curl_init($API_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"));

  $response = curl_exec($handle);
  echo $response;

?>


參考:

telegram bot機器人的申請方式:

筆記:發送訊息到 telegram bot 機器人(python / php)

Bot API Library Examples(官方資料)

分類:軟體      619
Tag telegram ,
留言

留言