-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSummary_Lambda_Function.py
More file actions
99 lines (84 loc) · 3.02 KB
/
Summary_Lambda_Function.py
File metadata and controls
99 lines (84 loc) · 3.02 KB
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
import pymysql
import json
import os
import requests
def lambda_handler(event, context):
# Database connection details
rds_host = os.environ['RDS_HOST']
username = os.environ['RDS_USERNAME']
password = os.environ['RDS_PASSWORD']
db_name = os.environ['RDS_DB_NAME']
# Telegram Bot API details
telegram_token = os.environ['TELEGRAM_TOKEN']
# Log the incoming event for debugging purposes
print("Received event: ", json.dumps(event, indent=4))
try:
# Check if the message key is present in the event
message = get_message_from_event(event)
chat_id = message['chat']['id']
# Connect to the database
connection = pymysql.connect(
host=rds_host,
user=username,
password=password,
db=db_name
)
try:
with connection.cursor() as cursor:
# Query to fetch medication details
sql = "SELECT medication_name, time FROM medreminder WHERE chatid = %s"
cursor.execute(sql, (chat_id,))
results = cursor.fetchall()
# Create the summary message
if results:
summary_message = "Here is a summary of your medications:\n"
for row in results:
summary_message += f"{row['medication_name']} at {row['time']}\n"
else:
summary_message = "You have no medications saved."
# Send the summary message to the user
send_telegram_message(telegram_token, chat_id, summary_message)
except pymysql.MySQLError as e:
print(f"MySQL Error: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps(f"MySQL Error: {str(e)}")
}
finally:
connection.close()
return {
'statusCode': 200,
'body': json.dumps('Summary sent successfully!')
}
except KeyError as e:
print(f"KeyError: {str(e)}")
return {
'statusCode': 400,
'body': json.dumps(f"Missing key: {str(e)}")
}
except Exception as e:
print(f"Exception: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps(f"Internal server error: {str(e)}")
}
def get_message_from_event(event):
"""Extract the message from the incoming event"""
if 'message' in event:
return event['message']
if 'body' in event:
body = json.loads(event['body'])
if 'message' in body:
return body['message']
raise KeyError("The 'message' key is missing in the event")
def send_telegram_message(token, chat_id, message):
url = f"https://api.telegram.org/bot{token}/sendMessage"
payload = {
'chat_id': chat_id,
'text': message
}
response = requests.post(url, json=payload)
if response.status_code != 200:
print(f"Failed to send message: {response.text}")
else:
print(f"Sent message: {message}")