masadonline commited on
Commit
1b813f3
Β·
verified Β·
1 Parent(s): b58e86b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -49
app.py CHANGED
@@ -1,61 +1,70 @@
1
  import streamlit as st
 
2
  from twilio.rest import Client
3
  from twilio.base.exceptions import TwilioRestException
4
 
5
- # Streamlit app title
6
- st.title("Send WhatsApp Message with Twilio")
7
-
8
- # Twilio credentials (It's best to get these from Streamlit secrets for security)
9
- account_sid = st.secrets.get("TWILIO_ACCOUNT_SID") or st.text_input("Account SID", "")
10
- auth_token = st.secrets.get("TWILIO_AUTH_TOKEN") or st.text_input("Auth Token", "")
11
-
12
- # Input fields for message parameters
13
- from_whatsapp = st.text_input("From (WhatsApp Number)", "whatsapp:+14155238886") # Default value provided
14
- to_whatsapp = st.text_input("To (WhatsApp Number)", "whatsapp:+923335500016") # Default value provided
15
- content_sid = st.text_input("Content SID", "HXb5b62575e6e4ff6129ad7c8efe1f983e") # Default value provided
16
- content_variables = st.text_input("Content Variables (e.g., {\"1\":\"12/1\",\"2\":\"3pm\"})", '{"1":"12/1","2":"3pm"}') # Default value provided
17
-
18
- # Function to send the WhatsApp message
19
- def send_whatsapp_message(account_sid, auth_token, from_whatsapp, to_whatsapp, content_sid, content_variables):
20
- """
21
- Sends a WhatsApp message using Twilio.
22
-
23
- Args:
24
- account_sid (str): Your Twilio Account SID.
25
- auth_token (str): Your Twilio Auth Token.
26
- from_whatsapp (str): The WhatsApp number to send the message from (in the format 'whatsapp:+number').
27
- to_whatsapp (str): The WhatsApp number to send the message to (in the format 'whatsapp:+number').
28
- content_sid (str): The SID of the Twilio Content template.
29
- content_variables (str): A JSON string of the variables to populate the template.
30
-
31
- Returns:
32
- str: The SID of the sent message, or an error message.
33
- """
34
  try:
35
  client = Client(account_sid, auth_token)
36
- message = client.messages.create(
37
- from_=from_whatsapp,
38
- content_sid=content_sid,
39
- content_variables=content_variables,
40
- to=to_whatsapp,
41
- )
42
  return message.sid
43
  except TwilioRestException as e:
44
- return str(e)
45
  except Exception as e:
46
- return f"An unexpected error occurred: {e}"
47
-
48
- # Button to trigger the message sending
49
- if st.button("Send WhatsApp Message"):
50
- if not account_sid or not auth_token:
51
- st.error("Please provide your Twilio Account SID and Auth Token.")
52
- elif not from_whatsapp or not to_whatsapp or not content_sid or not content_variables:
53
- st.error("Please fill in all the input fields.")
 
 
 
 
 
 
54
  else:
55
- # Call the function to send the message
56
- message_sid = send_whatsapp_message(account_sid, auth_token, from_whatsapp, to_whatsapp, content_sid, content_variables)
57
- if message_sid.startswith(("SM", "MM")): # Accept both SM and MM SIDs
58
- st.success(f"Message sent successfully! SID: {message_sid}")
59
  else:
60
- st.error(f"Error sending message: {message_sid}")
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
  from twilio.rest import Client
4
  from twilio.base.exceptions import TwilioRestException
5
 
6
+ st.set_page_config(page_title="WhatsApp Chat", layout="wide")
7
+
8
+ st.title("πŸ“± Two-Way WhatsApp Chat via Twilio Conversations")
9
+
10
+ # Twilio credentials
11
+ account_sid = st.secrets.get("TWILIO_ACCOUNT_SID") or st.text_input("Twilio Account SID", "")
12
+ auth_token = st.secrets.get("TWILIO_AUTH_TOKEN") or st.text_input("Twilio Auth Token", type="password")
13
+
14
+ # Conversation SID and Author (e.g., 'system' or phone number)
15
+ conversation_sid = st.text_input("Conversation SID", "CH0401ce390b374780b3eaded677d882b0")
16
+ author = st.text_input("Author Name (e.g., system or whatsapp:+92333xxxxxxx)", "system")
17
+
18
+ # Message to send
19
+ msg_to_send = st.text_input("Type your message here")
20
+
21
+ def send_message(account_sid, auth_token, conversation_sid, author, body):
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  try:
23
  client = Client(account_sid, auth_token)
24
+ message = client.conversations \
25
+ .v1 \
26
+ .conversations(conversation_sid) \
27
+ .messages \
28
+ .create(author=author, body=body)
 
29
  return message.sid
30
  except TwilioRestException as e:
31
+ return f"Twilio Error: {str(e)}"
32
  except Exception as e:
33
+ return f"Error: {str(e)}"
34
+
35
+ def fetch_messages(account_sid, auth_token, conversation_sid):
36
+ try:
37
+ client = Client(account_sid, auth_token)
38
+ messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=50)
39
+ return messages
40
+ except Exception as e:
41
+ return f"Error fetching messages: {e}"
42
+
43
+ # Send message button
44
+ if st.button("πŸ“€ Send Message"):
45
+ if not all([account_sid, auth_token, conversation_sid, author, msg_to_send]):
46
+ st.error("Please fill in all fields.")
47
  else:
48
+ sid = send_message(account_sid, auth_token, conversation_sid, author, msg_to_send)
49
+ if sid.startswith("IM"):
50
+ st.success(f"Message sent! SID: {sid}")
 
51
  else:
52
+ st.error(sid)
53
 
54
+ st.markdown("---")
55
+ st.subheader("πŸ•“ Chat History")
56
+
57
+ # Display message history
58
+ if st.button("πŸ”„ Refresh Chat"):
59
+ if not all([account_sid, auth_token, conversation_sid]):
60
+ st.warning("Provide Twilio credentials and Conversation SID first.")
61
+ else:
62
+ messages = fetch_messages(account_sid, auth_token, conversation_sid)
63
+ if isinstance(messages, str):
64
+ st.error(messages)
65
+ else:
66
+ for msg in reversed(messages): # Show newest at bottom
67
+ sender = msg.author
68
+ body = msg.body or "[No content]"
69
+ timestamp = msg.date_created.strftime("%Y-%m-%d %H:%M:%S")
70
+ st.markdown(f"**{sender}** [{timestamp}]: {body}")