使用PHP向Telegram bot发送消息

时间:2018-01-16 21:24:41

标签: php curl telegram-bot

我试图在这个PHP代码中使用CURL向Telegram Bot发送消息...

 <?php
  $botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";

  $website="https://api.telegram.org/bot".$botToken;
  $chatId=1234567;  //Receiver Chat Id
  $params=[
      'chat_id'=>$chatId,
      'text'=>'This is my message !!!',
  ];
  $ch = curl_init($website . '/sendMessage');
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  $result = curl_exec($ch);
  curl_close($ch);
?>

代码运行时没有错误,但我的目标Telegram bot中没有显示任何消息。

令牌是BotFather在创建目标Telegram机器人时给我的(使用此令牌访问HTTP API:<MY_DESTINATION_BOT_TOKEN>

任何建议都将受到赞赏......

4 个答案:

答案 0 :(得分:2)

您可以从@RawDataBot获取聊天ID,它将是Buffer.from(string, 'base64')

例如,在this response中将.message.chat.id

答案 1 :(得分:2)

我已经解决了....在我的原始代码中有两个错误,一个在代码中,一个在Telegram功能上,我不知道:实际上,电报僵尸网络到僵尸网络通信是这里解释不可能Simulate sending a message to a bot from url

所以我修改的代码是以下

 <?php
  $botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";

  $website="https://api.telegram.org/bot".$botToken;
  $chatId=1234567;  //** ===>>>NOTE: this chatId MUST be the chat_id of a person, NOT another bot chatId !!!**
  $params=[
      'chat_id'=>$chatId, 
      'text'=>'This is my message !!!',
  ];
  $ch = curl_init($website . '/sendMessage');
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  $result = curl_exec($ch);
  curl_close($ch);
?>

这样一切正常!

答案 2 :(得分:1)

如果要使用CURL发送电报,则需要下载文件 cacert.pem 并复制到Web服务器,然后从PHP脚本中调用它们。

您可以从

下载文件 cacert.pem
  

https://drive.google.com/open?id=1FCLH88MpKNLDXZg3pJUSAZ0BbUbNmBR2

我有一个教学视频,可以为您提供明确的答案,包括如何创建漫游器,获取令牌,获取用户chat_id,对CURL中的SSL和代理进行故障排除等:

  

这是我的教学视频https://youtu.be/UNERvcCz-Hw

的链接

这是完整的脚本:

<?php

// using GET URL Parameter -> message
$pesan = urlencode($_GET["message"]);

$token = "bot"."<token>";
$chat_id = "<chat_id>";
$proxy = "<ip_proxy>:<port>";

$url = "https://api.telegram.org/$token/sendMessage?parse_mode=markdown&chat_id=$chat_id&text=$pesan";

$ch = curl_init();

if($proxy==""){
    $optArray = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CAINFO => "C:\cacert.pem"   
    );
}
else{ 
    $optArray = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_PROXY => "$proxy",
        CURLOPT_CAINFO => "C:\cacert.pem"   
    );  
}

curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);

$err = curl_error($ch);
curl_close($ch);    

if($err<>"") echo "Error: $err";
else echo "Message SENT";

?>

答案 3 :(得分:0)

我测试了它并且它有效。 你只需要我们聊天就像下面这样:

$ chatId = '1234567';

相关问题