43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
import logging
|
|
|
|
from telethon import TelegramClient
|
|
from telethon.tl.functions.channels import GetFullChannelRequest
|
|
|
|
from bot.models import ChannelMessage
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
async def fetch_channel_messages(
|
|
client: TelegramClient,
|
|
channel: str,
|
|
limit: int | None = None,
|
|
) -> tuple[list[ChannelMessage], dict]:
|
|
"""Fetch messages and basic stats from a public channel."""
|
|
entity = await client.get_entity(channel)
|
|
full = await client(GetFullChannelRequest(entity))
|
|
|
|
stats = {
|
|
"title": entity.title,
|
|
"username": getattr(entity, "username", None),
|
|
"subscribers": full.full_chat.participants_count,
|
|
}
|
|
|
|
messages: list[ChannelMessage] = []
|
|
async for msg in client.iter_messages(entity, limit=limit):
|
|
if not msg.text:
|
|
continue
|
|
messages.append(
|
|
ChannelMessage(
|
|
id=msg.id,
|
|
date=msg.date,
|
|
text=msg.text,
|
|
views=msg.views,
|
|
forwards=msg.forwards,
|
|
replies=msg.replies.replies if msg.replies else None,
|
|
)
|
|
)
|
|
|
|
messages.reverse()
|
|
log.info("Fetched %d text messages from %s", len(messages), channel)
|
|
return messages, stats
|