首页 > 解决方案 > 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 请帮助如何获取翻译

错误输出图像

标签: phpcurltelegram-botphp-curl

解决方案


首先,我建议使用 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;
}

推荐阅读