John Davidson

php - Store API previous value and compare with new one

0 comments
Message:


I developed a telegram bot whose job is to post the score of a cricket match in the telegram group. The score needs to be posted only when the new score is updated. I'm trying to store the old score in the session and then compare it with the new one.


If both values (old and new) didn't match, post the score in the group but for some unknown reason, it is not working


Here is my code


<?php

session_start();

set_time_limit(0);


$token = 'xyz';
$group_name = 'xyz';


while(true){

$ipl = file_get_contents('https://cricket-api.vercel.app/cri.php?url=https://www.cricbuzz.com/live-cricket-scores/37632/dc-vs-csk-50th-match-indian-premier-league-2021');

$ipl_data = json_decode($ipl, true);

$current_score = $ipl_data['livescore']['current'];

if($current_score != $_SESSION['old_score']){
$bot = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$group_name}&text={$current_score}";
$hit = file_get_contents($bot);
}

$_SESSION['old_score'] = $current_score;



sleep(10);

}


?>


My Answer:
php

// Start session
session_start();

// Function to get the current score from the API
function getScore() {
// Code to fetch the score from the API
return $score;
}

// Get the old score from the session
$oldScore = isset($_SESSION['oldScore']) ? $_SESSION['oldScore'] : '';

// Get the new score from the API
$newScore = getScore();

// Compare old and new score
if ($oldScore != $newScore) {
// Update the old score in the session
$_SESSION['oldScore'] = $newScore;

// Post the new score in the telegram group
// Code to post the score in the group
echo "Score posted in the group: " . $newScore;
} else {
echo "Score remains the same, no update needed.";
}
?>


Make sure to replace the `getScore()` function with the actual code to fetch the score from the API. Also, ensure that the session is properly started before using `$_SESSION` variables. If the code is still not working, you may need to debug further to identify any potential issues.

Rate this post

5 of 5 based on 1932 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us