Create a 24/7 Raspberry Pi WeChat Bot with Python: Auto‑Reply, AI Chat & Camera

Learn how to turn a Raspberry Pi 4B into a continuously running WeChat robot using Python and the itchat library, covering automatic replies, AI‑powered chat via an online API, scheduled weather broadcasts, camera photo capture, and video calls with linphone, complete with full source code.

Java Baker
Java Baker
Java Baker
Create a 24/7 Raspberry Pi WeChat Bot with Python: Auto‑Reply, AI Chat & Camera

Background

The author owns a Raspberry Pi 4B (8 GB version) and, besides writing Java and architecture articles, has been experimenting with various fun projects on the Pi. This article starts a new series on practical Raspberry Pi projects for readers.

Raspberry Pi is a credit‑card‑sized single‑board computer with an ARM CPU that can run a Linux server 24/7 and connect to various peripherals, enabling many creative applications.

Requirements

Imagine having a WeChat robot that can auto‑reply, provide AI chat, send scheduled weather forecasts, and control a camera. Using Raspberry Pi together with the open‑source itchat library fulfills all these needs, as the Pi can stay online continuously and act as a persistent server.

Note: This article is for learning purposes only and must not be used for commercial or other unauthorized uses.

Itchat Overview

Itchat is an open‑source interface for personal WeChat accounts. With fewer than thirty lines of code you can build a robot that handles all messages. Repository: https://github.com/littlecodersh/ItChat

Essentially, itchat works as a web client for WeChat, implementing the web protocol via HTTP.

Feature Implementation

1. Auto‑Reply

Register message handlers for different message types (text, image, voice, video, friend requests, etc.) using itchat’s decorator syntax, similar to Java annotations.

For text messages, keywords can trigger specific logic. The demo below shows registration and handling of various message types.

import itchat, time
from itchat.content import *

# Register handler for text, map, card, note, sharing messages
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    itchat.send('%s: %s' % (msg.type, msg.text))
    if '你好' in msg.text:
        itchat.send('你好啊')
    elif '拜拜' in msg.text:
        itchat.send('下次聊')

# Register handler for media messages to download files
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    msg.download(msg.fileName)
    typeSymbol = {PICTURE: 'img', VIDEO: 'vid'}.get(msg.type, 'fil')
    return '@%s@%s' % (typeSymbol, msg.fileName)

# Register handler for friend requests
@itchat.msg_register(FRIENDS)
def add_friend(msg):
    msg.user.verify()
    msg.user.send('Nice to meet you!')

# Group chat handling (only reply when @mentioned)
@itchat.msg_register(TEXT, isGroupChat=True)
def group_text_reply(msg):
    if msg.isAt:
        msg.user.send(u'@%s I received: %s' % (msg.actualNickName, msg.text))

itchat.auto_login(True)
itchat.run(True)

2. AI Chat

Integrate an online AI API (e.g., Qingyunke) to provide chatbot responses. The API returns a JSON object; the content field is extracted and line‑break placeholders are replaced.

# Call API for AI chat, single text parameter
def ai_chat(msg):
    url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s' % msg
    response = requests.get(url)
    return response.json()["content"].replace('{br}', '
')

3. Scheduled Weather Forecast

Use the APScheduler library to schedule a daily weather report. The report is fetched via the AI chat function with a weather query (e.g., "上海天气"). The bot then searches for a specific group chat and sends the message.

from apscheduler.schedulers.blocking import BlockingScheduler

def weather_report():
    msg = ai_chat('上海天气')
    itchat.get_chatrooms(update=True)
    chatrooms = itchat.search_chatrooms(name='<replace with actual group name>')
    chatroom = itchat.update_chatroom(chatrooms[0]['UserName'])
    itchat.send_msg(msg=msg, toUserName=chatroom['UserName'])

if __name__ == '__main__':
    itchat.auto_login(hotReload=True)
    itchat.run(blockThread=False)
    scheduler = BlockingScheduler()
    scheduler.add_job(weather_report, 'cron', day_of_week='*', hour=9, minute=0, second=0)
    scheduler.start()

4. Camera Control (Photo & Video)

The Pi’s USB ports can connect a webcam. For photos, the fswebcam utility is used; for video calls, the linphone SIP client is employed.

Photo Capture

Install fswebcam and capture an image, then send it via WeChat.

# Capture photo with fswebcam and send to filehelper
img_file = '%d.jpg' % timestamp
os.system('fswebcam %s' % img_file)
itchat.send_image(img_file, toUserName='filehelper')

Video Call

Install linphone (or an older stable version) on the Pi and use its command‑line interface to initiate and terminate video calls, triggered by WeChat commands.

# Exit any running linphone instance, then start
os.system('linphonecsh exit; linphonecsh init -V -c .linphonerc')
time.sleep(1)
# Make a video call via linphone CLI
os.system('linphonecsh generic "call <replace with actual linphone account>"')

Full Code

The complete script, including additional features such as workout and sleep punch‑card logging, is available on GitHub: https://github.com/topcoding/wechat_robot.

# -*- coding: utf-8 -*-
import itchat, sqlite3, os, time, requests
from apscheduler.schedulers.blocking import BlockingScheduler

PUNCH_TYPE_WORKOUT = 1
PUNCH_TYPE_SLEEP = 2
ai_chat_switch = True
AI_CHATROOM_WHITELIST = ['<replace with actual group name>']

# ... (functions save_db, text_reply, group_reply, ai_chat, weather_report as shown above) ...

if __name__ == '__main__':
    itchat.auto_login(hotReload=True)
    itchat.run(blockThread=False)
    scheduler = BlockingScheduler()
    scheduler.add_job(weather_report, 'cron', day_of_week='*', hour=9, minute=0, second=0)
    scheduler.start()

More Examples

Refer to the itchat tutorial documentation for additional usage patterns: https://github.com/littlecodersh/ItChat/tree/master/docs/tutorial

Pythonraspberry-piitchatAI chatWeChat botlinphone
Java Baker
Written by

Java Baker

Java architect and Raspberry Pi enthusiast, dedicated to writing high-quality technical articles; the same name is used across major platforms.

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.