php - Telegram Bot 上的翻译
问题描述
if (strpos($message, "/translate") === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
file_get_contents($apiURL."/sendmessage?chat_id=".$chatID."&text=Hasil translate: ".$word." : $mymemori ");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_string);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(($html = curl_exec($ch)) === false) {
echo 'Curl error: ' . curl_error($ch);
die('111');
}
}
大家好,我正在尝试使用 php 在电报上制作翻译机器人,但输出仍然是错误或根本没有输出。我正在使用这个 API https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|id 请帮助如何获取翻译
错误输出图像
解决方案
首先,我建议使用 cURL,而不是file_get_contents
。
其次,无需回显任何内容,因为该 URL 将被 webhook 访问,而不是人类。
第三,您需要一种向 Telegram Bot API 发送请求的方法。
使用这个新代码:
define('Token', '<your_bot_token>');
# Reading the update from Telegram
$update = json_decode(file_get_contents('php://input'));
$message = $update->message;
$text = $message->text;
if (strpos($text, '/translate') === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
//
Bot('sendMessage', [
'chat_id' => $update->message->chat->id,
'text' => "Hasil translate: $word : $mymemori "
]);
}
function Bot(string $method, array $params = [])
{
$ch = curl_init();
$api_url = 'https://api.telegram.org/bot' . Token . "/$method";
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
if ($result->ok == false)
{
throw new Exception($result->description, $result->error_code);
}
return $result->result;
}
推荐阅读
- php - 如何修复“未捕获的语法错误:JSON 中的意外令牌 _ 位置......”
- vba - 如何在 span id 下获取内部文本
- d3.js - 将对象数据转换为 d3plus-react 的数组
- java - 包中的类如何使用同一个包的静态方法中的其他类?
- python-3.x - Python:与 Yubikey 的 TLS 会话
- javascript - 使用javascript在html画布中动画圈
- php - 如何创建一个包含数据库字段和上传到服务器的相应文件的 html 表
- python - 检测到的表中的数据
- html - 媒体查询后没有触发css动画
- c# - 运行EXE文件C#后如何插入参数