WhatsApp không cung cấp API chính thức cho bot cá nhân. Cách phổ biến: tự động hóa WhatsApp Web qua Selenium WebDriver.
Yêu cầu
- Python 3.6+
pip install selenium- ChromeDriver (phù hợp version Chrome) hoặc GeckoDriver (Firefox).
- Tài khoản WhatsApp trên điện thoại.
Cài đặt ChromeDriver
- Kiểm tra version Chrome:
chrome://version/ - Tải ChromeDriver tương ứng:
https://chromedriver.chromium.org/downloads - Đặt trong PATH hoặc chỉ định đường dẫn tuyệt đối.
- Mở Chrome -> web.whatsapp.com.
- Điện thoại: WhatsApp -> Linked Devices -> Link a Device -> Quét QR code trên màn hình.
- Script tìm contact, click, gõ tin nhắn, gửi.
- Selector XPath/CSS có thể thay đổi khi WhatsApp cập nhật UI. Cần kiểm tra và cập nhật.
- Rủi ro ban account: WhatsApp phát hiện automation -> khóa tài khoản. Chỉ dùng cho mục đích cá nhân, test, giới hạn tần suất.
- Đợi QR code: WebDriverWait 600s cho phép thời gian quét QR.
- Headless mode: WhatsApp Web không hoạt động tốt ở headless do detect bot.
Code gửi tin nhắn tự động
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import sys
# Khởi động Chrome
driver = webdriver.Chrome(r'C:\path\to\chromedriver.exe')
driver.get("https://web.whatsapp.com/")
# Đợi quét QR code (tối đa 600s)
wait = WebDriverWait(driver, 600)
# Tên contact/nhóm (CHÍNH XÁC như hiển thị)
target = '"Contact Name"'
# Tin nhắn từ command line argument
message = sys.argv[1] if len(sys.argv) > 1 else "Hello from Python!"
# XPath tìm span chứa title
x_arg = f'//span[contains(@title, {target})]'
group_title = wait.until(EC.presence_of_element_located((By.XPATH, x_arg)))
group_title.click()
# Ô nhập tin nhắn (selector có thể thay đổi theo phiên bản WhatsApp Web)
msg_box = driver.find_element(By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]')
msg_box.send_keys(message)
# Nút gửi
send_btn = driver.find_element(By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[2]/button')
send_btn.click()
print("Message sent!")
time.sleep(2)
driver.quit()
Chạy
python whatsapp_bot.py "Chào bạn, tin nhắn tự động!"
Quy trình
Lưu ý quan trọng
Alternatives (Thay thế an toàn hơn)
| Giải pháp | Mô tả |
|---|---|
| WhatsApp Business API | Chính thức, cho doanh nghiệp, cần duyệt. |
| Twilio API for WhatsApp | Dễ tích hợp, trả phí theo tin nhắn. |
| Waha / WhatsApp Web API (self-hosted) | Open source, chạy server riêng, vẫn dùng Web protocol. |
Kết luận
Selenium + WhatsApp Web là cách nhanh cho cá nhân/test, nhưng không khuyến nghị cho production do rủi ro ban và UI thay đổi thường xuyên. Doanh nghiệp nên dùng Business API.