-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
62 lines (40 loc) · 1.47 KB
/
main.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
import os
import json
import requests
TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")
CHAT_ID = os.environ.get("CHAT_ID")
URL_RESPONSE = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={CHAT_ID}&parse_mode=HTML&text="
def lambda_handler(event, context):
body = event_process(event)
if "spider" in body:
message, flag = scrapy_request(body)
elif "message" in body:
message, flag = telegram_request(body)
else:
raise Exception("Body resource not implemented")
status_code = send_message(message)
log = {"flag": flag, "message": message, "status_code": status_code}
return {"statusCode": 200, "body": json.dumps(log)}
def scrapy_request(body):
body_stats = body.get("stats", {})
template = "{}\n\n{}"
stats_table = ""
for stats in body_stats.keys():
stats_table = stats_table + "{} -> {}\n".format(stats, body_stats[stats])
message = template.format(body["spider"].upper(), stats_table.upper())
return message, "scrapy_request"
def telegram_request(body):
return "", "telegram_request"
def send_message(message):
message_url = URL_RESPONSE + message
send = requests.get(message_url)
return send.status_code
def event_process(event):
body = event.get("body", {})
if not body:
raise Exception("Body is Empty")
content = json.loads(body)
stats = content.get("stats", {})
if stats:
content["stats"] = json.loads(stats)
return content