optimuslib 0.0.37__py3-none-any.whl → 0.0.39__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
optimuslib/optimuslib.py CHANGED
@@ -101,7 +101,7 @@ def checkOS():
101
101
  osVersion = platform.platform()
102
102
  oshostname = platform.node()
103
103
  # log.info('osType: %s, osVersion: %s, oshostname: %s', osType, osVersion, oshostname)
104
- print('osType: '+osType+', osVersion: '+osVersion+', oshostname: '+oshostname)
104
+ print(f'osType: {osType}, osVersion: {osVersion}, oshostname: {oshostname}')
105
105
  return osType, osVersion, oshostname
106
106
 
107
107
 
@@ -253,7 +253,7 @@ def traverse(path):
253
253
  ############## REQUESTS LIBRARY ###################
254
254
  import time, sys, requests
255
255
  # import sys
256
- # import requests
256
+ import requests
257
257
  requests.packages.urllib3.disable_warnings()
258
258
 
259
259
  # For Futures - Parallel Processing of Requests
@@ -343,7 +343,7 @@ def sendRequest(method, requestUrl, cookies=None, headers=None, data=None, json=
343
343
  totalRequestsSent += 1
344
344
 
345
345
  # log.info('[%d/%d] Sending Request: %s',totalRequestsSent,len(requestUrl),requestUrl)
346
- log.debug('\t[%d] Sending Request: %s',totalRequestsSent,requestUrl)
346
+ log.debug(f'\t[{totalRequestsSent}] Sending Request: {requestUrl}')
347
347
  # log.info('\t[%d] Sending Request: %s',totalRequestsSent,requestUrl)
348
348
 
349
349
  # log.debug('Sending request - \n\t Request URL: %s %s\n\tRequest Headers: %s\n\t Request Data: %s\n\tRequest Json Data: %s', method, requestUrl, headers, data, json)
@@ -358,19 +358,25 @@ def sendRequest(method, requestUrl, cookies=None, headers=None, data=None, json=
358
358
  response=s.delete(requestUrl, cookies=cookies, headers=headers, data=data, json=json, params=params, files=files, timeout=timeout, allow_redirects=allow_redirects, verify=verify)
359
359
  if method=='put' or method=='PUT':
360
360
  response=s.put(requestUrl, cookies=cookies, headers=headers, data=data, json=json, params=params, files=files, timeout=timeout, allow_redirects=allow_redirects, verify=verify)
361
- # log.debug('Recieved Response - Response Status Code: %d\n\tResponse Headers: %s\n\tResponse Data: %s', response.result().status_code, str(response.result().headers), str(response.result().text))
362
- log.debug('Recieved Response - Response Status Code: %d\n\tResponse Data: %s', response.result().status_code, str(response.result().text))
361
+ # # log.debug('Recieved Response - Response Status Code: %d\n\tResponse Headers: %s\n\tResponse Data: %s', response.result().status_code, str(response.result().headers), str(response.result().text))
362
+ log.debug(f'Recieved Response - Response Status Code: {response.result().status_code}\n\tResponse Data: {str(response.result().text)}')
363
363
  return response
364
364
  # except requests.exceptions.ConnectionError as e:
365
365
  # except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, ConnectionResetError, http.client.RemoteDisconnected, RemoteDisconnected, ProtocolError, HTTPException, socket.gaierror) as e:
366
- except (ConnectionError, ConnectionResetError) as e:
367
- # log.error('ConnectionError occured - %s', e)
368
- log.error('Exception occured - %s', e)
366
+ except requests.exceptions.ConnectionError as e:
367
+ log.error(f'ConnectionError occured - {e}')
368
+ print('Sleeping for 60 secods before next request')
369
+ time.sleep(60)
370
+ sendRequest(method, requestUrl, cookies, headers, data, json, params, files, timeout, proxyhost, validResponseCodes, allow_redirects, verify)
371
+ # sys.exit()
372
+ except requests.exceptions.ConnectionResetError as e:
373
+ log.error(f'Exception occured - {e}')
369
374
  log.error('Is your internet connection Stable?')
370
- # sendRequest(requestUrl, cookies=cookies, headers=headers, data=data, json=json, params=params, files=files, timeout=timeout, proxyhost=None, validResponseCodes=False,allow_redirects=allow_redirects, verify=False)
371
375
  sys.exit()
376
+ except requests.exceptions.RequestException as e:
377
+ print(f"Request failed: {e}")
372
378
  except ConnectionRefusedError as e:
373
- log.error('Exception occured - %s', e)
379
+ log.error(f'Exception occured - {e}')
374
380
  log.error('Is proxy set and server not running?')
375
381
  sys.exit()
376
382
 
@@ -406,7 +412,7 @@ def sendBulkRequests(method, requestUrlList, cookies=None, headers=None, data=No
406
412
  for requestUrl in requestUrlList:
407
413
  totalBulkRequestsSent+=1
408
414
  # log.info('Sending Bulk Request...[%d/%d]', totalBulkRequestsSent, totalRequestUrl)
409
- log.debug('Sending Bulk Request...[%d/%d]', totalBulkRequestsSent, totalRequestUrl)
415
+ log.debug(f'Sending Bulk Request...[{totalBulkRequestsSent}/{totalRequestUrl}]')
410
416
  futureResponse = sendRequest(method, requestUrl, cookies=cookies, headers=headers, data=data, json=json, timeout=timeout, allow_redirects=allow_redirects, proxyhost=proxyhost)
411
417
  futureResponseList.append(futureResponse)
412
418
  return futureResponseList
@@ -1196,7 +1202,8 @@ def printAndSend(botToken,chatId,output):
1196
1202
 
1197
1203
  def logAndSend(botToken,chatId,output):
1198
1204
  log.info(output)
1199
- sendTelegramBotNotification(botToken,chatId,output)
1205
+ # sendTelegramBotNotification(botToken,chatId,output)
1206
+ sendDiscordBotNotification(botToken,chatId,output)
1200
1207
 
1201
1208
  ########## format a number as per indian currency
1202
1209
  def formatCurrrencyIndian(number):
@@ -1222,7 +1229,162 @@ def formatCurrrencyIndian(number):
1222
1229
 
1223
1230
  return formatted_number
1224
1231
 
1232
+ ########### DISCORD BOT NOTIFICATION - BOT DETAILS ##############
1233
+ # def getDiscordBotInfo(botToken):
1234
+ # log.info('Fetching BOT Information')
1235
+ # url = 'https://api.telegram.org/bot'+botToken+'/getMe'
1236
+ # response = sendRequest('get', url, proxyhost=proxyhost)
1237
+ # responseJson = response.result().json()
1238
+ # if responseJson['ok']==True:
1239
+ # if responseJson['result']:
1240
+ # id = responseJson['result']['id']
1241
+ # is_bot = responseJson['result']['is_bot']
1242
+ # first_name = responseJson['result']['first_name']
1243
+ # username = responseJson['result']['username']
1244
+ # can_join_groups = responseJson['result']['can_join_groups']
1245
+ # can_read_all_group_messages = responseJson['result']['can_read_all_group_messages']
1246
+ # supports_inline_queries = responseJson['result']['supports_inline_queries']
1247
+ # getVarInfo('id',id)
1248
+ # getVarInfo('is_bot',is_bot)
1249
+ # getVarInfo('first_name',first_name)
1250
+ # getVarInfo('username',username)
1251
+ # getVarInfo('can_join_groups',can_join_groups)
1252
+ # getVarInfo('can_read_all_group_messages',can_read_all_group_messages)
1253
+ # getVarInfo('supports_inline_queries',supports_inline_queries)
1254
+ # return True
1255
+ # else:
1256
+ # return False
1257
+ # else:
1258
+ # getVarInfo('responseJson',responseJson)
1259
+ # return False
1260
+
1261
+ ########### DISCORD BOT NOTIFICATION - FETCH RECEIVED MESSAGES ##############
1262
+ def getDiscordBotUpdates(botToken, channelId, messageCount=1):
1263
+ log.info('Checking new messages...')
1264
+ url = 'https://discord.com/api/v10/channels/'+channelId+'/messages?limit='+str(messageCount)
1265
+ headers = {'Authorization': 'Bot ' + botToken}
1266
+ response = sendRequest('get', url, headers=headers, proxyhost=proxyhost)
1267
+ # response = sendRequest('get', url, proxyhost=proxyhost)
1268
+ # try:
1269
+ if response.result().status_code == 200:
1270
+ responseJson = response.result().json()
1271
+ for msg in responseJson:
1272
+ author = msg['author']
1273
+ content = msg['content']
1274
+ timestamp = msg['timestamp']
1275
+ id = msg['id']
1276
+ username = author['username']
1277
+ # print(f"[{author['username']}] {content}")
1278
+
1279
+ getVarInfo('id',id)
1280
+ getVarInfo('timestamp',timestamp)
1281
+ getVarInfo('username',username)
1282
+ getVarInfo('content',content)
1283
+
1284
+ return id, timestamp, username, content
1285
+ # else:
1286
+ # log.info('\tNo Data in Result')
1287
+ # return 0, False, False, False, False
1288
+ # else:
1289
+ # getVarInfo('responseJson',responseJson)
1290
+ # return 0, False, False, False, False
1291
+ # except (KeyError, TypeError, ValueError) as e:
1292
+ # log.info('Exception Occured 202502042248: %s', e)
1293
+ # getVarInfo('responseJson',responseJson)
1294
+ # return 0, False, False, False, False
1295
+
1296
+
1297
+ # def clearDiscordBotUpdates(botToken, update_id=0):
1298
+ # log.info('Checking new messages...')
1299
+ # url = 'https://api.telegram.org/bot'+botToken+'/getUpdates?offset='+str(update_id+1)
1300
+ # response = sendRequest('get', url, proxyhost=proxyhost)
1301
+ # try:
1302
+ # responseJson = response.result().json()
1303
+ # if responseJson['ok']==True:
1304
+ # if responseJson['result']:
1305
+ # update_id = responseJson['result'][0]['update_id']
1306
+ # clearTelegramBotUpdates(botToken, update_id)
1307
+ # return True
1308
+ # else:
1309
+ # getVarInfo('responseJson',responseJson)
1310
+ # return False
1311
+ # except (KeyError, TypeError, ValueError) as e:
1312
+ # log.info('Exception Occured: %s', e)
1313
+ # getVarInfo('responseJson',responseJson)
1314
+ # return False
1315
+
1316
+ def fetchOTPDiscord(botToken, otpFetchWaitTime, otpChannelId):
1317
+ # 2FA - autofetch via telegram
1318
+ log.info('Fetching 2FA request with TOTP')
1319
+ twofa_value = 0
1320
+ retryCount = 0
1321
+ while retryCount<60:
1322
+ log.info('Sleeping for %d seconds', otpFetchWaitTime)
1323
+ time.sleep(otpFetchWaitTime)
1324
+ try:
1325
+ id, timestamp, username, content = getDiscordBotUpdates(botToken, otpChannelId, messageCount=1)
1326
+ log.info('update_id: %s, text: %s', id, content)
1327
+ twofa_value = content[-6:]
1328
+ getVarInfo('twofa_value',twofa_value)
1329
+ break
1330
+ except ValueError as e:
1331
+ retryCount += 1
1332
+ log.exception('Retrying %d since ValueError: %s',retryCount, e)
1333
+ # print(update_id, text)
1334
+ return twofa_value
1335
+
1336
+ ########### DISCORD BOT NOTIFICATION - SEND ##############
1337
+
1338
+ # function to validate if length is > 4096
1339
+ def sendDiscordBotNotification(botToken,channelId,message, parse_mode=''):
1340
+ msgs = [message[i:i + 2000] for i in range(0, len(message), 4096)]
1341
+ for text in msgs:
1342
+ sendDiscordBotNotificationMain(botToken,channelId,text, parse_mode)
1343
+
1344
+ def sendDiscordBotNotificationMain(botToken,channelId,message, parse_mode=''):
1345
+ log.info('Sending Message via BOT')
1346
+
1347
+ url = f'https://discord.com/api/v10/channels/{channelId}/messages'
1348
+ data = {'content': message}
1349
+ headers = {'Authorization': 'Bot ' + botToken}
1350
+ # proxyhost= 'http://127.0.0.1:8080'
1351
+ response = sendRequest('post', url, headers=headers, json=data, proxyhost=proxyhost)
1352
+ if response.result().status_code == 200:
1353
+ return True
1354
+ else:
1355
+ responseJson = response.result().json()
1356
+ try:
1357
+ log.info(f'Discord Bot Message Send Failure Error Description: {responseJson['errors']['content']['_errors'][0]['code']} - {responseJson['errors']['content']['_errors'][0]['message']}')
1358
+ except:
1359
+ log.info(f'Discord Bot Message Send Failure Error Description: {responseJson['message']}')
1360
+ getVarInfo('responseJson',responseJson)
1361
+ return False
1362
+
1363
+ # send telegram document
1364
+ def sendDiscordBotFile(botToken,channelId,filePath):
1365
+ documentFile = open(filePath, 'rb')
1366
+ url = f'https://discord.com/api/v10/channels/{channelId}/messages'
1367
+ files = {'file': documentFile}
1368
+ headers = {'Authorization': 'Bot ' + botToken}
1369
+ response = sendRequest('post', url, headers=headers, files=files, proxyhost=proxyhost)
1370
+ # response = sendRequest('post', url, params=params, files=files, proxyhost=proxyhost)
1371
+ responseJson = response.result().json()
1372
+ if response.result().status_code == 200:
1373
+ if responseJson['type']==0:
1374
+ return True
1375
+ else:
1376
+ log.info('Discord Bot Message Send Failure Error Description: %s', responseJson['description'])
1377
+ getVarInfo('responseJson',responseJson)
1378
+ return False
1379
+
1380
+ # if(optimuslib.sendTelegramNotification(botToken, chatId,output)):
1381
+ # print('Telegram Notification Sent.')
1382
+
1225
1383
 
1384
+ # getDiscordBotUpdates(botToken, channelId, messageCount)
1385
+ # fetchOTPDiscord(botToken, otpFetchWaitTime, otpChannelId)
1386
+ # sendDiscordBotNotification(botToken,channelId,message)
1387
+ # sendDiscordBotFile(botToken,channelId,filePath)
1226
1388
  ################################################
1227
1389
  log.info('[+] Optimuslib Import Sucessfull.')
1228
1390
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: optimuslib
3
- Version: 0.0.37
3
+ Version: 0.0.39
4
4
  Summary: Function Library for mostly used codes
5
5
  Author: Shomi Nanwani
6
6
  Requires-Python: >=3.9,<4.0
@@ -0,0 +1,5 @@
1
+ optimuslib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ optimuslib/optimuslib.py,sha256=LfDWhxtOT8pyP1PlB62Drkp3Of0maBCOVlEVUr_r_yw,55211
3
+ optimuslib-0.0.39.dist-info/METADATA,sha256=IwPhbKGK-wwxbKD_23BqyDzj-yVjPk-iKaBRPPSLiGY,611
4
+ optimuslib-0.0.39.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
5
+ optimuslib-0.0.39.dist-info/RECORD,,
@@ -1,5 +0,0 @@
1
- optimuslib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- optimuslib/optimuslib.py,sha256=9oRXJ9SqKqHlCuo_9BIYTrPUQ1fmc7ObUObzJ7oweVM,47839
3
- optimuslib-0.0.37.dist-info/METADATA,sha256=XjNdnYl_Z6Whpjj7tQDmizOG2Iu46pqE5MD2DrpatwE,611
4
- optimuslib-0.0.37.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
5
- optimuslib-0.0.37.dist-info/RECORD,,