/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>
158 lines
6 KiB
Python
158 lines
6 KiB
Python
"""
|
||
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()
|