Skip to content

Instantly share code, notes, and snippets.

@membrive
Last active February 6, 2022 12:48
Show Gist options
  • Save membrive/e2d23061e46a9f9c2faac1cf3a9a943d to your computer and use it in GitHub Desktop.
Save membrive/e2d23061e46a9f9c2faac1cf3a9a943d to your computer and use it in GitHub Desktop.
Creates a table with the message count and the date of the last message of each user of a Telegram group.
#!/usr/bin/env python
from telethon.sync import TelegramClient
from telethon.tl.types import PeerUser, UserStatusOffline
from prettytable import PrettyTable
# Generate API_ID, API_HASH and SHORT_NAME in https://my.telegram.org/apps
API_ID = ''
API_HASH = ''
SHORT_NAME = ''
CHAT_ID = -111111111 # your group ID (negative integer)
def get_user_messages(messages, user_id):
count = 0
last_message_date = ""
for message in messages:
if message.from_id == PeerUser(user_id):
if count == 0:
last_message_date = message.date.strftime("%d-%b-%Y (%H:%M:%S)")
count += 1
return count, last_message_date
def get_user_status(status):
if isinstance(status, UserStatusOffline):
return status.was_online.strftime("%d-%b-%Y (%H:%M:%S)")
else:
return status
def main():
t = PrettyTable([
'ID',
'Username',
'First Name',
'Last Name',
'Status',
'Msg count',
'Last msg'
])
with TelegramClient(SHORT_NAME, API_ID, API_HASH) as client:
print("Obtaining total messages. This may take a while...")
# if the number of msgs is large, set a limit or it will take long
messages = client.get_messages(CHAT_ID, limit=None)
print("Getting list of users...")
users = client.get_participants(CHAT_ID)
print("Processing data...")
for user in users:
t.add_row([
user.id,
user.username,
user.first_name,
user.last_name,
get_user_status(user.status),
get_user_messages(messages, user.id)[0],
get_user_messages(messages, user.id)[1]
])
print(t.get_string(sortby='Msg count', reversesort=True))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment