masadonline commited on
Commit
5048dcb
·
verified ·
1 Parent(s): 2934ef6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -61
app.py CHANGED
@@ -1,66 +1,60 @@
1
  import streamlit as st
2
- import os
3
  from twilio.rest import Client
4
- import time
5
-
6
- # Set up Streamlit app
7
- st.title("Twilio Conversation Viewer")
8
-
9
- # Get Twilio credentials from Streamlit secrets
10
- account_sid = st.secrets["TWILIO_SID"]
11
- auth_token = st.secrets["TWILIO_TOKEN"]
12
- conversation_sid = st.secrets["TWILIO_CONVERSATION_SID"]
13
-
14
- client = Client(account_sid, auth_token)
15
-
16
- def fetch_messages(conversation_sid):
17
- """Fetches messages from the Twilio conversation."""
18
- try:
19
- messages = client.conversations.v1.conversations(conversation_sid).messages.list()
20
- return list(messages)
21
- except Exception as e:
22
- st.error(f"Error fetching messages: {e}")
23
- return []
24
-
25
- def display_messages(messages):
26
- """Displays messages in the Streamlit app."""
27
- for message in messages:
28
- if message.author == 'system':
29
- st.markdown(f'<div style="background-color:#f0f2f6;padding:10px;border-radius:5px;margin-bottom:5px;"><strong>System:</strong> {message.body}</div>', unsafe_allow_html=True)
30
- else:
31
- st.markdown(f'<div style="background-color:#e1f5fe;padding:10px;border-radius:5px;margin-bottom:5px;"><strong>{message.author}:</strong> {message.body}</div>', unsafe_allow_html=True)
32
-
33
- def send_message(conversation_sid, author, body):
34
- """Sends a new message to the Twilio conversation."""
35
  try:
36
- message = client.conversations.v1.conversations(conversation_sid).messages.create(author=author, body=body)
37
- st.success(f"Message sent (SID: {message.sid})")
 
 
 
 
 
 
 
 
38
  except Exception as e:
39
- st.error(f"Error sending message: {e}")
40
-
41
- # Sidebar for configuration and actions
42
- with st.sidebar:
43
- st.header("Conversation Actions")
44
- new_message = st.text_input("Enter new message:")
45
- message_author = st.text_input("Your identifier (e.g., user1):", "user")
46
- if st.button("Send Message"):
47
- if new_message:
48
- send_message(conversation_sid, message_author, new_message)
49
- # Give a short delay to see the updated messages
50
- time.sleep(1)
51
- st.rerun() # Refresh the app to show the new message
52
-
53
- st.header("Real-time Updates")
54
- refresh_rate = st.slider("Refresh interval (seconds):", 1, 10, 3)
55
-
56
- # Main area to display messages
57
- st.subheader("Conversation History")
58
-
59
- while True:
60
- messages = fetch_messages(conversation_sid)
61
- if messages:
62
- display_messages(messages)
63
  else:
64
- st.info("No messages in this conversation yet.")
65
- time.sleep(refresh_rate)
66
- st.empty() # Clear the previous messages for the next update
 
 
 
 
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"): # Twilio message SIDs start with "SM"
58
+ st.success(f"Message sent successfully! SID: {message_sid}")
59
+ else:
60
+ st.error(f"Error sending message: {message_sid}")