init
This commit is contained in:
commit
ec1112e162
22 changed files with 837 additions and 0 deletions
43
bot/services/fetcher.py
Normal file
43
bot/services/fetcher.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
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
|
||||
Loading…
Add table
Add a link
Reference in a new issue