-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtangelamerkel.py
executable file
·381 lines (340 loc) · 13 KB
/
tangelamerkel.py
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/python3
import time
import sys
import argparse
import json
import os
import traceback
import re
from telethon import TelegramClient
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import ChannelParticipantsSearch, Updates, UpdateShortMessage, UpdateNewMessage, InputPeerEmpty
#
# Parse command line args
#
parser = argparse.ArgumentParser(description='Helps moderating Pokémon GO Telegram groups with an iron hammer')
parser.add_argument('--force-setup', help='Force the initial setup, automatically called first time', dest='setup', action='store_true')
parser.add_argument('--only-telegram', help='Show only Telegram info (ignore Profesor Oak)', dest='onlytelegram', action='store_true')
parser.add_argument('--refresh-oak', help='Refresh Oak info for all users (Telegram info always refreshed)', dest='refreshall', action='store_true')
parser.add_argument('--group', help='Specify the group username or numeric ID', nargs=1, dest='group')
parser.add_argument('--human-output', help='Print the output with usernames when available', dest='humanoutput', action='store_true')
parser.add_argument('--limit', help='Limit run to the first N people (for large groups or testing purposes)', nargs=1, dest='limit')
args = parser.parse_args()
#
# Setup configuration and data directory
#
datapath = os.path.expanduser("~") + "/.local/share/tangelamerkel"
os.path.isdir(datapath) or os.mkdir(datapath)
#
# Load persistent data
#
cached_users = {}
try:
with open(datapath + '/users.json') as f:
cached_users = json.load(f)
except FileNotFoundError:
pass
configuration = {}
try:
with open(datapath + '/config.json') as f:
configuration = json.load(f)
except FileNotFoundError:
args.setup=True
#
# What group?
#
if args.group == None:
group = input('Enter the group username or numeric ID: ')
args.group = [group]
print("[TIP!] Next time, you can invoke «%s --group %s» directly." % (sys.argv[0],group))
print(" See «%s --help» for more options." % (sys.argv[0]))
#
# Initial setup
#
if args.setup == True:
print("Go to https://my.telegram.org/ and create an app. Then input the required fields.")
configuration['api_id'] = input('API ID: ').strip()
configuration['api_hash'] = input('API Hash: ').strip()
configuration['phone'] = input('Phone (+34600000000): ').strip()
with open(datapath + '/config.json', 'w') as f:
json.dump(configuration, f)
#
# Method to get the responses from Profesor Oak
#
askingOakUserId = None
lastOakQuestion = None
def receiveUpdate(update):
global askingOakUserId
global users
global cached_users
if askingOakUserId == None:
return
try:
if isinstance(update,UpdateShortMessage) and update.user_id == 201760961:
# Short message
go_on = True
response = update.message
elif isinstance(update,UpdateNewMessage) and update.message.from_id == 201760961:
# New message
go_on = True
response = update.message.message
elif isinstance(update,Updates):
# Set of messages
go_on = False
for u in update.updates:
if hasattr(u,"message") and u.message.from_id == 201760961 and \
not hasattr(u.message.to_id,"channel_id"):
go_on = True
response = u.message.message
break
else:
go_on = False
if go_on == True:
# Parse Professor Oak output
if response.find(u"✅") >- 1:
cached_users[askingOakUserId]["registered"] = "True"
cached_users[askingOakUserId]["validated"] = "True"
elif response.find(u"⚠️") >- 1:
cached_users[askingOakUserId]["registered"] = "True"
cached_users[askingOakUserId]["validated"] = "False"
else:
cached_users[askingOakUserId]["registered"] = "False"
cached_users[askingOakUserId]["validated"] = "False"
if response.find(u"Amarillo") >- 1:
cached_users[askingOakUserId]["team"] = "instinct"
elif response.find(u"Rojo") >- 1:
cached_users[askingOakUserId]["team"] = "valor"
elif response.find(u"Azul") >- 1:
cached_users[askingOakUserId]["team"] = "mystic"
m = re.match("^([a-zA-Z0-9]+),.*$", response)
if m != None and m.lastindex == 1:
cached_users[askingOakUserId]["pokemon_username"] = m.group(1)
# Add user info to global users dict
users[askingOakUserId] = cached_users[askingOakUserId]
askingOakUserId = None
# Save cache on disk
with open(datapath + '/users.json', 'w') as f:
json.dump(cached_users, f)
except Exception as e:
print("\n\nUnhandled exception: %s" % e)
print(update)
print("\n")
#
# Connect to Telegram
#
client = TelegramClient('session_name', configuration['api_id'], configuration['api_hash'], update_workers=2)
if client.connect() != True:
print("Can't connect to Telegram. Maybe you abused API limit retries? Also check your connection!")
exit(1)
client.add_update_handler(receiveUpdate)
#
# Ensure you're authorized
#
if not client.is_user_authorized():
client.send_code_request(configuration['phone'])
client.sign_in(configuration['phone'], input('Authorization required. Check Telegram and enter the code: '))
#
# Search chat
#
chats = []
chosen_chat = None
result = client(GetDialogsRequest(
offset_date=None,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=30
))
chats.extend(result.chats)
if len(result.chats)>0:
for chat in result.chats:
try:
if chat.username.lower() == args.group[0].lower():
chosen_chat = chat
break
except AttributeError:
pass
if str(chat.id) == str(args.group[0]) or \
"100"+str(chat.id) == str(args.group[0]) or \
"-100"+str(chat.id) == str(args.group[0]):
chosen_chat = chat
break
else:
print("Unable to find specified chat!")
exit(1)
else:
print("Unable to get chat list!")
exit(1)
#
# Search participants in group
#
users = {}
offset = 0
count = 0
while True:
r = client(GetParticipantsRequest(channel=chosen_chat,filter=ChannelParticipantsSearch(""),offset=offset,limit=50,hash=0))
for user in r.users:
# Output user basic info while processing
sys.stdout.write("%s - %s %s " % (user.id,user.first_name or "",user.last_name or ""))
if user.username != None:
sys.stdout.write("(@%s)" % user.username)
sys.stdout.flush()
newuser = {}
# Always update username, first name and last name
if user.username != None:
newuser["username"] = user.username
if user.first_name != None:
newuser["first_name"] = user.first_name
if user.first_name != None:
newuser["last_name"] = user.last_name
# Search in cache. Use cached version if already registered and validated
# and no special "refresh all" mode is used
if args.refreshall == False and \
str(user.id) in cached_users.keys() and \
"registered" in cached_users[str(user.id)].keys() and \
"pokemon_username" in cached_users[str(user.id)].keys() and \
cached_users[str(user.id)]["registered"] == "True" and \
cached_users[str(user.id)]["validated"] == "True":
# Cached! Update cache username, first name and last name
cached_users[str(user.id)]["username"] = user.username
cached_users[str(user.id)]["first_name"] = user.first_name
cached_users[str(user.id)]["last_name"] = user.last_name
sys.stdout.write(" (Cached!)\n")
sys.stdout.flush()
# Add user info to global users dict
users[str(user.id)] = cached_users[str(user.id)]
# Update cache on disk
with open(datapath + '/users.json', 'w') as f:
json.dump(cached_users, f)
else:
# Add new user to cached users but don't write to disk now
newuser = {}
newuser["username"] = user.username
newuser["first_name"] = user.first_name
newuser["last_name"] = user.last_name
cached_users[str(user.id)] = newuser
if args.onlytelegram == False:
# Ask Profesor Oak for relevant data
sys.stdout.write(" (Asking Profesor Oak...")
sys.stdout.flush()
# Limit Oak questions to one every 15 seconds
while lastOakQuestion != None and time.time() - lastOakQuestion < 20:
sys.stdout.write(".")
sys.stdout.flush()
time.sleep(1)
# Ok, we can continue now. Ask Oak!
askingOakUserId = str(user.id)
client.send_message('profesoroak_bot', 'Quién es %s' % user.id)
lastOakQuestion = time.time()
sys.stdout.write(")\n")
sys.stdout.flush()
else:
sys.stdout.write(" (Ignoring Profesor Oak)\n")
sys.stdout.flush()
# Add user info to global users dict
users[str(user.id)] = newuser
# Update cache on disk
with open(datapath + '/users.json', 'w') as f:
json.dump(cached_users, f)
count = count + 1
if args.limit != None and int(args.limit[0]) <= count:
break
if (args.limit != None and int(args.limit[0]) <= count) or len(r.users) < 50:
break
else:
offset = offset + 50
#
# Waiting for Profesor Oak
#
sys.stdout.write("Finishing...")
sys.stdout.flush()
while lastOakQuestion != None and time.time() - lastOakQuestion < 15:
sys.stdout.write(".")
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\n")
sys.stdout.flush()
#
# Print information
#
def humanprint(u):
sys.stdout.write(" %s - %s %s %s %s\n" % \
(u, \
users[u]["first_name"] if "first_name" in users[u].keys() and users[u]["first_name"] != None else '', \
users[u]["last_name"] if "last_name" in users[u].keys() and users[u]["last_name"] != None else '', \
"@" + users[u]["username"] if "username" in users[u].keys() and users[u]["username"] != None else '', \
users[u]["pokemon_username"] if "pokemon_username" in users[u].keys() and users[u]["pokemon_username"] != None else '', \
))
sys.stdout.write("\n")
sys.stdout.flush()
print("Users without username:")
for u in users:
if "username" not in users[u].keys() or users[u]["username"] == None:
if args.humanoutput == True:
humanprint(u)
else:
sys.stdout.write("%s " % u)
sys.stdout.write("\n")
sys.stdout.flush()
if args.onlytelegram == True:
# The rest of the output is Oak info
exit(0)
print("Unregistered users:")
for u in users:
if "registered" not in users[u].keys() or users[u]["registered"] == "False":
if args.humanoutput == True:
humanprint(u)
else:
sys.stdout.write("%s " % u)
sys.stdout.write("\n")
sys.stdout.flush()
print("Unvalidated users:")
for u in users:
if users[u]["registered"] == "True" and \
("validated" not in users[u].keys() or users[u]["validated"] == "False"):
if args.humanoutput == True:
humanprint(u)
else:
sys.stdout.write("%s " % u)
sys.stdout.write("\n")
sys.stdout.flush()
print("Validated users:")
for u in users:
if users[u]["registered"] == "True" and users[u]["validated"] == "True":
if args.humanoutput == True:
humanprint(u)
else:
sys.stdout.write("%s " % u)
sys.stdout.write("\n")
sys.stdout.flush()
print("Users from team Mystic:")
for u in users:
if users[u]["registered"] == "True" and "team" in users[u].keys() and \
users[u]["team"] == "mystic":
if args.humanoutput == True:
humanprint(u)
else:
sys.stdout.write("%s " % u)
sys.stdout.write("\n")
sys.stdout.flush()
print("Users from team Valor:")
for u in users:
if users[u]["registered"] == "True" and "team" in users[u].keys() and \
users[u]["team"] == "valor":
if args.humanoutput == True:
humanprint(u)
else:
sys.stdout.write("%s " % u)
sys.stdout.write("\n")
sys.stdout.flush()
print("Users from team Instinct:")
for u in users:
if users[u]["registered"] == "True" and "team" in users[u].keys() and \
users[u]["team"] == "instinct":
if args.humanoutput == True:
humanprint(u)
else:
sys.stdout.write("%s " % u)
sys.stdout.write("\n")
sys.stdout.flush()