- Notifications
You must be signed in to change notification settings - Fork 0
Files
/
app.py
906 lines (856 loc) · 47.9 KB
/
app.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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
from colorama import *
from datetime import datetime, timedelta
from fake_useragent import FakeUserAgent
from faker import Faker
from requests import (
JSONDecodeError,
RequestException,
Session
)
from time import sleep
from urllib.parse import parse_qs
import json
import os
import sys
import random
import re
class MatchQuest:
def __init__(self) -> None:
self.session = Session()
self.faker = Faker()
self.headers = {
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
'Cache-Control': 'no-cache',
'Host': 'tgapp-api.matchain.io',
'Origin': 'https://tgapp-api.matchain.io',
'Pragma': 'no-cache',
'Referer': 'https://tgapp-api.matchain.io/',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-site',
'User-Agent': FakeUserAgent().random
}
def clear_terminal(self):
os.system('cls' if os.name == 'nt' else 'clear')
def print_timestamp(self, message):
print(
f"{Fore.BLUE + Style.BRIGHT}[ {datetime.now().astimezone().strftime('%x %X %Z')} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{message}",
flush=True
)
def process_queries(self, lines_per_file: int):
if not os.path.exists('queries.txt'):
raise FileNotFoundError(f"File 'queries.txt' not found. Please ensure it exists.")
with open('queries.txt', 'r') as f:
queries = [line.strip() for line in f if line.strip()]
if not queries:
raise ValueError("File 'queries.txt' is empty.")
existing_queries = set()
for file in os.listdir():
if file.startswith('queries-') and file.endswith('.txt'):
with open(file, 'r') as qf:
existing_queries.update(line.strip() for line in qf if line.strip())
new_queries = [query for query in queries if query not in existing_queries]
if not new_queries:
self.print_timestamp(f"{Fore.YELLOW + Style.BRIGHT}[ No New Queries To Add ]{Style.RESET_ALL}")
return
files = [f for f in os.listdir() if f.startswith('queries-') and f.endswith('.txt')]
files.sort(key=lambda x: int(re.findall(r'\d+', x)[0]) if re.findall(r'\d+', x) else 0)
last_file_number = int(re.findall(r'\d+', files[-1])[0]) if files else 0
for i in range(0, len(new_queries), lines_per_file):
chunk = new_queries[i:i + lines_per_file]
if files and len(open(files[-1], 'r').readlines()) < lines_per_file:
with open(files[-1], 'a') as outfile:
outfile.write('\n'.join(chunk) + '\n')
self.print_timestamp(f"{Fore.GREEN + Style.BRIGHT}[ Updated '{files[-1]}' ]{Style.RESET_ALL}")
else:
last_file_number += 1
queries_file = f"queries-{last_file_number}.txt"
with open(queries_file, 'w') as outfile:
outfile.write('\n'.join(chunk) + '\n')
self.print_timestamp(f"{Fore.GREEN + Style.BRIGHT}[ Generated '{queries_file}' ]{Style.RESET_ALL}")
def load_queries(self, file_path):
with open(file_path, 'r') as file:
return [line.strip() for line in file if line.strip()]
def register_user(self, queries: str):
url = 'https://tgapp-api.matchain.io/api/tgapp/v1/user/register'
for query in queries:
try:
parsed_query = parse_qs(query)
user_data_json = parsed_query['user'][0]
user_data = json.loads(user_data_json)
uid = user_data.get('id')
first_name = user_data.get('first_name', '')
last_name = user_data.get('last_name', '')
username = user_data.get('username', '')
nickname = f"{self.faker.user_name()}{random.randint(1000, 9999)}"
data = json.dumps({'uid':int(uid),'first_name':first_name,'last_name':last_name,'username':username,'nickname':nickname,'invitor':'799088ca289a5695366dedcce0c35bf3','tg_login_params':query})
headers = {
**self.headers,
'Content-Length': str(len(data)),
'Content-Type': 'application/json'
}
response = self.session.post(url=url, headers=headers, data=data)
response.raise_for_status()
except (Exception, JSONDecodeError, RequestException) as e:
continue
def login_user(self, queries: str):
url = 'https://tgapp-api.matchain.io/api/tgapp/v1/user/login'
accounts = []
for query in queries:
try:
parsed_query = parse_qs(query)
user_data_json = parsed_query['user'][0]
user_data = json.loads(user_data_json)
uid = user_data.get('id')
first_name = user_data.get('first_name', '')
last_name = user_data.get('last_name', '')
username = user_data.get('username', '')
data = json.dumps({'uid':uid,'first_name':first_name,'last_name':last_name,'username':username,'tg_login_params':query})
headers = {
**self.headers,
'Content-Length': str(len(data)),
'Content-Type': 'application/json'
}
response = self.session.post(url=url, headers=headers, data=data)
response.raise_for_status()
login_user = response.json()
token = login_user['data']['token']
accounts.append((token, first_name, uid))
except (Exception, JSONDecodeError, RequestException) as e:
self.print_timestamp(
f"{Fore.YELLOW + Style.BRIGHT}[ Failed To Process {query} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.RED + Style.BRIGHT}[ {str(e)} ]{Style.RESET_ALL}"
)
continue
return accounts
def profile_user(self, token: str, first_name: str, uid: int):
url = 'https://tgapp-api.matchain.io/api/tgapp/v1/user/profile'
data = json.dumps({'uid':uid})
headers = {
**self.headers,
'Authorization': token,
'Content-Length': str(len(data)),
'Content-Type': 'application/json'
}
try:
response = self.session.post(url=url, headers=headers, data=data)
response.raise_for_status()
return response.json()
except RequestException as e:
self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.RED + Style.BRIGHT}[ An HTTP Error Occurred While Fetching Profile User: {str(e)} ]{Style.RESET_ALL}"
)
return None
except Exception as e:
self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.RED + Style.BRIGHT}[ An Unexpected Error Occurred While Fetching Profile User: {str(e)} ]{Style.RESET_ALL}"
)
return None
def progress_quiz_daily(self, token: str, first_name: str):
url = 'https://tgapp-api.matchain.io/api/tgapp/v1/daily/quiz/progress'
headers = {
**self.headers,
'Authorization': token,
'Content-Type': 'application/json'
}
answer_result = {'answer_result':[]}
try:
response = self.session.get(url=url, headers=headers)
response.raise_for_status()
progress_quiz_daily = response.json()
if 'msg' in progress_quiz_daily:
if progress_quiz_daily['msg'] == 'Already answered today':
self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.MAGENTA + Style.BRIGHT}[ Daily Quiz Already Answered Today ]{Style.RESET_ALL}"
)
elif 'data' in progress_quiz_daily:
for quiz in progress_quiz_daily['data']:
quiz_id = quiz['Id']
correct_answer = None
for answer in quiz['items']:
if answer['is_correct']:
correct_answer = answer['number']
break
answer_result['answer_result'].append({'quiz_id':quiz_id,'selected_item':correct_answer,'correct_item':correct_answer})
self.submit_quiz_daily(token=token, first_name=first_name, answer_result=answer_result)
except RequestException as e:
return self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.RED + Style.BRIGHT}[ An HTTP Error Occurred While Fetching Progress Quiz Daily: {str(e)} ]{Style.RESET_ALL}"
)
except Exception as e:
return self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.RED + Style.BRIGHT}[ An Unexpected Error Occurred While Fetching Progress Quiz Daily: {str(e)} ]{Style.RESET_ALL}"
)
def submit_quiz_daily(self, token: str, first_name: str, answer_result: dict):
url = 'https://tgapp-api.matchain.io/api/tgapp/v1/daily/quiz/submit'
data = json.dumps(answer_result)
headers = {
**self.headers,
'Authorization': token,
'Content-Length': str(len(data)),
'Content-Type': 'application/json'
}
try:
response = self.session.post(url=url, headers=headers, data=data)
response.raise_for_status()
submit_quiz_daily = response.json()
if 'msg' in submit_quiz_daily:
if submit_quiz_daily['msg'] == 'OK':
return self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.GREEN + Style.BRIGHT}[ Submitted Quiz Daily ]{Style.RESET_ALL}"
)
elif 'err' in submit_quiz_daily:
if submit_quiz_daily['err'] == 'Already answered today':
return self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.MAGENTA + Style.BRIGHT}[ Daily Quiz Already Answered Today ]{Style.RESET_ALL}"
)
except RequestException as e:
return self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.RED + Style.BRIGHT}[ An HTTP Error Occurred While Submit Quiz Daily: {str(e)} ]{Style.RESET_ALL}"
)
except Exception as e:
return self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.RED + Style.BRIGHT}[ An Unexpected Error Occurred While Submit Quiz Daily: {str(e)} ]{Style.RESET_ALL}"
)
def status_task_daily(self, token: str, first_name: str, uid: int):
url = 'https://tgapp-api.matchain.io/api/tgapp/v1/daily/task/status'
headers = {
**self.headers,
'Authorization': token,
'Content-Type': 'application/json'
}
try:
response = self.session.get(url=url, headers=headers)
response.raise_for_status()
status_task_daily = response.json()
if 'data' in status_task_daily:
for status in status_task_daily['data']:
self.purchase_task_daily(token=token, first_name=first_name, uid=uid, type_purchase=status['type'])
except RequestException as e:
return self.print_timestamp(
f"{Fore.CYAN + Style.BRIGHT}[ {first_name} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.RED + Style.BRIGHT}[ An HTTP Error Occurred While Fetching Status Task Daily: {str(e)} ]{Style.RESET_ALL}"
)
except Exception as e:
matchquest = MatchQuest()
queries_files = [f for f in os.listdir() if f.startswith('queries-') and f.endswith('.txt')]
queries_files.sort(key=lambda x: int(re.findall(r'\d+', x)[0]) if re.findall(r'\d+', x) else 0)
matchquest.print_timestamp(
f"{Fore.MAGENTA + Style.BRIGHT}[ 1 ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.CYAN + Style.BRIGHT}[ Split Queries ]{Style.RESET_ALL}"
)
matchquest.print_timestamp(
f"{Fore.MAGENTA + Style.BRIGHT}[ 2 ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.CYAN + Style.BRIGHT}[ Use Existing 'queries-*.txt' ]{Style.RESET_ALL}"
)
matchquest.print_timestamp(
f"{Fore.MAGENTA + Style.BRIGHT}[ 3 ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.CYAN + Style.BRIGHT}[ Use 'queries.txt' Without Splitting ]{Style.RESET_ALL}"
)
initial_choice = int(input(
f"{Fore.BLUE + Style.BRIGHT}[ {datetime.now().astimezone().strftime('%x %X %Z')} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.YELLOW + Style.BRIGHT}[ Select An Option ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
))
if initial_choice == 1:
accounts = int(input(
f"{Fore.YELLOW + Style.BRIGHT}[ How Much Account That You Want To Process Each Terminal ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
))
matchquest.print_timestamp(f"{Fore.CYAN + Style.BRIGHT}[ Processing Queries To Generate Files ]{Style.RESET_ALL}")
matchquest.process_queries(lines_per_file=accounts)
queries_files = [f for f in os.listdir() if f.startswith('queries-') and f.endswith('.txt')]
queries_files.sort(key=lambda x: int(re.findall(r'\d+', x)[0]) if re.findall(r'\d+', x) else 0)
if not queries_files:
raise FileNotFoundError("No 'queries-*.txt' Files Found")
elif initial_choice == 2:
if not queries_files:
raise FileNotFoundError("No 'queries-*.txt' Files Found")
elif initial_choice == 3:
queries = [line.strip() for line in open('queries.txt') if line.strip()]
else:
raise ValueError("Invalid Initial Choice. Please Run The Script Again And Choose A Valid Option")
if initial_choice in [1, 2]:
matchquest.print_timestamp(f"{Fore.MAGENTA + Style.BRIGHT}[ Select The Queries File To Use ]{Style.RESET_ALL}")
for i, queries_file in enumerate(queries_files, start=1):
matchquest.print_timestamp(
f"{Fore.MAGENTA + Style.BRIGHT}[ {i} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.CYAN + Style.BRIGHT}[ {queries_file} ]{Style.RESET_ALL}"
)
choice = int(input(
f"{Fore.BLUE + Style.BRIGHT}[ {datetime.now().astimezone().strftime('%x %X %Z')} ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
f"{Fore.YELLOW + Style.BRIGHT}[ Select 'queries-*.txt' File ]{Style.RESET_ALL}"
f"{Fore.WHITE + Style.BRIGHT} | {Style.RESET_ALL}"
)) - 1
if choice < 0 or choice >= len(queries_files):
raise ValueError("Invalid Choice. Please Run The Script Again And Choose A Valid Option")
selected_file = queries_files[choice]
queries = matchquest.load_queries(selected_file)
matchquest.main(queries)
except (ValueError, IndexError, FileNotFoundError) as e:
matchquest.print_timestamp(f"{Fore.RED + Style.BRIGHT}[ {str(e)} ]{Style.RESET_ALL}")
except KeyboardInterrupt:
sys.exit(0)