turnley.dev

PHP and MySQL code for faucet operators

Tools & Calculators

NTF-003

Push an admin alert to Telegram

Two API calls and a bot token. The fastest way to know your faucet is dry before your users tell you.

Problems on a faucet are urgent in a way that email is not suited to. The wallet running dry, a payout queue backing up, a signup spike that looks like a bot run — all of them get worse while you are not looking at your inbox.

Telegram's bot API is one HTTPS request with a token and a chat id. No library, no SDK, no queue.

Rate limit it at the source. An alert firing on every failed payout during an outage will hit Telegram's limits and get you nothing at the moment you most needed it.

PHP
function telegram_alert(string $message, string $level = 'info'): bool
{
    $token  = setting('telegram_token');
    $chatId = setting('telegram_chat_id');
    if ($token === '' || $chatId === '') {
        return false;
    }

    // One alert per key per interval, or an outage becomes a flood.
    $key = 'tg:' . md5($level . '|' . substr($message, 0, 60));
    if (!rate_hit(db(), $key, 1, 900)) {
        return false;
    }

    $prefix = ['info' => 'ℹ️', 'warn' => '⚠️', 'crit' => '🚨'][$level] ?? '';

    $url = 'https://api.telegram.org/bot' . rawurlencode($token) . '/sendMessage';
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query([
            'chat_id'    => $chatId,
            'text'       => trim($prefix . ' ' . $message),
            'parse_mode' => 'HTML',
            'disable_web_page_preview' => true,
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 8,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $body = curl_exec($ch);
    curl_close($ch);

    $res = json_decode((string) $body, true);
    return (bool) ($res['ok'] ?? false);
}

Using it

Get the chat id by messaging your bot once and reading https://api.telegram.org/bot<TOKEN>/getUpdates.

Alert on conditions, not events: wallet below a threshold, queue older than an hour, signups above a multiple of the daily average. Alerting on every event teaches you to ignore the channel.

Send a daily summary as well. A quiet channel is indistinguishable from a broken one until you need it.

What bites people

The bot token is a credential. In settings, never in the repository, and never in a page a visitor can reach.

Alerts must never block a request. Fire them from cron or after the response, and let failures be silent.

Telegram limits messages per chat per second. The rate guard above is not optional on a busy site.

Also in Notifications