Build a Flexible WeChat Group Chatbot with Python, GUI, and Timed Messaging

This article walks through creating a configurable WeChat group chatbot using Python's itchat library, featuring toggleable auto-replies via CSV files, custom keyword responses, timed group messages, and a wxPython GUI, with detailed code explanations, multithreading design, and deployment tips for cloud servers.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Build a Flexible WeChat Group Chatbot with Python, GUI, and Timed Messaging

Preface

A friend asked for a configurable WeChat group chatbot; I used the itchat library and built a prototype in one night.

Program screenshot on the computer:

Phone display of the chatbot:

Although many simple itchat bots exist, this program offers several distinctive features:

Toggleable auto-reply for specific groups by editing group.csv.

Custom keyword replies configurable via keyword.csv using the {keyword,reply} format.

Timed group messages with dynamic modification of time and content.

A GUI built with wxPython that follows WeChat's minimalist design.

DIY Usage

1. For merchants

Merchants can schedule messages, e.g., "Reply xxx to get yyy", by pre‑writing entries in keyword.csv . This lets group members obtain what they need without manual typing, supporting multiple groups simultaneously.

2. For personal use

Send scheduled good‑night wishes to a partner, parents, or friends.

3. Deploy to Alibaba Cloud

Running the bot continuously requires the computer to stay on; deploying to a cloud server solves this. See my previous article for the deployment process and a link to an Alibaba Cloud discount page. Build a mini‑QQ from LAN to Internet Alibaba Cloud discount link: https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=otrai1l4

Detailed Code Design

1. Architecture

Because a GUI is introduced, both the GUI thread and the message‑sending thread are blocking. The GUI runs on the main thread, while the sending logic runs in a child thread. Communication between threads uses wxPython’s wx.lib.pubsub module; the child thread calls wx.CallAfter(pub.sendMessage) to update the GUI without freezing.

2. Process

The program loads configuration files to determine which groups have auto‑reply enabled and which keyword‑reply pairs are active. These settings cannot be changed at runtime.

def load_keyword(self):
    global keywords
    with open('keyword.csv', 'r', encoding='utf-8', newline=) as f:
        reader = csv.reader(f)
        for i, line in enumerate(reader):
            if i == 0:
                continue
            keywords[line[0]] = line[1]

The keywords dictionary is made global for easy access, and the first CSV row (header) is skipped.

The main group‑message handling code is as follows (comments omitted for brevity):

@itchat.msg_register(TEXT, isGroupChat=True)

def group_text(msg):
    global keywords
    groups = itchat.get_chatrooms(update=True)
    for group in groups:
        if group['NickName'] in group_names:
            group_id = msg['FromUserName']
            if not group_id == group['UserName']:
                break
            keys = keywords.keys()
            key = ''
            for i in keys:
                if i in msg['Text']:
                    key = i
                    break
            if key == '':
                return
            message = keywords.get(key)
            sender_id = msg['ActualUserName']
            group_info = itchat.update_chatroom(group_id, detailedMember=True)
            memberlist = group_info['MemberList']
            for member in memberlist:
                if member['UserName'] == sender_id:
                    to_user = member['RemarkName']
                    if len(to_user) == 0:
                        to_user = member['DisplayName']
                    if len(to_user) == 0:
                        to_user = member['NickName']
                    itchat.send_msg('@{}
{}'.format(to_user, message), group['UserName'])
                    wx.CallAfter(pub.sendMessage, "update", msg="Reply group [{}] member [{}] success:[{}]".format(group['NickName'], to_user, message))

The timed‑sending logic runs in a separate thread that starts a threading.Timer to trigger the callback after minutes * 60 seconds. The callback re‑creates the timer, achieving periodic execution without memory leaks.

def run(self):
    global t
    t = threading.Timer(minutes * 60, self.auto_timer)
    t.start()
    self.load_keyword()
    self.load_group()
    itchat.auto_login(hotReload=True)
    itchat.run()
def auto_timer(self):
    global auto_message
    groups = itchat.get_chatrooms(update=True)
    for group in groups:
        if group['NickName'] in group_names:
            itchat.send_msg('{}'.format(auto_message), group['UserName'])
            wx.CallAfter(pub.sendMessage, "update", msg="Group [{}] timed message:[{}] sent successfully".format(group['NickName'], auto_message))
    global t
    t = threading.Timer(minutes * 60, self.auto_timer)
    t.start()

The GUI portion of the code is omitted for brevity.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GUIPythonmultithreadingChatbotitchat
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

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.