├── .gitignore ├── ChannelMessages.py ├── ChannelUsers.py ├── README.md ├── config-sample.ini └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # IDE Files 4 | #------------------------- 5 | /nbproject/ 6 | .idea/* 7 | 8 | venv 9 | .ipynb_checkpoints 10 | .projectignore 11 | *.session 12 | anaconda-project.yml 13 | *.json 14 | *.ipynb 15 | config.ini -------------------------------------------------------------------------------- /ChannelMessages.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | import json 3 | import asyncio 4 | from datetime import date, datetime 5 | 6 | from telethon import TelegramClient 7 | from telethon.errors import SessionPasswordNeededError 8 | from telethon.tl.functions.messages import (GetHistoryRequest) 9 | from telethon.tl.types import ( 10 | PeerChannel 11 | ) 12 | 13 | 14 | # some functions to parse json date 15 | class DateTimeEncoder(json.JSONEncoder): 16 | def default(self, o): 17 | if isinstance(o, datetime): 18 | return o.isoformat() 19 | 20 | if isinstance(o, bytes): 21 | return list(o) 22 | 23 | return json.JSONEncoder.default(self, o) 24 | 25 | 26 | # Reading Configs 27 | config = configparser.ConfigParser() 28 | config.read("config.ini") 29 | 30 | # Setting configuration values 31 | api_id = config['Telegram']['api_id'] 32 | api_hash = config['Telegram']['api_hash'] 33 | 34 | api_hash = str(api_hash) 35 | 36 | phone = config['Telegram']['phone'] 37 | username = config['Telegram']['username'] 38 | 39 | # Create the client and connect 40 | client = TelegramClient(username, api_id, api_hash) 41 | 42 | async def main(phone): 43 | await client.start() 44 | print("Client Created") 45 | # Ensure you're authorized 46 | if await client.is_user_authorized() == False: 47 | await client.send_code_request(phone) 48 | try: 49 | await client.sign_in(phone, input('Enter the code: ')) 50 | except SessionPasswordNeededError: 51 | await client.sign_in(password=input('Password: ')) 52 | 53 | me = await client.get_me() 54 | 55 | user_input_channel = input('enter entity(telegram URL or entity id):') 56 | 57 | if user_input_channel.isdigit(): 58 | entity = PeerChannel(int(user_input_channel)) 59 | else: 60 | entity = user_input_channel 61 | 62 | my_channel = await client.get_entity(entity) 63 | 64 | offset_id = 0 65 | limit = 100 66 | all_messages = [] 67 | total_messages = 0 68 | total_count_limit = 0 69 | 70 | while True: 71 | print("Current Offset ID is:", offset_id, "; Total Messages:", total_messages) 72 | history = await client(GetHistoryRequest( 73 | peer=my_channel, 74 | offset_id=offset_id, 75 | offset_date=None, 76 | add_offset=0, 77 | limit=limit, 78 | max_id=0, 79 | min_id=0, 80 | hash=0 81 | )) 82 | if not history.messages: 83 | break 84 | messages = history.messages 85 | for message in messages: 86 | all_messages.append(message.to_dict()) 87 | offset_id = messages[len(messages) - 1].id 88 | total_messages = len(all_messages) 89 | if total_count_limit != 0 and total_messages >= total_count_limit: 90 | break 91 | 92 | with open('channel_messages.json', 'w') as outfile: 93 | json.dump(all_messages, outfile, cls=DateTimeEncoder) 94 | 95 | with client: 96 | client.loop.run_until_complete(main(phone)) 97 | -------------------------------------------------------------------------------- /ChannelUsers.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | import json 3 | import asyncio 4 | 5 | from telethon import TelegramClient 6 | from telethon.errors import SessionPasswordNeededError 7 | from telethon.tl.functions.channels import GetParticipantsRequest 8 | from telethon.tl.types import ChannelParticipantsSearch 9 | from telethon.tl.types import ( 10 | PeerChannel 11 | ) 12 | 13 | # Reading Configs 14 | config = configparser.ConfigParser() 15 | config.read("config.ini") 16 | 17 | # Setting configuration values 18 | api_id = config['Telegram']['api_id'] 19 | api_hash = config['Telegram']['api_hash'] 20 | 21 | api_hash = str(api_hash) 22 | 23 | phone = config['Telegram']['phone'] 24 | username = config['Telegram']['username'] 25 | 26 | # Create the client and connect 27 | client = TelegramClient(username, api_id, api_hash) 28 | 29 | async def main(phone): 30 | await client.start() 31 | print("Client Created") 32 | # Ensure you're authorized 33 | if await client.is_user_authorized() == False: 34 | await client.send_code_request(phone) 35 | try: 36 | await client.sign_in(phone, input('Enter the code: ')) 37 | except SessionPasswordNeededError: 38 | await client.sign_in(password=input('Password: ')) 39 | 40 | me = await client.get_me() 41 | 42 | user_input_channel = input("enter entity(telegram URL or entity id):") 43 | 44 | if user_input_channel.isdigit(): 45 | entity = PeerChannel(int(user_input_channel)) 46 | else: 47 | entity = user_input_channel 48 | 49 | my_channel = await client.get_entity(entity) 50 | 51 | offset = 0 52 | limit = 100 53 | all_participants = [] 54 | 55 | while True: 56 | participants = await client(GetParticipantsRequest( 57 | my_channel, ChannelParticipantsSearch(''), offset, limit, 58 | hash=0 59 | )) 60 | if not participants.users: 61 | break 62 | all_participants.extend(participants.users) 63 | offset += len(participants.users) 64 | 65 | all_user_details = [] 66 | for participant in all_participants: 67 | all_user_details.append( 68 | {"id": participant.id, "first_name": participant.first_name, "last_name": participant.last_name, 69 | "user": participant.username, "phone": participant.phone, "is_bot": participant.bot}) 70 | 71 | with open('user_data.json', 'w') as outfile: 72 | json.dump(all_user_details, outfile) 73 | 74 | with client: 75 | client.loop.run_until_complete(main(phone)) 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # telegram-analysis 2 | Tools to analyze Telegram groups and channels 3 | 4 | Please note that groups are as same as channels in Telegram. so you can use this code to get users and messages from any public group or channel. Also if you are a member of a private group or channel you can still get users list and messages from that group. 5 | 6 | A short video tutorial on how to use this script: 7 | https://www.youtube.com/watch?v=aU1p-F7gDo4&ab_channel=AmirYousefi 8 | 9 | A complete tutorial about using this script is available on Medium 10 | 11 | https://medium.com/@AmirYousefi/how-to-get-data-from-telegram-82af55268a4b 12 | -------------------------------------------------------------------------------- /config-sample.ini: -------------------------------------------------------------------------------- 1 | [Telegram] 2 | # no need for quotes 3 | 4 | # you can get telegram development credentials in telegram API Development Tools 5 | api_id = Telegram-API-ID 6 | api_hash = Telegram-API-Hash 7 | 8 | # use full phone number including + and country code 9 | phone = Your-Telegram-Phone-Number 10 | username = Your-Telegram-Username -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Telethon==1.23.0 2 | --------------------------------------------------------------------------------