Created
November 8, 2024 13:47
-
-
Save maxistar/d43658ef8d28af626774a8a46c041b63 to your computer and use it in GitHub Desktop.
Telegram Digets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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