-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
178 lines (140 loc) Β· 6.28 KB
/
app.py
File metadata and controls
178 lines (140 loc) Β· 6.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import streamlit as st
from streamlit_autorefresh import st_autorefresh
from streamlit.components.v1 import html as st_html
import streamlit.components.v1 as components
import random
import time
import html
from config import PAGE_CONFIG, CUSTOM_CSS
from utils import (
format_timestamp, get_active_users, get_messages,
send_message, test_connection, get_display_name
)
st.set_page_config(**PAGE_CONFIG)
st.markdown(CUSTOM_CSS, unsafe_allow_html=True)
# Initialize session state
if 'selected_user' not in st.session_state:
st.session_state.selected_user = None
# Main App
def main():
# Only show title when no user is selected
if not st.session_state.selected_user:
st.title("π¬ WhatsApp Admin Dashboard")
# Connection status
if test_connection():
if not st.session_state.selected_user:
st.success("π’ Connected to OMS Server")
else:
st.error("π΄ Cannot connect to OMS Server")
st.stop()
# Sidebar - User List
with st.sidebar:
# Controls
col1, col2 = st.columns([1, 1])
with col1:
if st.button("π Refresh", use_container_width=True):
st.rerun()
with col2:
# Auto-refresh toggle
auto_refresh = st.toggle("β± Auto (10s)", key="auto_refresh")
st.header("π₯ Active Conversations")
# Search bar
search_query = st.text_input("π Search contacts", placeholder="Search by name or phone...", label_visibility="collapsed")
if auto_refresh:
st_autorefresh(interval=10 * 1000, key="refresh")
# Fetch users
users = get_active_users()
# Filter users based on search
if search_query:
filtered_users = []
for user in users:
user_name = get_display_name(user['userName'], user['userId']).lower()
user_phone = user['userId'][2:]
if search_query.lower() in user_name or search_query in user_phone:
filtered_users.append(user)
users = filtered_users
if users:
st.write(f"**{len(users)} active users**")
for index, user in enumerate(users):
user_id = user['userId']
user_name = get_display_name(user['userName'], user_id)
last_msg : str = user['lastMessage']
last_time = format_timestamp(user['lastMessageTime'])
direction_icon = "" if user['direction'] == 'out' else ""
phone = f"{user_id[2:]}"
# User card
if st.button(
f"{direction_icon} **{user_name}** ({phone}) \n{last_msg[:25]} *{last_time}*",
key=f"user_{user_id}_{index}",
use_container_width=True
):
st.session_state.selected_user = user
st.rerun()
else:
st.info("No active conversations")
# Main Chat Area
if st.session_state.selected_user:
user = st.session_state.selected_user
user_id = user['userId']
user_name = get_display_name(user['userName'], user_id)
st.markdown(f"#### π¬ {user_name} ({user_id})")
# chatScreen_html = '<div class="chat-screen" id="chat-screen">'
# chatScreen_html += f'<h3>π¬ {user_name} ({user_id})</h3>'
# Messages Container
messages = get_messages(user_id)
# Build all messages HTML in one block
messages_html = '<div class="chat-container" id="chat-container">'
if messages:
for msg in messages:
timestamp = format_timestamp(msg['timestamp'])
escaped_message = html.escape(msg['message'])
if msg['direction'] == 'in':
messages_html += f'<div class="message-left"><div class="user-message"><div class="message-sender">{html.escape(user_name)}</div><div>{escaped_message}</div><div class="message-timestamp">{timestamp}</div></div></div>'
else:
messages_html += f'<div class="message-right"><div class="bot-message"><div class="message-sender">You (Bot)</div><div>{escaped_message}</div><div class="message-timestamp">{timestamp}</div></div></div>'
messages_html += '<div id="end-of-chat"></div>'
# st.markdown(messages_html, unsafe_allow_html=True)
messages_html += '</div>'
# chatScreen_html += messages_html
# chatScreen_html += '</div>'
st.markdown(messages_html, unsafe_allow_html=True)
# components.html(chatScreen_html)
# Message Input
form_key = f"send_message_form_{user_id}"
with st.form(form_key, clear_on_submit=True):
col1, col2 = st.columns([9, 1])
with col1:
message_input = st.text_input(
"",
placeholder="Type your message...",
label_visibility="collapsed"
)
with col2:
send_button = st.form_submit_button("β€", use_container_width=True)
if send_button and message_input and message_input.strip():
with st.spinner("Sending..."):
success = send_message(user_id, message_input.strip())
if success:
st.success("β
Message sent!")
time.sleep(0.5)
st.rerun()
else:
st.error("β Failed to send")
else:
# Welcome screen
st.markdown("""
### π Welcome to WhatsApp Admin Dashboard
Select a conversation from the sidebar to start monitoring messages and sending custom responses.
#### Features:
- π± Monitor all WhatsApp conversations
- π¬ View message history
- π€ Send custom messages to users
- π Manual refresh available
#### Getting Started:
1. Check the connection status above
2. Select a user from the sidebar
3. View their conversation history
4. Send custom messages as needed
""")
# Run the main app
main()