Telegram php示例发送消息

时间:2015-07-24 21:56:23

标签: telegram

我找不到一个通过电报协议从php发送消息的例子。我尝试使用this但失败了。你能举个例子吗?

3 个答案:

答案 0 :(得分:18)

我使用以下功能:

function sendMessage($chatID, $messaggio, $token) {
    echo "sending message to " . $chatID . "\n";

    $url = "https://api.telegram.org/bot" . $token . "/sendMessage?chat_id=" . $chatID;
    $url = $url . "&text=" . urlencode($messaggio);
    $ch = curl_init();
    $optArray = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true
    );
    curl_setopt_array($ch, $optArray);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

你以这种方式打电话

$token = "<insert bot token here>";
$chatid = "<chatID>";
sendMessage($chatid, "Hello World", $token);

答案 1 :(得分:6)

简单方法:

$token = "YOUR_BOT's_TOKEN";

$data = [
    'text' => 'your message here',
    'chat_id' => 'the_chat_id_here'
];

file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($data) );

答案 2 :(得分:5)

好吧,这似乎是一个相当古老的帖子,但没有答案,所以我希望它可以帮助某人。您可以使用我正在开发的以下存储库Telegram Bot Client in PHP中的示例。这是我用来发送消息的方法。

// initialise variables here
$chat_id = 1231231231;
// path to the picture, 
$text = 'your text goes here';
// following ones are optional, so could be set as null
$disable_web_page_preview = null;
$reply_to_message_id = null;
$reply_markup = null;

$data = array(
        'chat_id' => urlencode($chat_id),
        'text' => urlencode($text),
        'disable_web_page_preview' => urlencode($disable_web_page_preview),
        'reply_to_message_id' => urlencode($reply_to_message_id),
        'reply_markup' => urlencode($reply_markup)
    );

$url = https://api.telegram.org/botYOUR_TOKEN_GOES_HERE/sendMessage;

//  open connection
$ch = curl_init();
//  set the url
curl_setopt($ch, CURLOPT_URL, $url);
//  number of POST vars
curl_setopt($ch, CURLOPT_POST, count($data));
//  POST data
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//  To display result of curl
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//  execute post
$result = curl_exec($ch);
//  close connection
curl_close($ch);