I have a Telegram bot that will send new posts from certain pages on Twitter and Facebook.
I did it this way:
function checkTwitterPost($post, $author) {
$tw_last_post = strtotime($post['created_at']);
$twitter_last_update_path = './timestamps/'.$author.'_twitter_last_update.txt';
if (file_exists($twitter_last_update_path)) {
$tw_last_update = (int)file_get_contents($twitter_last_update_path);
} else {
$tw_last_update = 0;
}
file_put_contents($twitter_last_update_path, $tw_last_post);
if ($tw_last_post > $tw_last_update) {
unset($tw_last_update);
return true;
}
unset($tw_last_update);
return false;
}
function checkFacebookPost($post, $author) {
$fb_last_post = strtotime($post->created_time);
$facebook_last_update_path = './timestamps/'.$author.'_facebook_last_update.txt';
if (file_exists($facebook_last_update_path)) {
$fb_last_update = (int)file_get_contents($facebook_last_update_path);
} else {
$fb_last_update = 0;
}
file_put_contents($facebook_last_update_path, $fb_last_post);
if ($fb_last_post > $fb_last_update) {
unset($fb_last_update);
return true;
}
unset($fb_last_update);
return false;
}
$bot->command('start', function ($message) use ($bot) {
@unlink('./timestamps/user1_facebooke_last_update.txt');
@unlink('./timestamps/user1_twitter_last_update.txt');
@unlink('./timestamps/user2_facebooke_last_update.txt');
@unlink('./timestamps/user2_twitter_last_update.txt');
$users = array(
'user1' => ['facebook'=>'user1', 'twitter'=>'user1'],
'user2' => ['facebook'=>'user2', 'twitter'=>'user2'],
);
while (true) {
$account = $users['user1']['facebook'];
$post = FacebookUtil::getLastPost($account);
if (checkFacebookPost($post, $account)) {
$bot->sendMessage($message->getChat()->getId(), $post->message);
}
unset($post);
$account = $users[user1]['twitter'];
$post = TwitterUtil::getLastPost($account);
if (checkTwitterPost($post, $account)) {
$bot->sendMessage($message->getChat()->getId(), $post->message);
}
unset($post);
$account = $users['user2']['facebook'];
$post = FacebookUtil::getLastPost($account);
if (checkFacebookPost($post, $account)) {
$bot->sendMessage($message->getChat()->getId(), $post->message);
}
unset($post);
$account = $users['user2']['twitter'];
$post = TwitterUtil::getLastPost($account);
if (checkTwitterPost($post, $account)) {
$bot->sendMessage($message->getChat()->getId(), $post['text']);
}
unset($post);
sleep(1500);
}
});
It's works, but causes memory problems. After some time, the server falls down.
Are there any more suitable solutions?
Or I can somehow optimize this approach?