Spaces:
Running
Running
import streamlit as st | |
from twilio.rest import Client | |
from twilio.base.exceptions import TwilioRestException | |
# Streamlit app title | |
st.title("Send WhatsApp Message with Twilio") | |
# Twilio credentials (It's best to get these from Streamlit secrets for security) | |
account_sid = st.secrets.get("TWILIO_ACCOUNT_SID") or st.text_input("Account SID", "") | |
auth_token = st.secrets.get("TWILIO_AUTH_TOKEN") or st.text_input("Auth Token", "") | |
# Input fields for message parameters | |
from_whatsapp = st.text_input("From (WhatsApp Number)", "whatsapp:+14155238886") # Default value provided | |
to_whatsapp = st.text_input("To (WhatsApp Number)", "whatsapp:+923335500016") # Default value provided | |
content_sid = st.text_input("Content SID", "HXb5b62575e6e4ff6129ad7c8efe1f983e") # Default value provided | |
content_variables = st.text_input("Content Variables (e.g., {\"1\":\"12/1\",\"2\":\"3pm\"})", '{"1":"12/1","2":"3pm"}') # Default value provided | |
# Function to send the WhatsApp message | |
def send_whatsapp_message(account_sid, auth_token, from_whatsapp, to_whatsapp, content_sid, content_variables): | |
""" | |
Sends a WhatsApp message using Twilio. | |
Args: | |
account_sid (str): Your Twilio Account SID. | |
auth_token (str): Your Twilio Auth Token. | |
from_whatsapp (str): The WhatsApp number to send the message from (in the format 'whatsapp:+number'). | |
to_whatsapp (str): The WhatsApp number to send the message to (in the format 'whatsapp:+number'). | |
content_sid (str): The SID of the Twilio Content template. | |
content_variables (str): A JSON string of the variables to populate the template. | |
Returns: | |
str: The SID of the sent message, or an error message. | |
""" | |
try: | |
client = Client(account_sid, auth_token) | |
message = client.messages.create( | |
from_=from_whatsapp, | |
content_sid=content_sid, | |
content_variables=content_variables, | |
to=to_whatsapp, | |
) | |
return message.sid | |
except TwilioRestException as e: | |
return str(e) | |
except Exception as e: | |
return f"An unexpected error occurred: {e}" | |
# Button to trigger the message sending | |
if st.button("Send WhatsApp Message"): | |
if not account_sid or not auth_token: | |
st.error("Please provide your Twilio Account SID and Auth Token.") | |
elif not from_whatsapp or not to_whatsapp or not content_sid or not content_variables: | |
st.error("Please fill in all the input fields.") | |
else: | |
# Call the function to send the message | |
message_sid = send_whatsapp_message(account_sid, auth_token, from_whatsapp, to_whatsapp, content_sid, content_variables) | |
if message_sid.startswith(("SM", "MM")): # Accept both SM and MM SIDs | |
st.success(f"Message sent successfully! SID: {message_sid}") | |
else: | |
st.error(f"Error sending message: {message_sid}") | |