admin broadcast: accept a photo with caption, keep formatting, upload once

/system_mes and /sendusers0 only accepted plain text, so a photo with a
caption was silently ignored and nothing was sent. One _broadcast helper
now sends text (text_html) or photo (caption_html, 1024 limit checked),
uploads the photo through the main bot once and reuses its file_id,
honours retry_after and reports error reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-24 12:14:17 +00:00
parent 329c603ba3
commit 30f340543c
2 changed files with 277 additions and 156 deletions

View file

@ -275,89 +275,17 @@ class AdminBot:
async def system_mes_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start system message command - ask for message text"""
await update.message.reply_text(
"📨 Введите текст сообщения для отправки всем пользователям:\n\n"
"📨 Пришлите текст или фото с подписью для отправки всем пользователям:\n\n"
"Используйте /cancel для отмены."
)
return WAITING_FOR_SYSTEM_MESSAGE
async def handle_system_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle system message text input and send to all users"""
message_text = update.message.text
if not message_text or not message_text.strip():
await update.message.reply_text("❌ Сообщение не может быть пустым. Попробуйте снова или используйте /cancel для отмены.")
return WAITING_FOR_SYSTEM_MESSAGE
# Get all users from database
try:
conn = sqlite3.connect(self.db.db_path)
cursor = conn.cursor()
cursor.execute("SELECT user_id FROM telegram_users")
users = cursor.fetchall()
conn.close()
total_users = len(users)
if total_users == 0:
await update.message.reply_text("❌ В базе данных нет пользователей для отправки сообщения.")
return ConversationHandler.END
# Send status message
status_msg = await update.message.reply_text(
f"📤 Отправка сообщения {total_users} пользователям...\n\n"
f"Сообщение:\n{message_text}"
)
# Send message to all users
success_count = 0
failed_count = 0
# Format message with system message header
formatted_message = f"🔔 <b>System Message</b>\n\n{message_text}"
for i, (user_id,) in enumerate(users):
try:
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
async with aiohttp.ClientSession() as session:
async with session.post(url, json={
"chat_id": user_id,
"text": formatted_message,
"parse_mode": "HTML"
}, timeout=aiohttp.ClientTimeout(total=5)) as response:
if response.status == 200:
success_count += 1
else:
failed_count += 1
error_text = await response.text()
logger.warning(f"Failed to send to user {user_id}: {error_text}")
except Exception as e:
failed_count += 1
logger.error(f"Error sending to user {user_id}: {e}")
# Add small delay to avoid rate limiting (except for the last user)
if i < len(users) - 1:
await asyncio.sleep(0.05) # 50ms delay between messages
# Update status message
result_text = (
f"✅ <b>Рассылка завершена</b>\n\n"
f"📊 Статистика:\n"
f"• Всего пользователей: {total_users}\n"
f"• Успешно отправлено: {success_count}\n"
f"• Ошибок: {failed_count}\n\n"
f"<b>Отправленное сообщение:</b>\n{message_text}"
)
await status_msg.edit_text(result_text, parse_mode='HTML')
logger.info(f"System message sent: {success_count} successful, {failed_count} failed out of {total_users} users")
except Exception as e:
logger.error(f"Error in system message sending: {e}")
import traceback
logger.error(traceback.format_exc())
await update.message.reply_text(f"❌ Ошибка при отправке сообщений: {e}")
return ConversationHandler.END
"""/system_mes: send the admin's next message (text, or photo with caption) to every user."""
return await self._broadcast(
update, "SELECT user_id FROM telegram_users",
audience="пользователям", retry_state=WAITING_FOR_SYSTEM_MESSAGE, log_name="System message")
async def cancel_system_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Cancel system message command"""
await update.message.reply_text("❌ Отправка сообщения отменена.")
@ -366,94 +294,129 @@ class AdminBot:
async def sendusers0_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start sendusers0 command - ask for message text"""
await update.message.reply_text(
"📨 Введите текст сообщения для отправки пользователям без добавленных игроков:\n\n"
"📨 Пришлите текст или фото с подписью для пользователей без игроков:\n\n"
"Используйте /cancel для отмены."
)
return WAITING_FOR_USERS0_MESSAGE
async def handle_users0_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle message text input and send to users without gamers"""
message_text = update.message.text
if not message_text or not message_text.strip():
await update.message.reply_text("❌ Сообщение не может быть пустым. Попробуйте снова или используйте /cancel для отмены.")
return WAITING_FOR_USERS0_MESSAGE
# Get users without gamers from database
try:
conn = sqlite3.connect(self.db.db_path)
cursor = conn.cursor()
cursor.execute("""
"""/sendusers0: the same broadcast, only to users without any player."""
return await self._broadcast(
update,
"""
SELECT DISTINCT tu.user_id
FROM telegram_users tu
LEFT JOIN user_gamers ug ON tu.user_id = ug.user_id
WHERE ug.id IS NULL
""")
users = cursor.fetchall()
""",
audience="пользователям без игроков", retry_state=WAITING_FOR_USERS0_MESSAGE, log_name="Users0 message")
# Telegram limit for a photo caption, counted after entity parsing.
CAPTION_LIMIT = 1024
BROADCAST_HEADER = "🔔 <b>System Message</b>\n\n"
async def _broadcast(self, update: Update, users_sql: str, audience: str, retry_state, log_name: str):
"""
Send the admin's message to the users selected by users_sql through the
MAIN bot (TELEGRAM_BOT_TOKEN, raw Bot API calls — this process runs the
admin bot). Accepts plain text or a photo with a caption (it used to
accept text only, so a photo was silently ignored and nothing was sent).
The admin's formatting is kept: text_html / caption_html, not the plain
text. A file_id belongs to the bot that received the file, so the photo
is downloaded here, uploaded once by the main bot, and the file_id from
that first successful send is reused for everybody else.
"""
message = update.message
photo_bytes = None
if message.photo:
body = message.caption_html or ""
if len(self.BROADCAST_HEADER) - len("<b></b>") + len(message.caption or "") > self.CAPTION_LIMIT:
await message.reply_text(
f"❌ Подпись к фото длиннее {self.CAPTION_LIMIT} символов (Telegram не примет). "
"Сократите текст или пришлите его отдельно от картинки. /cancel — отмена.")
return retry_state
photo_file = await message.photo[-1].get_file()
photo_bytes = bytes(await photo_file.download_as_bytearray())
elif message.text and message.text.strip():
body = message.text_html
else:
await message.reply_text("❌ Нужен текст или фото с подписью. Попробуйте снова или используйте /cancel для отмены.")
return retry_state
try:
conn = sqlite3.connect(self.db.db_path)
users = [row[0] for row in conn.execute(users_sql).fetchall()]
conn.close()
total_users = len(users)
if total_users == 0:
await update.message.reply_text("❌ В базе данных нет пользователей без игроков для отправки сообщения.")
return ConversationHandler.END
# Send status message
status_msg = await update.message.reply_text(
f"📤 Отправка сообщения {total_users} пользователям без игроков...\n\n"
f"Сообщение:\n{message_text}"
)
# Send message to users without gamers
success_count = 0
failed_count = 0
# Format message with system message header
formatted_message = f"🔔 <b>System Message</b>\n\n{message_text}"
for i, (user_id,) in enumerate(users):
try:
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
async with aiohttp.ClientSession() as session:
async with session.post(url, json={
"chat_id": user_id,
"text": formatted_message,
"parse_mode": "HTML"
}, timeout=aiohttp.ClientTimeout(total=5)) as response:
if response.status == 200:
success_count += 1
else:
failed_count += 1
error_text = await response.text()
logger.warning(f"Failed to send to user {user_id}: {error_text}")
except Exception as e:
failed_count += 1
logger.error(f"Error sending to user {user_id}: {e}")
# Add small delay to avoid rate limiting (except for the last user)
if i < len(users) - 1:
await asyncio.sleep(0.05) # 50ms delay between messages
# Update status message
result_text = (
f"✅ <b>Рассылка завершена</b>\n\n"
f"📊 Статистика:\n"
f"• Всего пользователей без игроков: {total_users}\n"
f"• Успешно отправлено: {success_count}\n"
f"• Ошибок: {failed_count}\n\n"
f"<b>Отправленное сообщение:</b>\n{message_text}"
)
await status_msg.edit_text(result_text, parse_mode='HTML')
logger.info(f"Users0 message sent: {success_count} successful, {failed_count} failed out of {total_users} users")
except Exception as e:
logger.error(f"Error in users0 message sending: {e}")
import traceback
logger.error(traceback.format_exc())
await update.message.reply_text(f"❌ Ошибка при отправке сообщений: {e}")
logger.error(f"{log_name}: could not read users: {e}")
await message.reply_text(f"❌ Ошибка при чтении пользователей: {e}")
return ConversationHandler.END
if not users:
await message.reply_text(f"❌ В базе нет получателей ({audience}).")
return ConversationHandler.END
kind = "фото с подписью" if photo_bytes is not None else "текст"
status_msg = await message.reply_text(f"📤 Отправка ({kind}) {len(users)} {audience}…")
text = self.BROADCAST_HEADER + body
api = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}"
photo_id = None # main bot's file_id after the first successful upload
success = failed = 0
errors = {}
async with aiohttp.ClientSession() as session:
for i, user_id in enumerate(users):
try:
if photo_bytes is None:
request = session.post(f"{api}/sendMessage", json={
"chat_id": user_id, "text": text, "parse_mode": "HTML",
"disable_web_page_preview": False})
elif photo_id:
request = session.post(f"{api}/sendPhoto", json={
"chat_id": user_id, "photo": photo_id, "caption": text, "parse_mode": "HTML"})
else:
form = aiohttp.FormData()
form.add_field("chat_id", str(user_id))
form.add_field("caption", text)
form.add_field("parse_mode", "HTML")
form.add_field("photo", photo_bytes, filename="broadcast.jpg", content_type="image/jpeg")
request = session.post(f"{api}/sendPhoto", data=form)
async with request as response:
answer = await response.json(content_type=None)
if answer.get("ok"):
success += 1
if photo_bytes is not None and photo_id is None:
photo_id = answer["result"]["photo"][-1]["file_id"]
else:
failed += 1
reason = answer.get("description", f"HTTP {response.status}")
errors[reason] = errors.get(reason, 0) + 1
logger.warning(f"{log_name}: failed to send to user {user_id}: {reason}")
retry_after = (answer.get("parameters") or {}).get("retry_after")
if retry_after:
await asyncio.sleep(retry_after)
except Exception as e:
failed += 1
errors[type(e).__name__] = errors.get(type(e).__name__, 0) + 1
logger.error(f"{log_name}: error sending to user {user_id}: {e!r}")
# ~20 messages/s, under Telegram's ~30/s broadcast limit
if i < len(users) - 1:
await asyncio.sleep(0.05)
if (i + 1) % 100 == 0:
try:
await status_msg.edit_text(f"📤 Отправка ({kind}): {i + 1} из {len(users)}…")
except Exception:
pass
error_lines = "".join(f"\n• {html.escape(reason)}: {count}" for reason, count in
sorted(errors.items(), key=lambda item: -item[1])[:5])
await status_msg.edit_text(
f"✅ <b>Рассылка завершена</b> ({kind})\n\n"
f"• Получателей: {len(users)}\n"
f"• Отправлено: {success}\n"
f"• Ошибок: {failed}" + error_lines,
parse_mode='HTML')
logger.info(f"{log_name} sent ({kind}): {success} successful, {failed} failed out of {len(users)} users")
return ConversationHandler.END
async def cancel_users0_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Cancel users0 message command"""
await update.message.reply_text("❌ Отправка сообщения отменена.")
@ -537,7 +500,7 @@ class AdminBot:
entry_points=[CommandHandler("system_mes", self.system_mes_start)],
states={
WAITING_FOR_SYSTEM_MESSAGE: [
MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_system_message)
MessageHandler((filters.TEXT | filters.PHOTO) & ~filters.COMMAND, self.handle_system_message)
],
},
fallbacks=[CommandHandler("cancel", self.cancel_system_message)]
@ -548,7 +511,7 @@ class AdminBot:
entry_points=[CommandHandler("sendusers0", self.sendusers0_start)],
states={
WAITING_FOR_USERS0_MESSAGE: [
MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_users0_message)
MessageHandler((filters.TEXT | filters.PHOTO) & ~filters.COMMAND, self.handle_users0_message)
],
},
fallbacks=[CommandHandler("cancel", self.cancel_users0_message)]

View file

@ -0,0 +1,158 @@
"""
Admin broadcasts (/system_mes, /sendusers0): text and photo-with-caption are
both sent through the main bot's Bot API; the photo is uploaded once and its
file_id reused. Telegram is replaced by a fake aiohttp session.
"""
from tests.bot import _env # noqa: F401 (environment before bot imports)
import asyncio
import os
import sqlite3
import tempfile
import unittest
from types import SimpleNamespace
from telegram.ext import ConversationHandler
import admin_bot
from database import Database
def run(coro):
return asyncio.run(coro)
class FakeResponse:
def __init__(self, answer):
self.answer = answer
self.status = 200 if answer.get('ok') else 400
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def json(self, content_type=None):
return self.answer
class FakeSession:
"""Records every Bot API call; chat 666 answers 'bot was blocked'."""
calls = []
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
def post(self, url, json=None, data=None):
method = url.rsplit('/', 1)[1]
if json is not None:
chat, payload = json['chat_id'], dict(json)
else:
fields = {f[0]['name']: f[2] for f in data._fields}
chat, payload = int(fields['chat_id']), {'upload': True, **{k: v for k, v in fields.items() if k != 'photo'}}
FakeSession.calls.append((method, chat, payload))
if chat == 666:
return FakeResponse({'ok': False, 'description': 'Forbidden: bot was blocked by the user'})
result = {'photo': [{'file_id': 'small'}, {'file_id': 'MAIN_BOT_FILE_ID'}]} if method == 'sendPhoto' else {}
return FakeResponse({'ok': True, 'result': result})
class FakeFile:
async def download_as_bytearray(self):
return bytearray(b'\xff\xd8jpeg')
class FakePhotoSize:
async def get_file(self):
return FakeFile()
class FakeStatus:
def __init__(self, outbox, text):
self.outbox, self.text = outbox, text
async def edit_text(self, text, **kwargs):
self.outbox.append(('edit', text))
class FakeAdminMessage:
def __init__(self, outbox, text=None, caption=None, photo=False):
self.outbox = outbox
self.text = text
self.text_html = text.replace('ChessPenguin', '<b>ChessPenguin</b>') if text else None
self.caption = caption
self.caption_html = caption.replace('ChessPenguin', '<b>ChessPenguin</b>') if caption else None
self.photo = [FakePhotoSize(), FakePhotoSize()] if photo else None
async def reply_text(self, text, **kwargs):
self.outbox.append(('reply', text))
return FakeStatus(self.outbox, text)
class BroadcastTests(unittest.TestCase):
def setUp(self):
FakeSession.calls = []
self._orig_session = admin_bot.aiohttp.ClientSession
self._orig_sleep = admin_bot.asyncio.sleep
admin_bot.aiohttp.ClientSession = FakeSession
async def no_sleep(_s):
return None
admin_bot.asyncio.sleep = no_sleep
path = os.path.join(tempfile.mkdtemp(prefix="lichess-broadcast-"), "bot.db")
self.bot = admin_bot.AdminBot.__new__(admin_bot.AdminBot)
self.bot.db = Database(path)
for uid in (1, 2, 666, 4):
self.bot.db.add_or_get_telegram_user(user_id=uid, username=None, first_name='x', last_name=None, language_code='ru')
with sqlite3.connect(path) as conn:
gid = conn.execute("INSERT INTO gamers (username) VALUES ('Alpha')").lastrowid
conn.execute("INSERT INTO user_gamers (user_id, gamer_id, period_minutes) VALUES (1, ?, 60)", (gid,))
self.out = []
def tearDown(self):
admin_bot.aiohttp.ClientSession = self._orig_session
admin_bot.asyncio.sleep = self._orig_sleep
def update(self, **kw):
return SimpleNamespace(message=FakeAdminMessage(self.out, **kw))
def test_photo_with_caption_goes_to_everybody_uploaded_once(self):
state = run(self.bot.handle_system_message(self.update(caption="♟ ChessPenguin — free", photo=True), None))
self.assertEqual(ConversationHandler.END, state)
self.assertEqual(['sendPhoto'] * 4, [c[0] for c in FakeSession.calls])
self.assertEqual([1, 2, 4, 666], sorted(c[1] for c in FakeSession.calls))
first, *rest = FakeSession.calls
self.assertTrue(first[2].get('upload'))
self.assertEqual("🔔 <b>System Message</b>\n\n♟ <b>ChessPenguin</b> — free", first[2]['caption'])
# uploaded once by the main bot, every later send reuses its file_id
self.assertEqual([], [c for c in rest if c[2].get('upload')])
self.assertEqual({'MAIN_BOT_FILE_ID'}, {c[2]['photo'] for c in rest})
self.assertEqual({'HTML'}, {c[2]['parse_mode'] for c in rest})
self.assertIn("фото с подписью", self.out[0][1])
final = self.out[-1][1]
self.assertIn("Отправлено: 3", final)
self.assertIn("Ошибок: 1", final)
self.assertIn("bot was blocked by the user: 1", final)
def test_text_keeps_formatting(self):
run(self.bot.handle_system_message(self.update(text="Try ChessPenguin"), None))
self.assertEqual({'sendMessage'}, {c[0] for c in FakeSession.calls})
self.assertEqual("🔔 <b>System Message</b>\n\nTry <b>ChessPenguin</b>", FakeSession.calls[0][2]['text'])
def test_users0_only_users_without_players(self):
run(self.bot.handle_users0_message(self.update(caption="ChessPenguin", photo=True), None))
self.assertEqual([2, 4, 666], sorted(c[1] for c in FakeSession.calls))
def test_too_long_caption_is_refused_and_waits(self):
state = run(self.bot.handle_system_message(self.update(caption="x" * 1020, photo=True), None))
self.assertEqual(admin_bot.WAITING_FOR_SYSTEM_MESSAGE, state)
self.assertEqual([], FakeSession.calls)
self.assertIn("1024", self.out[-1][1])
if __name__ == '__main__':
unittest.main()