-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDispatcher_Lambda_Function.py
More file actions
123 lines (106 loc) · 4.16 KB
/
Dispatcher_Lambda_Function.py
File metadata and controls
123 lines (106 loc) · 4.16 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import json
import os
import boto3
import pymysql
import requests
def lambda_handler(event, context):
# Log the incoming event for debugging purposes
print("Received event: ", json.dumps(event, indent=4))
try:
# Parse the incoming message from Telegram
message = get_message(event)
chat_id = message['chat']['id']
text = message['text']
# Handle /start command
if text == "/start":
initialize_user(chat_id)
send_telegram_message(os.environ['TELEGRAM_TOKEN'], chat_id,
"Hello! Welcome to the MedReminder bot. Use /add to add a medication or /summary to get a summary of your medications.")
return response(200, 'Start message sent successfully!')
elif text.startswith("/add"):
target_function = get_env_variable('ADD_DRUG_FUNCTION')
elif text.startswith("/summary"):
target_function = get_env_variable('SUMMARY_FUNCTION')
elif text.startswith("/question"):
target_function = os.environ['CHATGPT_FUNCTION']
elif text == "yes" or text == "no":
target_function = get_env_variable('USER_ANSWER_LAMBDA')
else:
send_telegram_message(os.environ['TELEGRAM_TOKEN'], chat_id,
"Invalid command. Use /add or /summary.")
return response(200, 'Invalid command message sent successfully!')
# Invoke the target Lambda function
invoke_lambda(target_function, event)
return response(200, 'Request routed successfully!')
except KeyError as e:
print(f"KeyError: {str(e)}")
return response(400, f"Missing key: {str(e)}")
except Exception as e:
print(f"Exception: {str(e)}")
return response(500, f"Internal server error: {str(e)}")
def get_message(event):
""" Extract the message from the incoming event """
if 'message' in event:
return event['message']
elif '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 get_env_variable(name):
""" Retrieve environment variable or raise an error """
value = os.environ.get(name)
if not value:
raise KeyError(f"Environment variable {name} is missing")
return value
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}")
def invoke_lambda(function_name, event):
lambda_client = boto3.client('lambda')
response = lambda_client.invoke(
FunctionName=function_name,
InvocationType='Event', # Asynchronous invocation
Payload=json.dumps(event)
)
print(f"Invoked function {function_name}, response: {response}")
def response(status_code, message):
return {
'statusCode': status_code,
'body': json.dumps(message)
}
def initialize_user(chat_id):
# 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']
# Connect to the database
connection = pymysql.connect(
host=rds_host,
user=username,
password=password,
db=db_name
)
try:
with connection.cursor() as cursor:
# Check if the chatid already exists
cursor.execute("SELECT chatid FROM users_scores WHERE chatid = %s", (chat_id,))
result = cursor.fetchone()
if not result:
# Insert a new record with chatid and score 0
cursor.execute("INSERT INTO users_scores (chatid, score) VALUES (%s, %s)", (chat_id, 0))
connection.commit()
print(f"Initialized user with chatid {chat_id}")
except pymysql.MySQLError as e:
print(f"MySQL Error: {str(e)}")
finally:
connection.close()