gkippili commited on
Commit
dcce80d
·
verified ·
1 Parent(s): cefbbce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -151
app.py CHANGED
@@ -2,116 +2,28 @@ import streamlit as st
2
  import pandas as pd
3
  import pywhatkit
4
  import time
5
- import pyautogui
6
- import os
7
- from datetime import datetime
8
  from pyvirtualdisplay import Display # Import PyVirtualDisplay
9
 
10
  # Initialize a virtual display (required for headless environments)
11
  display = Display(visible=0, size=(800, 600))
12
  display.start() # Start the virtual display
13
 
14
- # Set page configuration
15
- st.set_page_config(page_title="WhatsApp Instant Messenger", page_icon="📱", layout="centered")
16
-
17
- # Custom CSS for styling
18
- st.markdown(
19
- """
20
- <style>
21
- /* Background Color */
22
- .stApp {
23
- background-color: #802b57;
24
- }
25
-
26
- /* Title and Labels */
27
- h1, h2, h3, label {
28
- color: white !important;
29
- font-weight: bold !important;
30
- }
31
-
32
- /* Success Messages */
33
- .stSuccess {
34
- color: white !important;
35
- font-weight: bold !important;
36
- }
37
-
38
- /* Error Messages */
39
- .stError {
40
- color: red !important;
41
- font-weight: bold !important;
42
- }
43
-
44
- /* Warning Messages */
45
- .stWarning {
46
- color: orange !important;
47
- font-weight: bold !important;
48
- }
49
-
50
- /* Spinner Text */
51
- .stSpinner > div > div {
52
- color: white !important;
53
- font-weight: bold !important;
54
- }
55
-
56
- /* Button Styling */
57
- .stButton button {
58
- background-color: #25D366;
59
- color: white;
60
- font-weight: bold;
61
- }
62
-
63
- /* File Uploader Label */
64
- .stFileUploader label {
65
- color: white !important;
66
- font-weight: bold !important;
67
- }
68
- /* Title, Labels, and All Messages */
69
- h1, h2, h3, label, p, .stSuccess, .stError, .stWarning, .stInfo, .stSpinner > div > div {
70
- color: white !important;
71
- font-weight: bold !important;
72
- }
73
-
74
- /* Button Styling */
75
- .stButton button {
76
- background-color: #25D366;
77
- color: white;
78
- font-weight: bold;
79
- }
80
-
81
- /* File Uploader Label */
82
- .stFileUploader label {
83
- color: white !important;
84
- font-weight: bold !important;
85
- }
86
-
87
- /* Progress Bar Text */
88
- .stProgress > div > div > div {
89
- color: white !important;
90
- font-weight: bold !important;
91
- }
92
- </style>
93
- """,
94
- unsafe_allow_html=True,
95
- )
96
-
97
- # Function to send WhatsApp message instantly and press enter
98
  def send_whatsapp_message(phone_number, message):
99
  try:
100
  # Clean phone number to ensure proper format
101
  phone_number = str(phone_number).strip()
102
  if not phone_number.startswith('+'):
103
  phone_number = '+' + phone_number
 
104
  # Use pywhatkit to open WhatsApp Web with the message
105
  pywhatkit.sendwhatmsg_instantly(
106
  phone_no=phone_number,
107
  message=message,
108
  wait_time=15, # Wait time for WhatsApp Web to load
109
- tab_close=False # Keep tab open
110
  )
111
-
112
- time.sleep(2) # Small delay
113
- pyautogui.press('enter') # Press Enter to send
114
-
115
  return True, None
116
  except Exception as e:
117
  return False, str(e)
@@ -120,84 +32,68 @@ def send_whatsapp_message(phone_number, message):
120
  st.title("WhatsApp Instant Messenger 📱")
121
  st.markdown("**Send instant WhatsApp messages to multiple recipients.**")
122
 
123
- # Manual Input Option
124
- st.subheader("**Send Single Message**")
125
- phone_number = st.text_input("**Enter Phone Number (with country code, e.g., +1234567890):**", key="single_phone")
126
- message = st.text_area("**Enter Message:**", key="single_message")
127
- if st.button("Send Now", key="send_single"):
128
- if phone_number and message:
129
- with st.spinner("Sending message..."):
130
- success, error = send_whatsapp_message(phone_number, message)
131
- if success:
132
- st.success(f"Message sent successfully to {phone_number}!")
133
- else:
134
- st.error(f"Failed to send message: {error}")
135
- else:
136
- st.warning("Please enter both phone number and message.")
137
-
138
  # File Upload Option
139
- st.subheader("**Send Multiple Messages**")
140
- st.markdown("**Upload an Excel file with columns:**")
141
  uploaded_file = st.file_uploader("Upload your Excel file", type=["xls", "xlsx"])
142
  if uploaded_file:
143
  try:
144
  # Read the Excel file
145
- if uploaded_file.name.endswith('.xls'):
146
- df = pd.read_excel(uploaded_file, engine='xlrd', dtype={"Phone Numbers": str})
147
- elif uploaded_file.name.endswith('.xlsx'):
148
- df = pd.read_excel(uploaded_file, engine='openpyxl', dtype={"Phone Numbers": str})
149
-
150
  st.success("File uploaded successfully!", icon="✅")
 
151
  # Validate required columns
152
- required_columns = {"Phone Numbers", "Message"}
153
  if not required_columns.issubset(df.columns):
154
  missing = required_columns - set(df.columns)
155
  st.error(f"Error: The file is missing columns: {', '.join(missing)}")
156
  else:
157
  # Send Messages
158
  if st.button("Send All Messages Now"):
159
- # Create containers for displaying progress
160
- status_container = st.empty()
161
- progress_bar = st.progress(0)
162
- result_container = st.empty()
163
-
164
- status_container.info("Preparing to send messages...")
165
  successful_sends = []
166
  failed_sends = []
167
- total_rows = len(df)
168
-
169
  for index, row in df.iterrows():
170
- current_row = index + 1
171
- progress = current_row / total_rows
172
- status_container.info(f"Processing row {current_row}/{total_rows}")
173
- progress_bar.progress(progress)
174
-
175
- phone_raw = str(row["Phone Numbers"])
176
- message = str(row["Message"])
177
-
178
- if not message:
179
- failed_sends.append((phone_raw, "Empty message"))
180
  continue
181
-
182
- success, error = send_whatsapp_message(phone_raw, message)
183
-
184
- if success:
185
- successful_sends.append((phone_raw, message))
186
- else:
187
- failed_sends.append((phone_raw, error))
188
-
189
- time.sleep(1)
190
-
191
- status_container.empty()
192
- result_text = f"Completed: {len(successful_sends)} successful, {len(failed_sends)} failed"
193
-
 
 
 
 
 
 
 
 
 
 
 
 
194
  if successful_sends:
195
- result_container.success(result_text)
196
- elif failed_sends:
197
- result_container.error(result_text)
198
- else:
199
- result_container.warning("No messages were processed")
 
200
  except Exception as e:
201
  st.error(f"Error processing the file: {str(e)}")
 
202
  # Stop the virtual display when done
203
  display.stop()
 
2
  import pandas as pd
3
  import pywhatkit
4
  import time
 
 
 
5
  from pyvirtualdisplay import Display # Import PyVirtualDisplay
6
 
7
  # Initialize a virtual display (required for headless environments)
8
  display = Display(visible=0, size=(800, 600))
9
  display.start() # Start the virtual display
10
 
11
+ # Function to send WhatsApp message instantly
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  def send_whatsapp_message(phone_number, message):
13
  try:
14
  # Clean phone number to ensure proper format
15
  phone_number = str(phone_number).strip()
16
  if not phone_number.startswith('+'):
17
  phone_number = '+' + phone_number
18
+
19
  # Use pywhatkit to open WhatsApp Web with the message
20
  pywhatkit.sendwhatmsg_instantly(
21
  phone_no=phone_number,
22
  message=message,
23
  wait_time=15, # Wait time for WhatsApp Web to load
24
+ tab_close=True # Close the tab after sending the message
25
  )
26
+ time.sleep(2) # Small delay to ensure the message is sent
 
 
 
27
  return True, None
28
  except Exception as e:
29
  return False, str(e)
 
32
  st.title("WhatsApp Instant Messenger 📱")
33
  st.markdown("**Send instant WhatsApp messages to multiple recipients.**")
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  # File Upload Option
 
 
36
  uploaded_file = st.file_uploader("Upload your Excel file", type=["xls", "xlsx"])
37
  if uploaded_file:
38
  try:
39
  # Read the Excel file
40
+ df = pd.read_excel(uploaded_file, dtype={"Phone Numbers": str})
41
+
 
 
 
42
  st.success("File uploaded successfully!", icon="✅")
43
+
44
  # Validate required columns
45
+ required_columns = {"Phone Numbers", "Message", "Date"}
46
  if not required_columns.issubset(df.columns):
47
  missing = required_columns - set(df.columns)
48
  st.error(f"Error: The file is missing columns: {', '.join(missing)}")
49
  else:
50
  # Send Messages
51
  if st.button("Send All Messages Now"):
 
 
 
 
 
 
52
  successful_sends = []
53
  failed_sends = []
54
+
 
55
  for index, row in df.iterrows():
56
+ phone_raw = str(row["Phone Numbers"]).strip()
57
+ message = str(row["Message"]).strip()
58
+ date_str = str(row["Date"]).strip()
59
+
60
+ if not phone_raw or not message or not date_str:
61
+ failed_sends.append((phone_raw, "Missing data"))
 
 
 
 
62
  continue
63
+
64
+ try:
65
+ # Parse the timestamp
66
+ scheduled_time = pd.to_datetime(date_str, format="%d-%m-%Y %H:%M:%S", errors="coerce")
67
+ if pd.isna(scheduled_time):
68
+ raise ValueError("Invalid date format")
69
+
70
+ current_time = datetime.now()
71
+ delay = (scheduled_time - current_time).total_seconds()
72
+
73
+ if delay > 0:
74
+ st.write(f"Scheduling message to {phone_raw} at {scheduled_time.strftime('%d-%m-%Y %H:%M:%S')}...")
75
+ time.sleep(delay) # Wait until the scheduled time
76
+
77
+ # Send the message
78
+ success, error = send_whatsapp_message(phone_raw, message)
79
+ if success:
80
+ successful_sends.append((phone_raw, message))
81
+ else:
82
+ failed_sends.append((phone_raw, error))
83
+
84
+ except Exception as e:
85
+ failed_sends.append((phone_raw, f"Error: {str(e)}"))
86
+
87
+ # Display results
88
  if successful_sends:
89
+ st.success(f"Successfully sent {len(successful_sends)} messages.")
90
+ if failed_sends:
91
+ st.error(f"Failed to send {len(failed_sends)} messages.")
92
+ for phone, error in failed_sends:
93
+ st.write(f"To: {phone}, Error: {error}")
94
+
95
  except Exception as e:
96
  st.error(f"Error processing the file: {str(e)}")
97
+
98
  # Stop the virtual display when done
99
  display.stop()