【问题标题】:Telegram php example send message [closed]Telegram php示例发送消息[关闭]
【发布时间】:2015-10-15 17:01:34
【问题描述】:

我找不到通过电报协议从 php 发送消息的示例。 你能给我一些功能性的例子吗?

【问题讨论】:

  • 你找到解决办法了吗?
  • 查看my answer

标签: telegram


【解决方案1】:

我使用以下函数:

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);

【讨论】:

  • 他在问核心 api,而不是 bot api!
  • 似乎很多电报开发者都是伊朗人?但我正在寻找关于机器人的简单示例......所有库在 c# 和 php 中都很复杂。有没有供 php 开发人员使用的代码库?或任何培训或教程?
  • 您能否在答案中添加如何解析响应。 {"ok":false,"error_code":400,"description":"Bad Request: chat not found"}
【解决方案2】:

简单的方法:

$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) );

【讨论】:

    【解决方案3】:

    嗯,这似乎是一个很老的帖子,但没有答案,所以我希望它对某人有所帮助。您可以使用我目前正在开发的以下存储库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);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多