Samfredoly commited on
Commit
e298590
·
verified ·
1 Parent(s): ccc02e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -48
app.py CHANGED
@@ -10,7 +10,7 @@ import os
10
  load_dotenv()
11
 
12
  # Configure logging
13
- logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger("bot_brain")
15
 
16
  # SMTP Server Configuration
@@ -33,22 +33,24 @@ def validate_email(email: str) -> bool:
33
  def send_email(from_addr: str, to_addr: str, subject: str, body: str) -> bool:
34
  """
35
  Sends an email using the SMTP client.
36
- Note: Some SMTP servers restrict the 'From' address.
37
  """
38
  msg = MIMEText(body)
39
  msg['Subject'] = subject
40
  msg['From'] = from_addr
41
  msg['To'] = to_addr
42
 
 
 
43
  try:
44
  with smtplib.SMTP(CLIENT_SMTP_HOST, SMTP_PORT) as server:
45
  server.starttls() # Upgrade to TLS
46
  server.login(SMTP_USER, SMTP_PASSWORD)
47
  server.sendmail(from_addr, [to_addr], msg.as_string())
48
- logger.info(f"Email sent from {from_addr} to {to_addr}")
 
49
  return True
50
  except Exception as e:
51
- logger.error(f"Error sending email from {from_addr} to {to_addr}: {e}")
52
  return False
53
 
54
  # Flask app acting as the Bot Brain API
@@ -65,57 +67,86 @@ def bot():
65
  4. Ask for the email body.
66
  When all details are collected, the email is sent.
67
  """
68
- try:
69
- data = request.json
70
- sender_number = data.get("from", "unknown")
71
- message_body = data.get("message", {}).get("text", {}).get("body", "").strip()
72
- except Exception as e:
73
- logger.error("Invalid JSON payload: %s", e)
74
- return jsonify({"status": "error", "message": "Invalid payload"}), 400
 
 
 
 
 
 
75
 
 
 
 
 
 
 
 
76
  state = conversations.get(sender_number, {})
77
 
78
  if not state:
79
- # Start a new conversation
80
  conversations[sender_number] = {"step": "from"}
81
- response_msg = "Welcome to SMTP Assistant! Please provide your 'From' email address."
82
- else:
83
- step = state.get("step")
84
- if step == "from":
85
- if validate_email(message_body):
86
- state["from"] = message_body
87
- state["step"] = "to"
88
- response_msg = "Thanks! Now, please provide the recipient's email address."
89
- else:
90
- response_msg = "Invalid email format. Please provide a valid 'From' email address."
91
- elif step == "to":
92
- if validate_email(message_body):
93
- state["to"] = message_body
94
- state["step"] = "subject"
95
- response_msg = "Great! Please provide the email subject."
96
- else:
97
- response_msg = "Invalid email format. Please provide a valid recipient email address."
98
- elif step == "subject":
99
- state["subject"] = message_body
100
- state["step"] = "body"
101
- response_msg = "Almost done! Please provide the email body."
102
- elif step == "body":
103
- state["body"] = message_body
104
- from_addr = state.get("from")
105
- to_addr = state.get("to")
106
- subject = state.get("subject")
107
- body = state.get("body")
108
- if send_email(from_addr, to_addr, subject, body):
109
- response_msg = f"Email sent successfully from {from_addr} to {to_addr}."
110
- else:
111
- response_msg = "Failed to send email. Please try again later."
112
- # Clear the conversation state after sending
113
- del conversations[sender_number]
114
  else:
115
- response_msg = "Unrecognized step. Let's start over. Please provide your 'From' email address."
116
- conversations[sender_number] = {"step": "from"}
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  return jsonify({"status": "success", "message": response_msg})
119
 
 
120
  if __name__ == "__main__":
121
- app.run(host="0.0.0.0", port=5000)
 
10
  load_dotenv()
11
 
12
  # Configure logging
13
+ logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
14
  logger = logging.getLogger("bot_brain")
15
 
16
  # SMTP Server Configuration
 
33
  def send_email(from_addr: str, to_addr: str, subject: str, body: str) -> bool:
34
  """
35
  Sends an email using the SMTP client.
 
36
  """
37
  msg = MIMEText(body)
38
  msg['Subject'] = subject
39
  msg['From'] = from_addr
40
  msg['To'] = to_addr
41
 
42
+ logger.debug(f"Preparing to send email from {from_addr} to {to_addr} with subject '{subject}'")
43
+
44
  try:
45
  with smtplib.SMTP(CLIENT_SMTP_HOST, SMTP_PORT) as server:
46
  server.starttls() # Upgrade to TLS
47
  server.login(SMTP_USER, SMTP_PASSWORD)
48
  server.sendmail(from_addr, [to_addr], msg.as_string())
49
+
50
+ logger.info(f"Email sent successfully from {from_addr} to {to_addr}")
51
  return True
52
  except Exception as e:
53
+ logger.error(f"Error sending email: {e}")
54
  return False
55
 
56
  # Flask app acting as the Bot Brain API
 
67
  4. Ask for the email body.
68
  When all details are collected, the email is sent.
69
  """
70
+ logger.debug("Received a request at /bot")
71
+
72
+ # Ensure the request contains valid JSON
73
+ if not request.is_json:
74
+ logger.error("Invalid request format: Not JSON")
75
+ return jsonify({"status": "error", "message": "Request must be JSON"}), 400
76
+
77
+ data = request.json
78
+ logger.debug(f"Request payload: {data}")
79
+
80
+ # Extract sender number and message
81
+ sender_number = data.get("from")
82
+ message_body = data.get("message", {}).get("text", {}).get("body", "").strip()
83
 
84
+ if not sender_number or not message_body:
85
+ logger.error("Missing required fields in request")
86
+ return jsonify({"status": "error", "message": "Missing 'from' or 'message.text.body'"}), 400
87
+
88
+ logger.info(f"Processing message from {sender_number}: '{message_body}'")
89
+
90
+ # Retrieve or initialize conversation state
91
  state = conversations.get(sender_number, {})
92
 
93
  if not state:
94
+ logger.info(f"New conversation started for {sender_number}")
95
  conversations[sender_number] = {"step": "from"}
96
+ return jsonify({"status": "success", "message": "Welcome! Please provide your 'From' email address."})
97
+
98
+ step = state.get("step")
99
+ logger.debug(f"Current step for {sender_number}: {step}")
100
+
101
+ response_msg = "Something went wrong."
102
+
103
+ if step == "from":
104
+ if validate_email(message_body):
105
+ state["from"] = message_body
106
+ state["step"] = "to"
107
+ response_msg = "Thanks! Now, please provide the recipient's email address."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  else:
109
+ response_msg = "Invalid email format. Please provide a valid 'From' email address."
 
110
 
111
+ elif step == "to":
112
+ if validate_email(message_body):
113
+ state["to"] = message_body
114
+ state["step"] = "subject"
115
+ response_msg = "Great! Please provide the email subject."
116
+ else:
117
+ response_msg = "Invalid email format. Please provide a valid recipient email address."
118
+
119
+ elif step == "subject":
120
+ state["subject"] = message_body
121
+ state["step"] = "body"
122
+ response_msg = "Almost done! Please provide the email body."
123
+
124
+ elif step == "body":
125
+ state["body"] = message_body
126
+
127
+ from_addr = state.get("from")
128
+ to_addr = state.get("to")
129
+ subject = state.get("subject")
130
+ body = state.get("body")
131
+
132
+ logger.info(f"Attempting to send email from {from_addr} to {to_addr} with subject '{subject}'")
133
+
134
+ if send_email(from_addr, to_addr, subject, body):
135
+ response_msg = f"Email sent successfully from {from_addr} to {to_addr}."
136
+ else:
137
+ response_msg = "Failed to send email. Please try again later."
138
+
139
+ # Clear the conversation state after sending
140
+ del conversations[sender_number]
141
+ logger.info(f"Conversation with {sender_number} cleared.")
142
+
143
+ else:
144
+ response_msg = "Unrecognized step. Restarting. Please provide your 'From' email address."
145
+ conversations[sender_number] = {"step": "from"}
146
+
147
+ logger.debug(f"Response message to {sender_number}: {response_msg}")
148
  return jsonify({"status": "success", "message": response_msg})
149
 
150
+
151
  if __name__ == "__main__":
152
+ app.run(host="0.0.0.0", port=5000, debug=True)