I’m having trouble with my PHP Telegram bot. It’s designed to send messages to all users when I use a command like /moderator broadcast:Hello everyone. Usually it works fine, but sometimes it gets stuck in a loop. It keeps sending the same message over and over until I delete the database.
Here’s a simplified version of my code:
function handleCommand($command, $message) {
if ($command == '/moderator') {
$parts = explode(':', $message);
if ($parts[0] == 'broadcast') {
broadcastMessage($parts[1]);
}
}
}
function broadcastMessage($text) {
$users = fetchAllUsers();
foreach ($users as $user) {
sendTelegramMessage($user['id'], $text);
}
}
function sendTelegramMessage($userId, $text) {
$apiUrl = 'https://api.telegram.org/bot' . BOT_TOKEN . '/sendMessage';
$params = [
'chat_id' => $userId,
'text' => $text
];
file_get_contents($apiUrl . '?' . http_build_query($params));
}
Any ideas why it might be getting stuck in a loop? How can I fix this issue without having to delete my database every time it happens?
I’ve dealt with similar issues in my Telegram bots. One thing that helped was implementing a message ID check. Basically, you store the ID of the last processed message and only process new ones. Something like:
$lastProcessedId = getLastProcessedId(); // Get from database
if ($message['message_id'] > $lastProcessedId) {
handleCommand($command, $message['text']);
updateLastProcessedId($message['message_id']);
}
This way, even if the bot somehow picks up its own messages, it won’t reprocess them. Also, consider adding some logging to track when and why broadcasts are triggered. It’s helped me debug weird behavior in the past.
Just remember to clear your message ID tracker periodically, or it might get too large over time.
sounds like ur bot might be responding to its own messages. try adding a check to ignore messages from the bot itself. u could also add a cooldown timer between broadcasts to prevent spam. good luck fixing it!
The issue you’re experiencing is likely due to the bot inadvertently processing its own messages. To resolve this, implement a check to ensure the message sender isn’t the bot itself. Additionally, consider adding a unique identifier to each broadcast message and maintaining a log of sent messages. This way, you can verify if a message has already been processed before sending it again. Implementing rate limiting for the broadcast function could also help prevent accidental spam. These measures should effectively prevent the loop without necessitating database deletions.