Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fortunto2/36ba823eb16b501a401b2b09ec759e88 to your computer and use it in GitHub Desktop.
Save fortunto2/36ba823eb16b501a401b2b09ec759e88 to your computer and use it in GitHub Desktop.
Telegram Digets
from telethon import TelegramClient
from telethon.tl.functions.messages import GetHistoryRequest
from datetime import datetime, timedelta, timezone
import asyncio
# Replace with your own API_ID and API_HASH
API_ID = '****'
API_HASH = '****'
CHANNEL_USERNAME = '****' # Example: '@channel_name'
# Define the time interval (e.g., one week ago from today)
end_date = datetime.now(timezone.utc)
start_date = end_date - timedelta(days=7)
async def get_popular_posts():
async with TelegramClient('session_name', API_ID, API_HASH) as client:
# Retrieve messages from the specified channel
offset_id = 0
limit = 100 # Adjust based on the number of posts in a week
all_messages = []
while True:
history = await client(GetHistoryRequest(
peer=CHANNEL_USERNAME,
offset_id=offset_id,
offset_date=None,
add_offset=0,
limit=limit,
max_id=0,
min_id=0,
hash=0
))
messages = history.messages
if not messages:
break
# Filter messages within the time interval
for message in messages:
if message.date >= start_date and message.date <= end_date:
all_messages.append(message)
offset_id = messages[-1].id
# Sort messages by view count (descending)
popular_posts = sorted(all_messages, key=lambda x: x.forwards or 0, reverse=True)
# Print top posts with their view counts
print("Most popular posts from the past week:")
for post in popular_posts[:5]: # Adjust the number of posts to display
print(f"Date: {post.date}, Forwards: {post.forwards}, Message: {post.message}")
# Run the async function
asyncio.run(get_popular_posts())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment