TwilioBot / app.py
masadonline's picture
Update app.py
1b813f3 verified
import streamlit as st
import requests
from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
st.set_page_config(page_title="WhatsApp Chat", layout="wide")
st.title("πŸ“± Two-Way WhatsApp Chat via Twilio Conversations")
# Twilio credentials
account_sid = st.secrets.get("TWILIO_ACCOUNT_SID") or st.text_input("Twilio Account SID", "")
auth_token = st.secrets.get("TWILIO_AUTH_TOKEN") or st.text_input("Twilio Auth Token", type="password")
# Conversation SID and Author (e.g., 'system' or phone number)
conversation_sid = st.text_input("Conversation SID", "CH0401ce390b374780b3eaded677d882b0")
author = st.text_input("Author Name (e.g., system or whatsapp:+92333xxxxxxx)", "system")
# Message to send
msg_to_send = st.text_input("Type your message here")
def send_message(account_sid, auth_token, conversation_sid, author, body):
try:
client = Client(account_sid, auth_token)
message = client.conversations \
.v1 \
.conversations(conversation_sid) \
.messages \
.create(author=author, body=body)
return message.sid
except TwilioRestException as e:
return f"Twilio Error: {str(e)}"
except Exception as e:
return f"Error: {str(e)}"
def fetch_messages(account_sid, auth_token, conversation_sid):
try:
client = Client(account_sid, auth_token)
messages = client.conversations.v1.conversations(conversation_sid).messages.list(limit=50)
return messages
except Exception as e:
return f"Error fetching messages: {e}"
# Send message button
if st.button("πŸ“€ Send Message"):
if not all([account_sid, auth_token, conversation_sid, author, msg_to_send]):
st.error("Please fill in all fields.")
else:
sid = send_message(account_sid, auth_token, conversation_sid, author, msg_to_send)
if sid.startswith("IM"):
st.success(f"Message sent! SID: {sid}")
else:
st.error(sid)
st.markdown("---")
st.subheader("πŸ•“ Chat History")
# Display message history
if st.button("πŸ”„ Refresh Chat"):
if not all([account_sid, auth_token, conversation_sid]):
st.warning("Provide Twilio credentials and Conversation SID first.")
else:
messages = fetch_messages(account_sid, auth_token, conversation_sid)
if isinstance(messages, str):
st.error(messages)
else:
for msg in reversed(messages): # Show newest at bottom
sender = msg.author
body = msg.body or "[No content]"
timestamp = msg.date_created.strftime("%Y-%m-%d %H:%M:%S")
st.markdown(f"**{sender}** [{timestamp}]: {body}")