程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

使用wxauto实现AI微信聊天机器人

balukai 2025-05-30 12:42:30 文章精选 5 ℃

以下是如何使用 wxauto 结合 AI 大模型(如 GPT)实现智能微信聊天机器人的分步指南,包含详细代码和注意事项:


1. 准备工作

1.1 安装依赖库

bash

pip install wxauto openai

1.2 获取 API Key

  • 如果使用 OpenAI,需注册并获取 API Key(官网)。
  • 若使用其他模型(如本地部署的 Llama、ChatGLM),需准备对应接口。

2. 核心代码实现

python

import time

from wxauto import WeChat

import openai


# 初始化微信客户端和 AI 模型

class WeChatAIBot:

def __init__(self, api_key, model="gpt-3.5-turbo"):

self.wx = WeChat()

openai.api_key = api_key

self.model = model

self.last_msg_id = 0 # 记录最后一条消息的 ID,避免重复处理


def generate_reply(self, prompt):

try:

response = openai.ChatCompletion.create(

model=self.model,

messages=[{"role": "user", "content": prompt}]

)

return response.choices[0].message['content'].strip()

except Exception as e:

print(f"AI 生成失败: {e}")

return None


def listen_and_reply(self, interval=1):

print("开始监听微信消息...")

while True:

try:

# 获取最新消息

msgs = self.wx.GetLastMessage()

if not msgs:

time.sleep(interval)

continue


# 解析消息内容

msg_info = {

'id': msgs[0],

'sender': msgs[1],

'content': msgs[2],

'is_group': '群聊' in msgs[3] # 判断是否是群聊

}


# 仅处理新消息和非自身消息

if msg_info['id'] > self.last_msg_id and not self.wx.IsSelfMessage(msg_info['sender']):

print(f"收到消息来自 {msg_info['sender']}: {msg_info['content']}")


# 生成回复

reply = self.generate_reply(msg_info['content'])

if reply:

# 群聊消息需要 @发送者

if msg_info['is_group']:

reply = f"@{msg_info['sender'].split(' ')[0]} {reply}"


# 发送回复

self.wx.SendMsg(reply, msg_info['sender'])

print(f"已回复: {reply}")


self.last_msg_id = msg_info['id']


except Exception as e:

print(f"处理消息出错: {e}")


time.sleep(interval)


if __name__ == "__main__":

# 配置 OpenAI API Key

API_KEY = "YOUR_API_KEY"


bot = WeChatAIBot(API_KEY)

bot.listen_and_reply(interval=1) # 检查间隔设为1秒


3. 关键功能说明

  1. 消息监听

O 通过 wxautoGetLastMessage 获取最新消息,记录消息 ID 避免重复处理。

O 过滤自身消息和旧消息。

  1. AI 集成

O 使用 OpenAI GPT 生成回复,可替换为其他模型(如本地部署的模型)。

O 支持群聊自动 @ 发送者。

  1. 防封号策略

O 设置合理的 interval(建议 ≥1 秒),避免频繁操作。

O 避免发送敏感内容或广告。


4. 注意事项

  1. 微信限制

O wxauto 基于窗口自动化,需保持微信客户端前台运行。

O 长时间运行可能导致微信卡顿,建议在备用设备上运行。

  1. 模型选择

O 若需低成本,可使用本地模型(如 ChatGLM-6B、Llama 2)通过 API 部署。

O 示例替换为 Hugging Face 模型:

python

from transformers import pipeline

chatbot = pipeline("text-generation", model="facebook/opt-350m")

def generate_reply(self, prompt):

return chatbot(prompt, max_length=50)[0]['generated_text']

  1. 扩展功能

O 添加白名单/黑名单控制回复对象。

O 支持文件、图片处理(需 wxauto 高级功能)。


5. 风险提示

  • 微信官方禁止自动化工具,此代码仅用于学习,谨慎使用。
  • 建议在测试账号或小范围场景中使用,避免账号封禁。

如果需要更稳定的方案,可研究微信协议或使用企业微信 API。

最近发表
标签列表