How to Build a WeChat Bot with PyWeChatSpy and Tuling API in Python

This guide shows how to build a WeChat bot using the PyWeChatSpy library and Tuling AI API, covering registration, API key acquisition, image folder setup, and a complete Python script that parses messages, replies to 'pats' with random images, and forwards other texts to the Tuling service for automatic responses.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
How to Build a WeChat Bot with PyWeChatSpy and Tuling API in Python

Introduction

Since the WeChat web login was disabled, the previous auto‑login reply no longer works. The following tutorial uses the PyWeChatSpy library (installable via pip) to implement a bot.

Create Bot

Visit the Tuling robot website ( http://www.tuling123.com/ ), open the Help Center, register a user, and in the robot management page create a Tuling robot (up to 5, each with its own apikey). The apikey is used for API authentication.

Complete Code

Create a folder to store reply images and place the code in the same directory. The script sets up a WeChatSpy instance, parses incoming messages, replies to “pats” with a random image and a fixed text, handles text messages, and forwards other messages to the Tuling API for automatic replies.

from PyWeChatSpy import WeChatSpy
import random
import re
import json
import requests
import time
userid = str(1)
# 1 可以替换成任何长度小于32的字符串哦
apikey = str('')
# 这里的A,记得替换成你自己的apikey~
# def robot(content):#调用机器人
#     # 图灵api
#     api = r'http://openapi.tuling123.com/openapi/api/v2'
#     # 创建post提交的数据
#     data = {
#         "perception": {
#         "inputText": {
#         "text": content
#                     }
#                 },
#         "userInfo": {
#                 "apiKey": apikey,
#                 "userId": userid,
#                 }
#     }
#     # 转化为json格式
#     jsondata = json.dumps(data)
#     # 发起post请求
#     response = requests.post(api, data = jsondata)
#     # 将返回的json数据解码
#     robot_res = json.loads(response.content)
#     # 提取对话数据
#     print(robot_res["results"][0]['values']['text'])
def my_parser(data):
    if data["type"] == 5: # 判断是微信消息数据
        for msg in data["data"]:
            if (msg["self"] == 0):
                # 遍历微信消息
                if msg["msg_type"] == 10000:  # 判断是微信拍一拍系统提示
                    m = re.search('.*?拍了拍我。', msg["content"])
                    if m:  # 判断为拍一拍
                        image_path = f"E:/images/{random.randint(1,4)}.jpg" # 随机选一张回复用的图片
                        itchat.send_file(msg["wxid1"], image_path)
                        itchat.send_text(msg["wxid1"], "我可能在学习吧(自动回复)")
                elif msg["msg_type"] == 1: #判断为文本消息
                    if (re.search('.*?@chatroom',msg["wxid1"])==None): #判断不是群消息
                        m = re.search('在吗', msg["content"])
                        if m:
                            itchat.send_text(msg["wxid1"],"我是机器人恒利,有事请留言。")
                else:
                    api = r'http://openapi.tuling123.com/openapi/api/v2'
                    # 创建post提交的数据
                    data = {
                        "perception": {
                            "inputText": {
                                "text":  msg["content"]
                            }
                        },
                        "userInfo": {
                            "apiKey": apikey,
                            "userId": userid,
                        }
                    }
                    # 转化为json格式
                    jsondata = json.dumps(data)
                    # 发起post请求
                    response = requests.post(api, data=jsondata)
                    # 将返回的json数据解码
                    robot_res = json.loads(response.content)
                    # 提取对话数据
                    print(robot_res["results"][0]['values']['text'])
                    itchat.send_text(msg["wxid1"], '['+robot_res["results"][0]['values']['text']+'(自动回复)]')
itchat = WeChatSpy(parser=my_parser)  # 实例化WeChatSpy类
if __name__ == '__main__':
    itchat.run()  # 运行代码

Effect Demonstration

Running the script logs into WeChat, listens for messages, and automatically replies according to the logic described.

图片
图片
图片
图片
图片
图片
图片
图片
backendPythonautomationWeChatBotPyWeChatSpyTuling API
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.