php之使用 curl 在电报机器人中发送消息
kuangbin
阅读:54
2024-05-10 16:29:43
评论:0
我想从数据库中获取我的机器人消息并发送给用户,当我的文本只有 1 个单词时它可以工作,但现在它不起作用并显示 HTTP BAD REQUEST 400。我想我应该使用 curl,但我没有找不到任何可用于从电报机器人发送长消息的文档。(实际上是因为我是 php 的初学者)
这是我的代码
$botToken="something";
$website="https://api.telegram.org/bot".$botToken;
$update = file_get_contents("php://input");
$update = json_decode($update, true);
$chatID = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
define("dbhost", "localhost:3306"); define("dbuser", "sm");
define("dbpass", "sm"); define("database", "sm");
switch ($message){
case "/get":
connected($chatID);
break;
}
function sendMessage($chatID,$message){
$url =$GLOBALS[website]."/sendMessage?chat_id=".$chatID."&text=".$message;
//file_get_contents($url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
//checkJSON($chatID,$update);
}
function connected($chatID){
$conn = mysql_connect(dbhost,dbuser,dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
mysql_select_db( database );
$strSQL = "SELECT text FROM bott WHERE id= '1' ";
$result = mysql_query($strSQL) or die('SQL Error :: '.mysql_error());
$row = mysql_fetch_assoc($result);
$message=$row['text'];
sendMessage($chatID,$message);
mysql_close($conn);
}
function checkJSON($chatID,$update){
$myFile = "log.txt";
$updateArray = print_r($update,TRUE);
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $chatID ."\n\n");
fwrite($fh, $updateArray."\n\n");
fclose($fh);
}
?>
这是我使用 file_get_contents 时的错误
[08-Jul-2016 12:27:35 America/Chicago] PHP Warning: file_get_contents(https://api.telegram.org/bot218048829:AAF7baKISagQfALp4OIPh- yU_hMOnpFGU0A/sendMessage? chat_id=98506693&text=Introduction%0D%0AA+COMPUTER+PROCESSOR+such+as+Intel%92s+i486+used+to+cost+around+the+same+as+a+small+car.+Nowadays+a+chip+with+similar+power+is+the+price+of+a+chocolate+bar.%0D%0A): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in /home/sfduiir1/public_html/php.php on line 29
此代码不会向用户发送任何内容。
请您参考如下方法:
在 curl 方法中,您不应该使用 url 中的任何数据。
当您看到出现错误的网址时,其中的空格无效。
这是一个有效的 curl 代码:
$website="https://api.telegram.org/bot".$botToken;
$chatId=1234567; //Receiver Chat Id
$params=[
'chat_id'=>$chatID,
'text'=>'MoonLight',
];
$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);
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。