Build a WeChat Smart Chatbot in 16 Lines of Python – Step‑by‑Step Guide
This article shows how to create a WeChat intelligent chatbot using only 16 lines of Python code, covering installation of required libraries, obtaining a Turing API key, implementing message handling, and running the bot with automatic login and a persistent loop.
Effect
After logging in with my own WeChat account, the chatbot takes over the conversation and responds intelligently, as demonstrated in the screenshots below.
Project Idea
The overall architecture consists of a WeChat client (ItChat) that receives messages, forwards them to the Turing chatbot API, and returns the reply to the user.
Code Analysis
1. Install and import modules
The project relies on the itchat and requests libraries. Install them via pip install itchat requests and import them in the script.
import itchat</code><code>import requests2. Apply for a Turing chatbot
Register on the Turing website, create a robot, and obtain its unique API key. The free version requires real‑name verification and allows up to 100 messages per day.
3. Implement the chatbot function
Define a function that sends the user’s message to the Turing API and returns the reply.
def get_response(msg):
apiUrl = "http://www.tuling123.com/openapi/api"
data = {'key': KEY, 'info': msg, 'userid': "WeChat-robot"}
r = requests.post(apiUrl, data=data)
return r["text"]4. Implement the WeChat message handler
Use the @itchat.msg_register(itchat.content.TEXT) decorator to capture incoming text messages, call the chatbot function, and send the reply back.
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(user_data):
print(user_data) # raw message data
user_msg = user_data["Text"]
reply = get_response(user_msg)
print(reply)
return reply or user_msg5. QR code login and run loop
When the program starts, it displays a QR code for WeChat login and then keeps running to handle messages continuously.
itchat.auto_login() # scan QR code to log in
itchat.run() # keep the program aliveThe complete solution consists of fewer than 20 lines of code and provides a functional WeChat intelligent chatbot.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
