I’m currently working on a Telegram bot using PHP, and I’ve run into a problem. I keep user chat IDs in my database to send mass messages. When I enter the command /admin sendall:hello, it should ideally send the message just once to all users. However, at times, it ends up sending the same message repeatedly without stopping, and I have to clear my database to fix it.
Here’s an excerpt of my command handling code:
case '/admin':
if ($chat_id === 'admin_chat_id') {
$commandParts = str_replace('/admin', '', $message);
$commandParts = trim($commandParts);
$splitCommands = explode(':', $commandParts);
$AdminCommand = new AdminCommand();
$AdminCommand->executeCommand($splitCommands[0], $splitCommands[1]);
} else {
sendMessage($chat_id, 'You have been blocked.');
}
break;
Here’s how the AdminCommand class looks:
class AdminCommand extends Database {
public function executeCommand($command, $argument = null) {
switch ($command) {
case 'sendall':
$this->sendToAll($argument);
break;
default:
break;
}
}
public function sendToAll($message) {
$stmt = $this->con->prepare('SELECT * FROM `users`');
$stmt->execute();
$userList = $stmt->fetchAll();
foreach ($userList as $user) {
sendMessage($user['chatid'], $message);
}
exit();
}
}
This is the sendMessage function I use:
function sendMessage($chatId, $message) {
$url = BOT_URL . "/sendMessage?chat_id=" . $chatId . "&text=" . urlencode($message);
file_get_contents($url);
}
Can anyone suggest what might be causing this issue where messages keep looping endlessly?