-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChat.py
More file actions
220 lines (180 loc) · 7.86 KB
/
Copy pathChat.py
File metadata and controls
220 lines (180 loc) · 7.86 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""
WhatsApp Business API - Bulk & Single Message Sender
=====================================================
Requirements:
pip install requests
Setup:
1. Go to https://developers.facebook.com/ and create an app
2. Add WhatsApp product to your app
3. Get your ACCESS_TOKEN, PHONE_NUMBER_ID from the API setup page
4. Verify recipient numbers (in sandbox, numbers must be verified)
Usage:
python whatsapp_sender.py
"""
import requests
import json
import time
# ─────────────────────────────────────────────
# CONFIGURATION — fill these in before running
# ─────────────────────────────────────────────
ACCESS_TOKEN = "YOUR_WHATSAPP_ACCESS_TOKEN" # From Meta Developer Console
PHONE_NUMBER_ID = "YOUR_PHONE_NUMBER_ID" # From Meta Developer Console
API_VERSION = "v19.0"
API_URL = f"https://graph.facebook.com/{API_VERSION}/{PHONE_NUMBER_ID}/messages"
HEADERS = {
"Authorization": f"Bearer {ACCESS_TOKEN}",
"Content-Type": "application/json",
}
# ─────────────────────────────────────────────
# CORE FUNCTION — send a single message
# ─────────────────────────────────────────────
def send_message(to: str, message: str) -> dict:
"""
Send a WhatsApp text message to a single number.
Args:
to : Recipient phone number with country code, e.g. "919876543210"
message : Text content to send
Returns:
dict with 'success' bool and 'response' or 'error'
"""
payload = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": to,
"type": "text",
"text": {
"preview_url": False,
"body": message
}
}
try:
response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=15)
data = response.json()
if response.status_code == 200 and "messages" in data:
print(f" ✅ Sent to {to} | Message ID: {data['messages'][0]['id']}")
return {"success": True, "response": data}
else:
error_msg = data.get("error", {}).get("message", "Unknown error")
print(f" ❌ Failed to send to {to} | Error: {error_msg}")
return {"success": False, "error": error_msg}
except requests.exceptions.RequestException as e:
print(f" ❌ Network error for {to} | {str(e)}")
return {"success": False, "error": str(e)}
# ─────────────────────────────────────────────
# SINGLE MESSAGE SENDER
# ─────────────────────────────────────────────
def send_single(to: str, message: str):
"""Send a message to one recipient."""
print(f"\n📤 Sending single message to {to}...")
result = send_message(to, message)
return result
# ─────────────────────────────────────────────
# BULK MESSAGE SENDER
# ─────────────────────────────────────────────
def send_bulk(contacts: list, message: str, delay_seconds: float = 1.0):
"""
Send a message to multiple recipients.
Args:
contacts : List of phone numbers, e.g. ["919876543210", "918765432109"]
message : Text content to send
delay_seconds : Delay between each message to avoid rate limiting (default 1s)
Returns:
Summary dict with success/failure counts
"""
total = len(contacts)
success = 0
failed = 0
errors = []
print(f"\n📦 Starting bulk send to {total} contact(s)...\n{'-'*40}")
for index, number in enumerate(contacts, start=1):
print(f"[{index}/{total}] Sending to {number}...")
result = send_message(number, message)
if result["success"]:
success += 1
else:
failed += 1
errors.append({"number": number, "error": result.get("error")})
# Delay between messages to respect API rate limits
if index < total:
time.sleep(delay_seconds)
# Summary
print(f"\n{'='*40}")
print(f"📊 Bulk Send Summary")
print(f" Total : {total}")
print(f" ✅ Success: {success}")
print(f" ❌ Failed : {failed}")
if errors:
print(f"\n Failed Numbers:")
for e in errors:
print(f" - {e['number']}: {e['error']}")
print(f"{'='*40}\n")
return {"total": total, "success": success, "failed": failed, "errors": errors}
# ─────────────────────────────────────────────
# INTERACTIVE CLI
# ─────────────────────────────────────────────
def interactive_mode():
print("=" * 45)
print(" WhatsApp Business API - Message Sender")
print("=" * 45)
print(" 1. Send Single Message")
print(" 2. Send Bulk Messages")
print(" 3. Exit")
print("-" * 45)
choice = input("Select an option (1/2/3): ").strip()
if choice == "1":
to = input("Enter recipient phone (with country code, e.g. 919876543210): ").strip()
message = input("Enter your message: ").strip()
send_single(to, message)
elif choice == "2":
print("\nEnter recipient phone numbers (with country code).")
print("Type 'done' when finished.\n")
contacts = []
while True:
num = input(f" Number {len(contacts)+1}: ").strip()
if num.lower() == "done":
break
if num:
contacts.append(num)
if not contacts:
print("⚠️ No contacts entered. Exiting.")
return
message = input("\nEnter your message: ").strip()
delay = input("Delay between messages in seconds (default 1): ").strip()
delay = float(delay) if delay else 1.0
send_bulk(contacts, message, delay_seconds=delay)
elif choice == "3":
print("Goodbye!")
else:
print("⚠️ Invalid option. Please run the script again.")
# ─────────────────────────────────────────────
# EXAMPLE: Programmatic usage
# ─────────────────────────────────────────────
def example_usage():
"""
Example of how to use the functions directly in code.
Comment out interactive_mode() below and uncomment this to use.
"""
# Single message
send_single(
to="919876543210",
message="Hello! This is a single test message from WhatsApp Business API."
)
# Bulk messages
numbers = [
"919876543210",
"918765432109",
"917654321098",
]
send_bulk(
contacts=numbers,
message="Hello! This is a bulk message from WhatsApp Business API.",
delay_seconds=1.5
)
# ─────────────────────────────────────────────
# ENTRY POINT
# ─────────────────────────────────────────────
if __name__ == "__main__":
interactive_mode()
# To use programmatic mode instead, comment the line above
# and uncomment the line below:
# example_usage()