Telegram

Hotspot On-Login Telegram Notification — 7

Put it in a hotspot user profile's On Login field. Every login sends a Telegram message with voucher name, IP, MAC, device name, login method, data quota, note/expiry, profile and number of online users.

MikroTik Version

RouterOS 7

# EN: Telegram bot token from @BotFather | AR: توكن البوت من @BotFather
:local botToken "change here";
# EN: Telegram chat ID that receives the alerts | AR: رقم الشات الذي سيستقبل التنبيهات
:local chatId "change here";

# EN: Runs only after the two variables are edited, so it never blocks other On-Login code
# AR: لا يعمل إلا بعد تعديل المتغيرين حتى لا يعطل باقي أكواد On-Login
:if ($botToken != "change here" && $chatId != "change here") do={

    # EN: Helper: makes text safe for the Telegram URL (space -> +, & -> %26) | AR: دالة تجهز النص لرابط تيليجرام (المسافة إلى + و & إلى %26)
    :local safe do={
        :local out "";
        :if ([:len $s] > 0) do={
            :for i from=0 to=([:len $s] - 1) do={
                :local c [:pick $s $i ($i + 1)];
                :if ($c = " ") do={ :set c "+" };
                :if ($c = "&") do={ :set c "%26" };
                :set out ($out . $c);
            }
        }
        :return $out;
    }

    # EN: $user, $address and $"mac-address" are provided by the hotspot at login
    # AR: المتغيرات $user و $address و $"mac-address" يوفرها الهوتسبوت عند الدخول
    :local userRow [/ip hotspot user find where name=$user];
    :local voucherNote [/ip hotspot user get $userRow comment];
    :local pkg [/ip hotspot user get $userRow profile];
    :local viaMethod [/ip hotspot active get [find where user=$user] login-by];
    :local online [:len [/ip hotspot active find]];

    # EN: Data quota in MB ("Unlimited" when no limit is set) | AR: حصة البيانات بالميجا (Unlimited عند عدم وجود حد)
    :local quota "Unlimited";
    :local limitBytes [/ip hotspot user get $userRow limit-bytes-total];
    :if ([:typeof $limitBytes] = "num") do={
        :if ($limitBytes > 0) do={ :set quota (($limitBytes / 1048576) . "+MB") }
    }

    # EN: Device name from the DHCP lease | AR: اسم الجهاز من DHCP
    :local device "unknown";
    :do { :set device [/ip dhcp-server lease get [find where address=$address] host-name] } on-error={}

    :local nl "%0A";
    :local text ("LOGIN" . $nl . "Voucher:+" . [$safe s=$user] . $nl . "IP:+" . $address . $nl . "MAC:+" . $"mac-address" . $nl . "Device:+" . [$safe s=$device] . $nl . "Login+by:+" . $viaMethod . $nl . "Quota:+" . $quota . $nl . "Note/Expiry:+" . [$safe s=$voucherNote] . $nl . "Time:+" . [/system clock get date] . "+" . [/system clock get time] . $nl . "Profile:+" . [$safe s=$pkg] . $nl . "Users+online:+" . $online);

    # EN: Send the message | AR: إرسال الرسالة
    /tool fetch url=("<https://api.telegram.org/bot>" . $botToken . "/sendMessage?chat_id=" . $chatId . "&text=" . $text) keep-result=no;
}