-
Notifications
You must be signed in to change notification settings - Fork 0
/
Task.py
355 lines (300 loc) · 16.1 KB
/
Task.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
from datetime import datetime, time
import requests
import os
from dotenv import load_dotenv
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
load_dotenv()
BOT_TOKEN=bot_token = os.getenv("BOT_TOKEN")
# 21310000 isf 11320000 teh
class Task:
def __init__(self, creator, receivers, how_often,orgin_city,destination_city,date,start_time,end_time,username=None,password=None,firstName=None,lastName=None,title='MR',nationalCode=None,notificationCellphoneNumber=None,alibabaToken=None,Task_id=None,mute=True,active=True):
self.active = active
self.creator = creator
self.receivers = receivers
self.how_often = how_often
self.date = date
self.start_time = start_time
self.end_time = end_time
self.orgin_city=orgin_city
self.destination_city=destination_city
# -------------------
self.mute=mute
# -------------------
self.username=username
self.password=password
self.firstName=firstName
self.lastName=lastName
self.title=title
self.nationalCode=nationalCode
self.notificationCellphoneNumber=notificationCellphoneNumber
self.alibabaToken=alibabaToken
self.Task_id=Task_id
@staticmethod
def get_task_fields():
# This method returns a list of field names expected for a task.
#
# creator, receivers, how_often, orgin_city, destination_city, date, start_time, end_time, username = None, password = None, firstName = None, lastName = None, title = 'MR', nationalCode = None, notificationCellphoneNumber = None, alibabaToken = None, Task_id = None, mute = True, active = True):
return [
{"field_name": "creator", "message": "creator id", "required": True},
{"field_name": "receivers", "message": "receivers id in array", "required": True},
{"field_name": "how_often", "message": "how_often", "required": True},
{"field_name": "orgin_city", "message": "origin city name that you want to start your trip from in persian", "required": True},
{"field_name": "destination_city", "message": "destination city name that you want to go in persian", "required": True},
{"field_name": "date", "message": "date that you want to go and it must be in this format: 2023-10-07 in gregorian calendar", "required": True},
{"field_name": "start_time", "message": "start time of that date that you want me search for you and it must be in this format: 00:00:00", "required": True},
{"field_name": "end_time", "message": "end time of that date that you want me search for you and it must be in this format: 23:59:59", "required": True},
{"field_name": "username", "message": "username of your alibaba account", "required": False},
{"field_name": "password", "message": "password of your alibaba account", "required": False},
{"field_name": "firstName", "message": "your firstName that you want booked under that name in your alibaba account", "required": False},
{"field_name": "lastName", "message": "your lastName that you want booked under that name in your alibaba account", "required": False},
{"field_name": "title", "message": "your gender that you want booked under that name in your alibaba account for men is 'MR'", "required": False},
{"field_name": "nationalCode", "message": "your nationalCode that you want booked under that name in your alibaba account", "required": False},
{"field_name": "notificationCellphoneNumber", "message": "your phonenumber that you want booked under that name in your alibaba account", "required": False},
{"field_name": "alibabaToken", "message": "it is local", "required": False},
{"field_name": "Task_id", "message": "it is local", "required": False},
{"field_name": "mute", "required": False},
{"field_name": "active", "required": False}
]
def get_CityCode_ali_baba(self,city):
url = "https://ws.alibaba.ir/api/v1/bus/stations"
querystring = {"filter":"containsall={ct:"+f"'{city}'"+"}"}
response = requests.request("GET", url ,params=querystring)
print(response.json())
result=response.json()['result']['items']
if len(result)>0:
return result[0]['domainCode']
def get_CityName_ali_baba(self,city):
url = "https://ws.alibaba.ir/api/v1/bus/stations"
querystring = {"filter":"containsall={ct:"+f"'{city}'"+"}"}
response = requests.request("GET", url ,params=querystring)
result=response.json()['result']['items']
if len(result)>0:
return result[0]['displayNames'][1]['value']
def get_CityCode_snapp(self,city):
url = "https://www.snapptrip.com/bus/api/listing/v1/cities"
querystring = {"query":city}
response = requests.request("GET", url, params=querystring)
result=response.json()
if len(result)>0:
return (result[0]['id'])
def get_url_ali_baba(self):
return f'https://ws.alibaba.ir/api/v2/bus/available?orginCityCode={self.get_CityCode_ali_baba(self.orgin_city)}&destinationCityCode={self.get_CityCode_ali_baba(self.destination_city)}&requestDate={self.date}&passengerCount=1'
def get_url_snapp(self):
return f'https://www.snapptrip.com/bus/api/listing/v1/availability/{self.get_CityCode_snapp(self.orgin_city)}/to/{self.get_CityCode_snapp(self.destination_city)}/on/{self.date}'
def send_message(self,available,company):
if available:
for CHAT_ID in self.receivers:
# API endpoint
api_url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
deleted_value = {key: value for key, value in available.items() if key != 'proposalId'}
message = f"I found ticket for you in {company}\ncurrent time is "+str(datetime.now().time())+'\n'+str(deleted_value)
message += '\n'+self.__str__()
if company=='alibaba':
try:
if self.username and self.password and self.firstName and self.lastName and self.title and self.nationalCode and self.notificationCellphoneNumber:
message += '\nit is url that I booked for you just pay it :'+self.book_ticket_alibaba(providerItemIds=available['proposalId'],username=self.username,password=self.password,firstName=self.firstName,lastName=self.lastName,title=self.title,nationalCode=self.nationalCode,notificationCellphoneNumber=self.notificationCellphoneNumber)
except Exception as e:
message += '\nthere is a problem in booking ticket for you'+str(e)
params = {
'chat_id': CHAT_ID,
'text': message
}
response = requests.post(api_url, json=params)
if response.status_code == 200:
print("Message sent successfully!")
else:
print("Failed to send message. Status code:", response.status_code)
print("Response:", response.text)
else:
for CHAT_ID in self.receivers:
api_url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
message = f"there is not any ticket available in {company}"
message += '\n'+self.__str__()
params = {
'chat_id': CHAT_ID,
'text': message,
'disable_notification': True
}
response = requests.post(api_url, json=params)
if response.status_code == 200:
print("Message sent successfully!")
else:
print("Failed to send message. Status code:", response.status_code)
print("Response:", response.text)
def get_data_ali_baba(self):
if not self.active:
return
# print(self.get_url_ali_baba())
request = requests.get(self.get_url_ali_baba())
print(self.get_url_ali_baba())
data=request.json()['result']
print(data)
availableList=data['availableList']
from_time_str = self.start_time
from_time_obj = datetime.strptime(from_time_str, '%H:%M:%S').time()
to_time_str = self.end_time
to_time_obj = datetime.strptime(to_time_str, '%H:%M:%S').time()
is_any=False
for available in availableList:
time_str=available['departureDateTime'].split('T')[1]
time_obj = datetime.strptime(time_str, '%H:%M:%S').time()
if time_obj>=from_time_obj and time_obj<=to_time_obj:
if available['availableSeats']>0:
is_any=True
self.send_message(available,'alibaba')
if not is_any and not self.mute:
self.send_message(None,'alibaba')
def get_data_snapp(self):
if not self.active:
return
request = requests.get(self.get_url_snapp())
data=request.json()
availableList=data['solutions']
from_time_str = self.start_time
from_time_obj = datetime.strptime(from_time_str, '%H:%M:%S').time()
to_time_str = self.end_time
to_time_obj = datetime.strptime(to_time_str, '%H:%M:%S').time()
is_any=False
for available in availableList:
time_str=available['departureTime']
time_obj = datetime.strptime(time_str, '%H:%M').time()
if time_obj>=from_time_obj and time_obj<=to_time_obj:
if available['capacity']>0:
is_any=True
self.send_message(available,'snapp')
if not is_any and not self.mute:
self.send_message(None,'snapp')
def login_alibaba(self,username,password):
# print('login_alibaba')
url = "https://ws.alibaba.ir/api/v3/account/token"
payload = {
"emailOrPhone": f"{username}",
"password": f"{password}"
}
headers = {
"Content-Type": "application/json"
}
response = requests.request("POST", url, json=payload, headers=headers)
token = response.json()['result']['access_token']
return token
def get_last_ticket_alibaba(self,providerItemIds):
# print('get_last_ticket_alibaba')
url = f'https://ws.alibaba.ir/api/v1/bus/available/{providerItemIds}/seats'
response = requests.request("GET", url)
for item in response.json()['result']:
if item['status'] == 'Available':
# print(item['index'], item['status'])
break
return item['number']
def poass_passenger_ddetail_alibaba(self,providerItemIds,token,firstName,lastName,title,seat,nationalCode):
# print('poass_passenger_ddetail_alibaba')
url = "https://ws.alibaba.ir/api/v1/coordinator/basket/items/bus"
payload = {"providerItemIds": [f"{providerItemIds}"],
"firstName": firstName,
"lastName": lastName,
"firstNameEnglish": None,
"lastNameEnglish": None,
"title": title,
"seats": [seat],
"nationalCodes": [nationalCode]
}
headers = {
"Authorization": f"Bearer {token}"
}
response = requests.request("PUT", url, json=payload, headers=headers)
basketId = response.json()['result']['basketId']
return basketId
def checkout_alibaba(self,token,basketId,notificationCellphoneNumber):
# print('checkout_alibaba')
url = f"https://ws.alibaba.ir/api/v2/coordinator/basket/{basketId}/checkout"
headers = {
"Authorization": f"Bearer {token}"
}
payload = {"notificationEmail": "", "notificationCellphoneNumber": notificationCellphoneNumber}
response = requests.request("POST", url, json=payload, headers=headers)
orderId = response.json()['result']['orderId']
return orderId
def confirm_alibaba(self,token,orderId):
# print('confirm_alibaba')
url = f'https://ws.alibaba.ir/api/v1/coordinator/order/{orderId}/confirm'
headers = {
"Authorization": f"Bearer {token}"
}
response = requests.request("POST", url, headers=headers)
print(response.text)
return response.json()["success"]
def status_alibaba(self,token,orderId):
# print('status_alibaba')
url = f"https://ws.alibaba.ir/api/v2/coordinator/order/{orderId}/status"
headers = {
"Authorization": f"Bearer {token}"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
return response.json()["result"]['orderStatus']=="Confirmed"
def pay_alibaba(self,orderId,token):
# print('pay_alibaba')
url = f'https://ws.alibaba.ir/api/v3/coordinator/order/{orderId}/pay-request'
payload = {"redirectUrl": f"https://www.alibaba.ir/bus/{self.get_CityName_ali_baba(self.orgin_city)}-{self.get_CityName_ali_baba(self.destination_city)}/o6ti0e/{orderId}/issue",
"payRequestType": "PayByBank"}
headers = {
"Authorization": f"Bearer {token}"
}
response = requests.request("POST", url, json=payload, headers=headers)
return response.json()['result']['bankUrl']
def book_ticket_alibaba(self,providerItemIds,username,password,firstName,lastName,title,nationalCode,notificationCellphoneNumber):
if not self.alibabaToken:
token=self.login_alibaba(username,password)
print(token)
try:
mongodb_password = os.getenv("MONGODB_PASSWORD")
uri = f"mongodb+srv://khabaziana:{mongodb_password}@cluster0.l4miazp.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
#update token in mongo
db = client.Biliti
collection = db.Tasks
collection.update_one({'_id':self.Task_id},{'$set':{'alibabaToken':token}})
client.close()
except:
pass
self.token=token
else:
token=self.alibabaToken
print(token)
seat=self.get_last_ticket_alibaba(providerItemIds)
# print(seat)
basketId= self.poass_passenger_ddetail_alibaba(providerItemIds,token,firstName,lastName,title,seat,nationalCode)
# print(basketId)
orderId=self.checkout_alibaba(token,basketId,notificationCellphoneNumber)
# print(orderId)
if self.confirm_alibaba(token,orderId):
if self.status_alibaba(token,orderId):
result = self.pay_alibaba(orderId,token)
# must deactivate task
try:
mongodb_password = os.getenv("MONGODB_PASSWORD")
uri = f"mongodb+srv://khabaziana:{mongodb_password}@cluster0.l4miazp.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
#update token in mongo
db = client.Biliti
collection = db.Tasks
collection.update_one({'_id':self.Task_id},{'$set':{'active':False}})
client.close()
except:
pass
return result
def __str__(self):
return '\n'.join([
f"Task created by {self.creator}, ",
f"receivers: {', '.join(self.receivers)}, ",
f"how often: {self.how_often}, ",
f"origin city code: {self.orgin_city}, ",
f"destination city code: {self.destination_city}, ",
f"date: {self.date}, ",
f"start time: {self.start_time}, ",
f"end time: {self.end_time}"
])
if __name__ == "__main__":
task=Task(creator = '684630739',receivers = ['684630739'],how_often = 'daily',orgin_city = 'تهران',destination_city = 'اصفهان',date = '2023-10-17',start_time = '00:00:00',end_time = '23:59:59')
task.get_data_ali_baba()