跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
PythonWeChatAI

微信 AI 群聊机器人本地搭建教程

介绍如何使用 Python 和 wxauto 库在本地搭建微信 AI 群聊机器人。步骤包括申请百度千帆大模型 API Key,配置 Access Token,编写代码实现群消息监听、商品管理(增删查)、自动回复及定时问候功能。通过调用 ERNIE-Lite 模型处理自然语言指令,支持管理员与群聊隔离监控,适用于社群自动化管理与客户服务场景。

CoderByte发布于 2026/3/24更新于 2026/5/2022 浏览
微信 AI 群聊机器人本地搭建教程

微信 AI 机器人是基于人工智能技术的自动化服务系统,具备自然语言处理能力,可理解用户输入并给出响应或执行任务。它能提供 24 小时实时服务,节省搜索时间,提高社群管理效率。

一、申请 API Key

  1. 访问千帆大模型官网,在模型广场搜索 ERNIE-Lite(免费),点击体验。

文章配图

  1. 点击应用接入,填入必填项,点击创建(需实名认证)。

文章配图

文章配图

  1. 获取 API Key 和 Secret Key。

文章配图

二、代码实现

注:运行代码前请登录 PC 端微信,否则可能运行失败。

完整代码

import requests
import json
import csv
import os
import schedule
import time
from wxauto import WeChat

class WeChatBot:
    def __init__(self):
        self.wx = WeChat()
        self.list_name = [
            '徐长卿', # 机器人账号添加管理员的备注,ros 为机器人,ros 给管理员的备注就应为徐长卿,可进行修改
            '嘻嘻嘻', # 被监控群聊名称
            'AAA 刘哥百货超市',
            '小超市'
        ]
        # 为每个群聊添加监听
        for group in self.list_name:
            self.wx.AddListenChat(who=group, savepic=True)

    def get_access_token(self):
        """使用 API Key,Secret Key 获取 access_token"""
        url = "https://aip.bce.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用 API Key]&client_secret=[应用 Secret Key]"
        payload = json.dumps("")
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        response = requests.post(url, headers=headers, data=payload)
        if response.status_code == 200:
            return response.json().get("access_token")
        else:
            print("Failed to get access token:", response.text)
            return None

    def call_ai_model(self, content):
        """调用大模型接口并返回结果"""
        access_token = self.get_access_token()
        if access_token:
            url = f"https://aip.bce.baidu.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-lite-8k?access_token={access_token}"
            payload = json.dumps({
                "messages": [
                    { "role": "user", "content": content }
                ]
            })
            headers = {
                'Content-Type': 'application/json'
            }
            response = requests.post(url, headers=headers, data=payload)
            if response.status_code == 200:
                return response.json().get('result')
            else:
                print("Failed to get response from chat API:", response.text)
                return None
        else:
            print("Access token is None, cannot proceed with chat API request.")
            return None

    def send_morning_wishes(self):
        """发送早安祝福消息"""
        good_morning_message = "老板生成一段祝福群友的早安祝福"
        ai_reply = self.call_ai_model(good_morning_message)
        if ai_reply:
            for group in self.list_name:
                self.wx.SendMsg(msg=ai_reply, who=group)

    def send_evening_greetings(self):
        """发送晚上好的消息"""
        evening_greetings = "老板生成一段祝福群友的晚上好祝福"
        for group in self.list_name:
            self.wx.SendMsg(msg=evening_greetings, who=group)

    def listen_messages(self):
        wait = 1 # 设置 1 秒查看一次是否有新消息
        while True:
            msgs = self.wx.GetListenMessage()
            for chat, messages in msgs.items():
                who = chat.who # 获取聊天窗口名(群名)
                if who in self.list_name:
                    for msg in messages:
                        msg_type = msg.type
                        content = msg.content
                        print(f'【{who}】:{content}')
                        sender = msg.sender
                        
                        if who != self.list_name[0]:
                            if content.startswith('购买'):
                                try:
                                    parts = content.split('购买')[1].strip()
                                    commodity_name, quantity = parts.split(' ', 1)
                                    if self.is_commodity_exists(commodity_name):
                                        reply = f"{sender},已为您将{commodity_name}{quantity}添加至订单中,感谢您的支持"
                                        self.save_to_csv_order(sender, commodity_name, quantity)
                                        self.wx.SendMsg(msg=reply, who=who)
                                    else:
                                        reply = f"{sender},该商品小店尚未出售"
                                        self.wx.SendMsg(msg=reply, who=who)
                                except ValueError:
                                    reply = f"{sender},输入格式错误,请按照'购买 商品名称 购买数量'的格式输入。"
                                    self.wx.SendMsg(msg=reply, who=who)
                            elif content.startswith('查询'):
                                parts = content.split('查询')[1].strip()
                                if parts:
                                    commodity_name = parts
                                    if self.is_commodity_exists(commodity_name):
                                        price_info = self.get_price_info(commodity_name)
                                        reply = f"{sender},{commodity_name} {price_info}"
                                    else:
                                        reply = f"{sender},该商品小店尚未出售"
                                        self.wx.SendMsg(msg=reply, who=who)
                            if content.startswith('老板'):
                                ai_reply = self.call_ai_model(content[2:])
                                if ai_reply:
                                    self.wx.SendMsg(msg=ai_reply, who=who)
                        elif who == self.list_name[0]:
                            if content.startswith('转发'):
                                new_content = content[2:].strip()
                                self.forward_message(new_content)
                            if content.startswith('增加'):
                                try:
                                    parts = content.split('增加')[1].strip()
                                    if parts:
                                        commodity_name, price_info = parts.split(' ', 1)
                                        if self.is_commodity_exists(commodity_name):
                                            reply = f"{sender},{commodity_name}已经存在。"
                                        else:
                                            reply = f"{sender},{commodity_name}增加成功。"
                                            self.save_to_csv(commodity_name, price_info)
                                            self.wx.SendMsg(msg=reply, who=who)
                                except ValueError:
                                    reply = f"{sender},输入格式错误,请按照'增加 商品名称 价格信息'的格式输入。"
                                    self.wx.SendMsg(msg=reply, who=who)
                            elif content.startswith('删除'):
                                commodity_name = content.split('删除')[1].strip()
                                if self.delete_commodity_from_csv(commodity_name):
                                    reply = f"{sender},{commodity_name}删除成功。"
                                else:
                                    reply = f"{sender},{commodity_name}不存在。"
                                self.wx.SendMsg(msg=reply, who=who)
            schedule.run_pending()
            time.sleep(wait)

    def forward_message(self, content):
        """将消息转发到所有监控的群聊"""
        for group in self.list_name:
            if group != self.list_name[0]:
                self.wx.SendMsg(msg=content, who=group)

    def save_to_csv_order(self, username, commodity_name, quantity):
        with open('order.csv', 'a', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow([username, commodity_name, quantity])
            print(f"订单 '{commodity_name}' 已添加到 order.csv")

    def get_price_info(self, commodity_name):
        with open('commodity.csv', 'r', encoding='utf-8') as file:
            reader = csv.reader(file)
            for row in reader:
                if row and row[0] == commodity_name:
                    return row[1]
        return "未知价格"

    def save_to_csv(self, commodity_name, price_info):
        with open('commodity.csv', 'a', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow([commodity_name, price_info])
            print(f"商品 '{commodity_name}' 已添加到 commodity.csv")

    def is_commodity_exists(self, commodity_name):
        if not os.path.exists('commodity.csv'):
            return False
        with open('commodity.csv', 'r', encoding='utf-8') as file:
            reader = csv.reader(file)
            for row in reader:
                if row and row[0] == commodity_name:
                    return True
        return False

    def delete_commodity_from_csv(self, commodity_name):
        lines = []
        found = False
        with open('commodity.csv', 'r', encoding='utf-8') as file:
            reader = csv.reader(file)
            for row in reader:
                if row and row[0] != commodity_name:
                    lines.append(row)
                elif row:
                    found = True
        with open('commodity.csv', 'w', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerows(lines)
        return found

    def start(self):
        schedule.every().day.at("08:30").do(self.send_morning_wishes)
        schedule.every().day.at("19:30").do(self.send_evening_greetings)
        self.listen_messages()

if __name__ == "__main__":
    bot = WeChatBot()
    bot.start()

代码说明

  1. __init__ 函数中第一个元素为管理员,其他可为群聊或个人用户。
  2. get_access_token 函数中需替换 URL 中的 [应用 API Key] 和 [应用 Secret Key],注意删除方括号且不要留空格。
  3. 程序通过 wxauto 库对微信进行实时监控,支持管理员和需要管理的群聊互不干扰,可并行检查多个群聊。可根据需求自行设置时间发送早安、晚安祝福。wxauto 库开源,建议配合官方文档查看修改。

上述功能旨在实现自动化管理,正常使用不会导致微信封号。

目录

  1. 一、申请 API Key
  2. 二、代码实现
  3. 完整代码
  4. 代码说明
  • 💰 8折买阿里云服务器限时8折了解详情
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • Linux Shell 与脚本基础实战指南
  • DeepSeek、豆包、Kimi 三大模型命理测算实测与避坑
  • AI 辅助编程:需求对齐模式提升代码准确率
  • Llama-2-7b 在昇腾 NPU 上的六大核心场景性能基准报告
  • WorkBuddy 桌面智能体安装与实战指南
  • C++ 模板编程基础:泛型编程入门与实践
  • 垂直微调大模型与通用大模型在情感场景下的能力对比分析
  • Coze 构建 AI 应用:从智能体开发到 Web 部署实战
  • BaseCTF Week3 Web 与 Misc 解题思路
  • Node.js 下载安装与环境配置全流程
  • Java 包装类与泛型核心解析
  • AI 时代初级开发者的创意生存指南:数据与创新的边界
  • OpenClaw 本地部署及 cpolar 公网访问实战
  • OpenClaw 接入飞书机器人配置指南
  • Claude Skills 功能特性与使用指南
  • MATLAB 实现基于多目标粒子群算法(MOPSO)的无人机三维路径规划
  • Microsoft 365 Copilot Chat 与 Microsoft 365 Copilot 详细对比
  • Python 爬虫入门:构建简单数据抓取程序
  • 工作多年想转行编程游戏开发:现状分析与学习路径
  • VR 如何为 AI 伦理决策注入人性压力

相关免费在线工具

  • RSA密钥对生成器

    生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online

  • Mermaid 预览与可视化编辑

    基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online

  • 随机西班牙地址生成器

    随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online

  • curl 转代码

    解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online