-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcrawler.py
More file actions
178 lines (127 loc) · 6.31 KB
/
crawler.py
File metadata and controls
178 lines (127 loc) · 6.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.sync import TelegramClient
from telethon import functions, types
import telethon.utils as tel_utils
from telethon.errors import FloodWaitError, ChannelPrivateError, rpcerrorlist
from telethon.tl import types
import time
import datetime
import logging
import pickle
from progress.bar import ChargingBar
import configparser
import db_utilities
DB_NAME = 'Telegram'
######################################################
# Utilities
######################################################
# Get the client from config file
def get_client(config_file="config.ini"):
# Reading Configs
config = configparser.ConfigParser()
config.read(config_file)
api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']
phone = config['Telegram']['phone']
username = config['Telegram']['username']
client = TelegramClient(username, api_id, api_hash)
return client, phone
# return the ID type of a peer object
def get_peer_id(peer):
if type(peer) is types.PeerChannel:
return peer.channel_id, 'channel'
if type(peer) is types.PeerUser:
return peer.user_id, 'user'
if type(peer) is types.PeerChat:
return peer.chat_id, 'chat'
return [None, None]
# save preprocess docs in pickle
def save_as_pickle(text_list, outfile_name):
with open(outfile_name, 'wb') as fp:
pickle.dump(text_list, fp)
######################################################
# get client
client, phone = get_client()
# Download the messages of a channel by username
async def download_content_by_name(channels, limit):
# Start from the last checkpoint
print('Number of channels to search: ', len(channels))
with ChargingBar('Downloading content', max=len(channels)) as bar:
for channel in channels:
try:
channel_peer = await client.get_input_entity(channel)
channel = channel_peer.channel_id
channel_connect = await client.get_entity(channel)
title = channel_connect.title
n_subscribers = channel_connect.participants_count
creation_date = datetime.datetime.timestamp(channel_connect.date)
description = ''
username = ''
is_scam = False
verified = False
if type(channel_connect) is types.Channel:
channel_full_info = None
try:
channel_full_info = await client(GetFullChannelRequest(channel=channel_connect))
except FloodWaitError as e:
print('Flood waited for', e.seconds)
description = channel_full_info.full_chat.about
username = channel_full_info.chats[0].username
is_scam = channel_full_info.chats[0].scam
n_subscribers = channel_full_info.full_chat.participants_count
verified = channel_connect.verified
media = {}
messages = {}
async for message in client.iter_messages(channel, limit = limit):
message_date = datetime.datetime.timestamp(message.date)
message_author = get_peer_id(message.from_id)[0]
is_forwarded = False
forwarded_from_id = None
forwarded_message_date = None
if message.forward:
is_forwarded = True
forwarded_from_id = get_peer_id(message.forward.from_id)[0]
forwarded_message_date = datetime.datetime.timestamp(message.forward.date)
if message.text:
messages[message.id] = {'message':message.text, 'date': message_date, 'author': message_author,
'is_forwarded':is_forwarded, 'forwarded_from_id':forwarded_from_id,
'forwarded_message_date':forwarded_message_date}
time.sleep(0.00001)
if message.media and message.file:
if not (message.gif or message.sticker):
title = message.file.name
file_id = message.file.id
file_ext = message.file.ext
media[message.id] = {'title': title, 'date': message_date, 'author': message_author, 'extension': file_ext,
'is_forwarded':is_forwarded, 'forwarded_from_id':forwarded_from_id, 'media_id':file_id,
'forwarded_message_date':forwarded_message_date}
time.sleep(0.00001)
# insert all to the end
new_ch = { '_id':channel, 'creation_date': creation_date, 'username': username, 'title': title, 'description': description, 'scam': is_scam,
'text_messages': messages, 'generic_media': media, 'n_subscribers': n_subscribers, 'verified': verified}
db_utilities.insert_channel(new_ch, DB_NAME)
time.sleep(1)
except FloodWaitError as e:
print('Flood waited for', e.seconds)
except ChannelPrivateError:
print("Private channel")
logging.warning('error with this channel ' + str(channel))
bar.next()
async def main():
await client.start()
# Ensure you're authorized
if not await client.is_user_authorized():
await client.send_code_request(phone)
try:
await client.sign_in(phone, input('Enter the code: '))
except SessionPasswordNeededError:
await client.sign_in(password=input('Password: '))
#client.flood_sleep_threshold = 0 # Don't auto-sleep
channels_to_find = db_utilities.get_other_channels_references(DB_NAME)
while channels_to_find.__len__() > 0:
save_as_pickle(channels_to_find, 'channels_to_find')
await download_content_by_name(channels_to_find, 10000)
with client:
client.loop.run_until_complete(main())