-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd_Lambda_Function.py
More file actions
103 lines (87 loc) · 3.27 KB
/
Add_Lambda_Function.py
File metadata and controls
103 lines (87 loc) · 3.27 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
100
101
102
103
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:
# Parse the incoming message from Telegram
if 'body' in event:
body = json.loads(event['body'])
if 'message' not in body:
raise KeyError("The 'message' key is missing in the event body")
message = body['message']
else:
raise KeyError("The 'body' key is missing in the event")
chat_id = message['chat']['id']
message_body = message['text']
# Check if the message format is correct
if ',' not in message_body:
raise ValueError("Invalid message format. Expected 'medication_name, time'.")
# Assuming the format is "medication_name, time"
medication_name, time = map(str.strip, message_body.split(','))
# Connect to the database
connection = pymysql.connect(
host=rds_host,
user=username,
password=password,
db=db_name
)
try:
with connection.cursor() as cursor:
# Insert data into MySQL
sql = "INSERT INTO medreminder (chatid, medication_name, time) VALUES (%s, %s, %s)"
cursor.execute(sql, (chat_id, medication_name, time))
connection.commit()
print(f"Inserted medication: {medication_name} at {time} for chat ID: {chat_id}")
# Send confirmation message back to the user
send_telegram_message(telegram_token, chat_id, f"Medication '{medication_name}' has been saved for {time}.")
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('Medication saved successfully!')
}
except KeyError as e:
print(f"KeyError: {str(e)}")
return {
'statusCode': 400,
'body': json.dumps(f"Missing key: {str(e)}")
}
except ValueError as e:
print(f"ValueError: {str(e)}")
return {
'statusCode': 400,
'body': json.dumps(f"Value error: {str(e)}")
}
except Exception as e:
print(f"Exception: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps(f"Internal server error: {str(e)}")
}
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}")