Search code examples
phptesseract

Send multiple results as single message with line breaks to telegram bot in PHP


I'm running tesseract on images in images folder and if the OCR result has "Error occurred" text then I want to send all the pictures names with error message concatenated as a single message with lines breaks of course for each message.

With the below code I'm receiving separate messages for every single picture result.

But I want Something like as on this picture all as a single message. Example picture

Here is my code tho;

$dir = "images/*.jpg";

$images = glob( $dir );

foreach( $images as $image):

$result = (new TesseractOCR($image))
->run();

$info = pathinfo($image);
$file_name =  basename($image,'.'.$info['extension']);
$Name = str_replace("_"," ", $file_name);

$msg = "Error Occurred";

if($result === $msg)
{
    $err = $Name . " - Says - ".$msg."\n";

    $apiToken = $bot_token;
    $data = [
        'chat_id' => $chat_id,
        'text' => $err
    ];
    $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data) );
    
}
else 
{
    

    $msg = $Name . " - Good! \n";

    echo $msg."</br>";

}

endforeach;


Solution

  • Sending of the message needs to happen outside of the foreach loop

    I have changed the code to collect all the errors into an array then after the loop if any errors exist, it implodes the array into a multiline string and sends the message

    <?php
    
    $dir = "images/*.jpg";
    
    $images = glob($dir);
    
    $errors = [];
    
    foreach ($images as $image) {
    
        $result = (new TesseractOCR($image))
            ->run();
    
        $info = pathinfo($image);
        $file_name = basename($image, '.' . $info['extension']);
        $Name = str_replace("_", " ", $file_name);
    
        $msg = "Error Occurred";
    
        if ($result === $msg) {
            $errors[] = $Name . " - Says - " . $msg;
        }
        else {
            $msg = $Name . " - Good! \n";
            echo $msg . "</br>";
        }
    }
    
    if (count($errors) > 0) {
        $apiToken = $bot_token;
        $data = [
            'chat_id' => $chat_id,
            'text' => implode("\n", $errors)
        ];
        $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data));
    }