PHP Telegram Bot Translation Feature Not Working

if (strpos($input, "/lang") === 0) {
    $text = substr($input, 6);
    $response = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$text."&langpair=en|es"), TRUE)["matches"]["translation"];
    file_get_contents($botURL."/sendmessage?chat_id=".$userID."&text=Translation result: ".$text." : $response ");
    $handle = curl_init();
    curl_setopt($handle, CURLOPT_URL, $api_string);
    curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
    
    if(($result = curl_exec($handle)) === false) {
    echo 'Curl error: ' . curl_error($handle);
    die('Error occurred');
    }
    
}

I am building a Telegram bot with PHP that should translate text using the MyMemory API. The bot responds to commands but the translation function keeps failing. When users send a message starting with the command, nothing gets translated or the bot crashes completely. I have checked the API endpoint and it works fine when tested directly in browser. The issue seems to be with how I am handling the JSON response or making the API call. Can someone help me figure out what is wrong with my implementation? The bot should take the text after the command and return the translated version but it just shows errors instead.

Your API mixing is messy, but the real problem is you’re not checking if text exists after substr. When someone types /lang without text, substr(input, 6) returns empty string and breaks the API call. Just add if(empty($text)) before the request. Also, that curl code at the end is useless - you already sent the message with file_get_contents.

I ran into the same issue with MyMemory API. Your JSON parsing is the problem - the response structure isn’t as simple as you’re treating it. You can’t just access [“matches”][“translation”] directly. The matches field is an array of translation objects, so you need $response[“matches”][0][“translation”] to grab the first match. Also, why are you making two separate HTTP requests? Pick either file_get_contents() or cURL, not both. Add some error checking for the JSON decode and verify the API response structure before accessing nested elements. The API sometimes returns empty matches or errors that’ll break your code without proper validation.

You’re not URL-encoding your text parameter - that’s what’s breaking everything. Special characters, spaces, and non-ASCII stuff will kill the request instantly. Just run urlencode() on your $text variable before you stick it in the API URL.

Your cURL setup’s also half-baked. You’re creating the handle but $api_string isn’t defined anywhere, so nothing happens. Pick one - either use file_get_contents() since it’s simple, or actually finish the cURL implementation.

Also throw in some error handling to check if the API request worked and if the JSON response has what you expect before trying to use it.