I’m working on a Telegram bot using PHP and I’m stuck with a timing issue. Here’s what I’m trying to do:
User clicks a button that triggers a callback query
Bot waits for 2 minutes
Bot sends a message to the user
Bot updates the database
I’m not sure how to implement this delay and automatic execution. Any ideas on how to achieve this? I’ve tried using sleep() but it seems to block the entire script. Is there a better way to handle this kind of timed action in a Telegram bot?
Here’s a basic example of what I have so far:
function handleCallbackQuery($callbackQuery) {
$chatId = $callbackQuery->getMessage()->getChat()->getId();
// What to do here to delay the message and database update?
// sendMessageAfterDelay($chatId, 'This message should appear after 2 minutes');
// updateDatabase();
}
have u tried using a message queue? smthing like RabbitMQ could work. You’d push the task to the queue when the callback happens, then have a separate process that checks the queue every few seconds. when it finds a task thats 2 mins old, it sends the message and updates the DB. keeps ur bot responsive and handles the delay nicely
I’ve faced a similar challenge with timed actions in Telegram bots. The key is to avoid blocking operations like sleep(). Instead, you could leverage a job queue system or a cron job to handle the delayed actions.
For a simple solution, you might consider using the ‘at’ command on Unix-like systems. Here’s a rough idea:
When the callback query is received, create a unique identifier for this action, then write a small PHP script that sends the message and updates the database. Use exec() to schedule this script to run after 2 minutes using ‘at’.
Something like:
$uniqueId = uniqid();
$command = "echo 'php /path/to/delayed_action.php $chatId $uniqueId' | at now + 2 minutes";
exec($command);
This approach offloads the delay to the system, allowing your bot to continue processing other requests. Just ensure your server supports the ‘at’ command and your PHP has the necessary permissions.
Remember to handle potential issues like duplicate actions or missed executions in your delayed_action.php script.
While the ‘at’ command approach can be effective in some cases, it might not be ideal in all hosting environments. An alternative is to handle delayed tasks by recording them in a database. When a callback query is received, the bot can insert an entry with the chat ID, message details, and the intended execution time into a dedicated table. A separate process, such as a cron job running every minute, can then check for tasks whose execution times have passed, send the messages, update the main database, and mark the tasks as completed.
This approach is more portable and provides better control over task execution and management.