mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-10-01 03:32:09 +03:00
feat(tgbot): add /broadcast to relay an admin message to all clients (#6510)
* feat(tgbot): add /broadcast to relay an admin message to all clients Admins had no way to reach every client at once: notifications only cover exhausted quotas, so an operator had to copy a message to each client chat by hand. Add an admin-only /broadcast flow to the bot: - /broadcast asks for a message; any message the admin sends — text, rich text, photo, video, file, sticker or a whole album — becomes the broadcast by reference (admin chat + message ids), and a preview self-copy shows the admin exactly what recipients will get while rejecting content Telegram cannot copy before the run starts. - The draft references the original instead of parsing its content, so copyMessage/copyMessages deliver everything 1:1 on behalf of the bot with no forward header (the admin's identity stays private), no caption length pitfalls, and future Telegram message types work without new parsing. - A media group arrives as separate updates; its ids are buffered with a short debounce, sorted, and delivered as one copyMessages call so recipients see the original album. - Delivery runs in a background goroutine (common.GoRecover): sequential sends with a small pause, 429 retry_after honored per recipient, failures counted without stopping the run, progress edited into one card at most every 25 sends or 3 seconds, a cancel button checked between sends, and a final delivered/failed/skipped summary. The summary is edited into the card (only sent separately if the card is gone), so it is never duplicated. - Recipients repeat the notifyExhausted walk: clients with a linked tg_id, deduplicated, admins excluded — they already receive the reports. The message content is never logged. New i18n keys are added to all 13 locales. * fix(tgbot): harden broadcast composition per review - Key the composition per admin chat instead of one process-wide draft: two admins can now compose at once without dropping each other's drafts, and one admin's /broadcast no longer wipes another chat's half-collected album. - Bind each preview card to its own draft via a random token carried in the confirm callback, so a stale Send tap is answered with an error instead of delivering a newer, unapproved draft. - Ignore non-admin senders while a chat composes: the awaiting state is keyed by chat id, and in a group that chat is shared. - Check the cancel flag inside the flood-control retry loop, so a 429 with a long retry_after no longer holds the single broadcast slot after the admin cancelled. - Scale the per-recipient pause by the copied batch size, so an album keeps the same per-second ceiling as a single message. - Trim the comment blocks that exceeded the two-line cap. * fix(tgbot): reset broadcast state on stop and classify 403 as skipped - Clear compositions and cancel the active run from StopBot, next to the per-chat draft resets: an album debounce timer, a confirmable token or a held runner slot must not outlive the receiver that created them. - Sleep flood-control waits in 5 s slices and re-check cancel and bot state between them, so a minutes-long retry_after no longer parks the single-runner slot after the admin cancelled or the bot stopped. - Count Telegram 403 (the chat never started the bot, or blocked it) as skipped instead of failed, log it at debug rather than one warning per recipient, and append one line to the summary naming the reason. - Trim the remaining comment blocks over the two-line cap. * fix(tgbot): count unreachable recipients in broadcast progress throttle The progress card refresh was keyed on sent+failed, which a 403 does not advance since unreachable chats were split out of the failure count. A streak of unreachable recipients while that sum sat on a multiple of broadcastProgressEvery (0 included, so from the very first recipient) edited the card once per chat, doubling the request rate the send delay is sized for and defeating the throttle. Count processed recipients. * fix(tgbot): key broadcast compositions by admin, not chat After #6604 moved conversation state to the admin (chatUser), the broadcast draft map stayed keyed by chat. Two admins composing in one group then shared a slot: the second admin's message dropped the first admin's draft, whose Send tap answered "went wrong" while only the other draft could go out - the same class #6604 fixed for the add-client wizard. Drafts, album buffers and confirm tokens now live under the admin who ran /broadcast. The router now hands handleBroadcastInput only the admin whose own /broadcast is awaiting input, so its sender re-check and the test that fed it a non-admin message directly (an input no route can deliver) are removed. --------- Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
@@ -2425,6 +2425,7 @@
|
||||
"usageDesc": "Показать трафик клиента: /usage email",
|
||||
"inboundDesc": "Поиск входящих: /inbound имя (админ)",
|
||||
"restartDesc": "Перезапустить ядро Xray (админ)",
|
||||
"broadcastDesc": "Массовая рассылка всем клиентам (админ)",
|
||||
"clearallDesc": "Сбросить трафик всех клиентов (админ)"
|
||||
},
|
||||
"messages": {
|
||||
@@ -2481,6 +2482,15 @@
|
||||
"error_add_client": "⚠️ Ошибка:\n\n {{ .error }}",
|
||||
"using_default_value": "Используется значение по умолчанию👌",
|
||||
"incorrect_input": "Ваш ввод недействителен.\nФразы должны быть непрерывными без пробелов.\nПравильный пример: aaaaaa\nНеправильный пример: aaa aaa 🚫",
|
||||
"broadcastAskText": "📤 Рассылка: пришлите сообщение для ваших клиентов — текст, фото, видео, файл или целый альбом.",
|
||||
"broadcastAlreadyRunning": "❗ Рассылка уже идёт, дождитесь её завершения.",
|
||||
"broadcastNoRecipients": "❗ Нет клиентов с привязанным Telegram ID.",
|
||||
"broadcastPreview": "📤 Это сообщение уйдёт {{ .Count }} получателям. Отправить?",
|
||||
"broadcastNotCopyable": "❗ Это сообщение нельзя скопировать для рассылки. Пришлите другое.",
|
||||
"broadcastUnreachable": "ℹ️ {{ .Count }} получателей ни разу не начинали диалог с ботом (или заблокировали его) — им нельзя написать. Попросите их нажать Start.",
|
||||
"broadcastProgress": "📤 Отправлено {{ .Sent }} из {{ .Total }} (не доставлено: {{ .Failed }})\r\n",
|
||||
"broadcastFinished": "✅ Рассылка завершена.\r\n👥 Получателей: {{ .Total }}\r\n📨 Доставлено: {{ .Sent }}\r\n🚫 Не доставлено: {{ .Failed }}\r\n⏭ Пропущено: {{ .Skipped }}\r\n⏱ Время: {{ .Time }}\r\n",
|
||||
"broadcastCanceled": "🛑 Рассылка отменена.\r\n👥 Получателей: {{ .Total }}\r\n📨 Доставлено: {{ .Sent }}\r\n🚫 Не доставлено: {{ .Failed }}\r\n⏭ Пропущено: {{ .Skipped }}\r\n⏱ Время: {{ .Time }}\r\n",
|
||||
"AreYouSure": "Вы уверены? 🤔",
|
||||
"SuccessResetTraffic": "📧 Почта: {{ .ClientEmail }}\n🏁 Результат: ✅ Успешно",
|
||||
"FailedResetTraffic": "📧 Почта: {{ .ClientEmail }}\n🏁 Результат: ❌ Неудача \n\n🛠️ Ошибка: [ {{ .ErrorMessage }} ]",
|
||||
@@ -2499,6 +2509,7 @@
|
||||
"buttons": {
|
||||
"closeKeyboard": "❌ Закрыть клавиатуру",
|
||||
"cancel": "❌ Отмена",
|
||||
"broadcastSend": "📤 Отправить",
|
||||
"cancelReset": "❌ Отменить сброс",
|
||||
"cancelIpLimit": "❌ Отменить лимит IP",
|
||||
"confirmResetTraffic": "✅ Подтвердить сброс трафика?",
|
||||
@@ -2539,6 +2550,9 @@
|
||||
"SortedTrafficUsageReport": "Отсортированный отчет об использовании трафика"
|
||||
},
|
||||
"answers": {
|
||||
"broadcastStarted": "🚀 Рассылка запущена.",
|
||||
"broadcastCanceling": "🛑 Рассылка остановится после текущего получателя.",
|
||||
"broadcastCanceled": "❌ Рассылка отменена.",
|
||||
"successfulOperation": "✅ Успешно!",
|
||||
"errorOperation": "❗ Ошибка в операции.",
|
||||
"getInboundsFailed": "❌ Не удалось получить входящие подключения.",
|
||||
|
||||
Reference in New Issue
Block a user