Skip to content

Cancel all active sessions

Armando Lüscher edited this page Nov 12, 2017 · 6 revisions

If you want to cancel all active conversations by a timer or cronjob, you can do it with this example script. Just add your bot API key, username and MySQL credentials.

(This example uses Carbon for calculating the expiration date, you can install it using composer require nesbot/carbon)

<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';

use Carbon\Carbon;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Telegram;

$bot_api_key       = '';
$bot_username      = '';
$mysql_credentials = [
    'host'     => 'localhost',
    'user'     => 'root',
    'password' => '',
    'database' => 'telegram_bot',
];

// This message gets sent to the user, to let him/her know that the conversation has expired. (set to null to not send a message)
$message = 'Your session expired please touch /#COMMAND# to start again';

// This is how old a conversation is regarded as active.
$expiration_limit = '15 minutes';

$telegram = new Telegram($bot_api_key, $bot_username);
$telegram->enableMySql($mysql_credentials);
$pdo = DB::getPdo();

// Prepared statement to get all expired conversations.
$stmt_expired = $pdo->prepare("
    SELECT *
    FROM `" . TB_CONVERSATION . "`
    WHERE `status` = 'active'
      AND `updated_at` < :expired
");
$stmt_expired->execute([
    ':expired' => Carbon::parse("-{$expiration_limit}")->toDateTimeString(),
]);
$expired = $stmt_expired->fetchAll(PDO::FETCH_ASSOC);

// Prepared statement to stop active conversation.
$stmt_expire = $pdo->prepare("
    UPDATE `" . TB_CONVERSATION . "`
    SET `status` = 'stopped'
    WHERE `id` = :conversation_id
");

// Stop all expired conversations.
foreach ($expired as $conversation) {
    $command = $conversation['command'];
    $user_id = $conversation['user_id'];
    $chat_id = $conversation['chat_id'];

    $is_stopped = $stmt_expire->execute([
        ':conversation_id' => $conversation['id'],
    ]);
    if (!$is_stopped) {
        echo "Failed to stop conversation '{$command}' (user_id: {$user_id}, chat_id: {$chat_id})\n";
        continue;
    }

    if ($message !== null) {
        // Let the user know that the conversation/session has been stopped/expired.
        $result = Request::sendMessage([
            'chat_id' => $chat_id,
            'text'    => str_replace('#COMMAND#', $command, $message),
        ]);

        if ($result->isOk()) {
            echo "Message sent successfully to {$chat_id}\n";
        } else {
            echo "Failed to send message to {$chat_id}\n";
        }
    } else {
        echo "No message sent to {$chat_id}\n";
    }
}