สร้าง WhatsApp Chatbot ด้วย Python เนื่องจาก WhatsApp ไม่มี Official Bot API ใช้ Selenium ควบคุม Browser ผ่าน WhatsApp Web
ข้อกำหนดเบื้องต้น
- Python 3.6+
pip install selenium- ChromeDriver (ตรงเวอร์ชัน Chrome Browser) ดาวน์โหลด: chromedriver.chromium.org
- WhatsApp Account และ Phone เชื่อมต่อ Internet
โค้ดตัวอย่าง: ส่งข้อความไปยัง Contact/Group
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
# Setup Chrome Driver
driver = webdriver.Chrome(r'C:\path\to\chromedriver.exe') # ระบุ Path จริง
driver.get("https://web.whatsapp.com/")
# รอ QR Code Scan (Manual ครั้งแรก)
wait = WebDriverWait(driver, 600) # Wait 10 นาที
# Target: ชื่อ Contact หรือ Group (ต้องตรงกับที่แสดงใน WhatsApp Web)
target = '"My Contact Name"' # ใส่ Quote หากชื่อมี Space
# Message
message = "Hello from Python Selenium!"
# XPath สำหรับหา Contact
x_arg = f'//span[contains(@title,{target})]'
contact = wait.until(EC.presence_of_element_located((By.XPATH, x_arg)))
contact.click()
# หา Message Input Box
input_box = wait.until(EC.presence_of_element_located((
By.XPATH, '//div[@contenteditable="true"][@data-tab="10"]'
)))
input_box.send_keys(message)
# กด Enter ส่ง (หรือหา Send Button)
input_box.send_keys(Keys.ENTER)
print("Message sent!")
time.sleep(2)
driver.quit()
คำอธิบายโค้ดสำคัญ
- WebDriverWait + ExpectedConditions: รอ Element โหลดเสร็จ ไม่ใช้
time.sleep()แบบคงที่ - XPath Selector: ใช้
contains(@title, ...)หา Contact โดยชื่อ - Message Input: WhatsApp Web ใช้
div[contenteditable="true"]สำหรับ Input - Keys.ENTER: ส่งข้อความ (Alternative: Click Send Button)
รันครั้งแรก (QR Code)
- Run Script → Chrome เปิด WhatsApp Web
- โทรศัพท์: WhatsApp → Linked Devices → Link a Device
- Scan QR Code บนหน้าจอ
- Script จะดำเนินการต่ออัตโนมัติ
ข้อจำกัดและความเสี่ยง
- WhatsApp Policy: Automation ผ่าน Web 違反 Terms of Service อาจโดน Ban Account
- Selector Changes: WhatsApp Update UI บ่อย XPath อาจเสีย
- Rate Limiting: ส่งมากเกินไป → Block
- No Official API: สำหรับ Business ควรใช้ WhatsApp Business API (Official, ต้อง Apply)
ทางเลือกอื่น: WhatsApp Business API
สำหรับ Production/Business ใช้ Official API:
- Meta Business Manager → WhatsApp Business Account
- ใช้
requestsเรียก REST API - รองรับ Template Messages, Media, Interactive Buttons
- มีค่าใช้จ่ายต่อ Conversation
ไลบรารี่เสริม: pywhatkit (Simple)
pip install pywhatkit
import pywhatkit as kit
# ส่งข้อความทันที (ต้อง Login WhatsApp Web ใน Browser ก่อน)
kit.sendwhatmsg_instantly("+66XXXXXXXXX", "Hello from pywhatkit!")
# ส่งตามเวลา
kit.sendwhatmsg("+66XXXXXXXXX", "Scheduled Message", 14, 30) # 14:30
หมายเหตุ: pywhatkit ใช้ PyAutoGUI + Browser Automation คล้าย Selenium แต่ Simple กว่า