🎁 福利:点击这里 领取火山引擎625万免费token,让你的机器人永远不会饿着!
一、项目介绍
你是否遇到过这些烦恼:
- 微信群里问题太多,回复不过来?
- 想做个机器人但是怕被封号?
- 想接入ChatGPT但是太贵又不稳定?
今天分享一个基于Python RPA技术的微信群自动回复方案,使用DeepSeek大模型,稳定性高,成本低,而且完全不会被封号!
核心特性
- 🤖 基于RPA技术,模拟真人操作
- 🔥 使用DeepSeek大模型,性能接近GPT-4
- 💪 支持群聊@自动回复
- 🚀 毫秒级响应,超强稳定性
- 🎯 支持自定义知识库(通过Dify实现)
二、实现原理
系统架构
核心流程
- 监听微信群消息
- 检测@机器人消息
- 提取问题内容
- 调用AI接口生成回答
- 模拟键盘输入回复
三、核心代码实现
消息监听与处理
def monitor_messages(self):
"""监听微信消息"""
logging.info(f"开始监听微信消息...\n机器人名称: {self.bot_name}")
last_message = None
while True:
try:
msg_info = self.get_last_message()
if msg_info and msg_info != last_message:
msg_data = self.parse_message(msg_info)
if self.is_mentioned(content):
question = self.extract_question(content)
response = self.get_ai_response(question)
self.send_message(self.target, formatted_response)
except Exception as e:
logging.error(f"监听消息时出错: {str(e)}")
Dify API调用
def call_dify_api(self, prompt):
headers = {
"Authorization": f"Bearer {self.dify_api_key}",
"Content-Type": "application/json"
}
data = {
"inputs": {},
"query": prompt,
"response_mode": "blocking",
"conversation_id": "",
"user": "abc-123"
}
response = requests.post(
self.dify_api_url,
headers=headers,
json=data,
timeout=100
)
return response.json()['answer']
四、趣味对话示例
以下是一些真实对话截图,展示机器人的实际表现,直接上效果:
五、部署说明
环境要求
- Python 3.7+
- 微信PC版
- PyOfficeRobot库
- requests库
部署步骤
- 安装依赖
pip install PyOfficeRobot requests pyperclip pywinauto
- 配置API密钥
self.api_key = "your-api-key" # DeepSeek API密钥
- 运行程序
python wechat_bot.py
六、完整代码实现
from PyOfficeRobot.core.WeChatType import WeChat
import time
import requests
import re
import traceback
import logging
import pyperclip
from pywinauto import keyboard
from datetime import datetime
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(f'wechat_bot_{datetime.now().strftime("%Y%m%d")}.log', encoding='utf-8'),
logging.StreamHandler()
]
)
class WeChatBot:
def __init__(self):
# 初始化重试配置
self.retry_count = 3
self.retry_interval = 5
# 初始化微信
self.initialize_wechat()
# 基础配置
self.bot_name = "Bot" # 机器人名称
self.target = "AI交流群" # 目标群名
self.use_dify = True # 是否使用Dify API
def initialize_wechat(self):
"""初始化微信,包含重试机制"""
for attempt in range(self.retry_count):
try:
self.wx = WeChat()
logging.info("微信初始化成功")
return
except Exception as e:
logging.error(f"微信初始化失败 (尝试 {attempt + 1}/{self.retry_count}): {str(e)}")
if attempt < self.retry_count - 1:
time.sleep(self.retry_interval)
else:
raise Exception("微信初始化失败,已达到最大重试次数")
def call_dify_api(self, prompt):
"""调用Dify API,包含重试机制"""
headers = {
"Authorization": f"Bearer {self.dify_api_key}",
"Content-Type": "application/json"
}
data = {
"inputs": {},
"query": prompt,
"response_mode": "blocking",
"conversation_id": "",
"user": "abc-123"
}
for attempt in range(self.retry_count):
try:
response = requests.post(
self.dify_api_url,
headers=headers,
json=data,
timeout=100
)
if response.status_code == 200:
return response.json()['answer']
except Exception as e:
logging.error(f"API调用出错 (尝试 {attempt + 1}/{self.retry_count}): {str(e)}")
if attempt < self.retry_count - 1:
time.sleep(self.retry_interval)
return "抱歉,当前系统繁忙,请稍后再试。"
def get_last_message(self):
"""获取最新消息,包含重试机制"""
for attempt in range(self.retry_count):
try:
return self.wx.GetLastMessage
except Exception as e:
logging.error(f"获取消息失败 (尝试 {attempt + 1}/{self.retry_count}): {str(e)}")
if attempt < self.retry_count - 1:
time.sleep(self.retry_interval)
return None
def format_response(self, user, question, content):
"""格式化回复消息"""
logging.info(f"用户: {user}\n问题: {question}\n回复: {content}")
return f"回复【{user}】问题:\n{question}\n---------------\n{content}"
def is_mentioned(self, message):
"""检查是否被@"""
return f"@{self.bot_name}" in str(message)
def extract_question(self, message):
"""提取@之后的问题内容"""
message = str(message)
pattern = f"@{self.bot_name}(.*)"
match = re.search(pattern, message)
if match:
return match.group(1).strip()
return ""
def parse_message(self, msg_info):
"""解析消息内容"""
try:
if isinstance(msg_info, tuple) and len(msg_info) >= 2:
name = msg_info[0]
content = msg_info[1]
logging.info(f"name: {name}, 内容: {content}")
return {"name": name, "content": content}
return None
except Exception as e:
logging.error(f"解析消息失败: {str(e)}")
return None
def send_message(self, name, message):
"""发送消息到指定窗口"""
try:
logging.info(f"正在发送消息到 {name}: {message}")
self.wx.ChatWith(name)
time.sleep(0.3)
pyperclip.copy(message)
keyboard.send_keys("^v")
time.sleep(0.1)
keyboard.send_keys("{ENTER}")
time.sleep(0.1)
logging.info("消息发送成功")
return True
except Exception as e:
logging.error(f"发送消息失败: {str(e)}")
return False
def monitor_messages(self):
"""监听微信消息"""
logging.info(f"开始监听微信消息...\n机器人名称: {self.bot_name}")
last_message = None
while True:
try:
msg_info = self.get_last_message()
if msg_info and msg_info != last_message:
logging.info(f"收到新消息: {msg_info}")
last_message = msg_info
msg_data = self.parse_message(msg_info)
if not msg_data:
continue
content = msg_data.get("content", "")
if self.is_mentioned(content):
question = self.extract_question(content)
if question:
response = self.call_dify_api(question)
formatted_response = self.format_response(
msg_data.get("name"),
question,
response
)
self.send_message(self.target, formatted_response)
time.sleep(1)
except Exception as e:
logging.error(f"监听消息时出错: {str(e)}")
time.sleep(self.retry_interval)
def run(self):
"""运行机器人"""
try:
self.monitor_messages()
except KeyboardInterrupt:
logging.info("程序已手动停止")
except Exception as e:
logging.error(f"程序运行出错: {str(e)}")
traceback.print_exc()
if __name__ == "__main__":
bot = WeChatBot()
bot.run()
使用说明:
- 将上述代码保存为
wechat_bot.py
- 修改以下配置:
bot_name
: 机器人名称target
: 目标群名称dify_api_key
: 您的API密钥dify_api_url
: API地址
- 运行程序即可
七、注意事项
-
使用建议
- 建议在测试群先试用
- 合理设置回复延迟
- 定期检查日志
-
常见问题
-
Q: 会被封号吗?
-
A: 不会,因为是模拟人工操作
-
Q: 响应速度如何?
-
A: 平均1-2秒内回复
-
八、未来规划
-
功能扩展
- 支持更多群管理功能
- 添加情感分析
- 支持图片识别
-
性能优化
- 引入消息队列
- 优化响应速度
- 增加并发处理
总结
本项目通过RPA技术和DeepSeek API,实现了一个稳定、高效的微信群自动回复机器人。不仅解决了群管理的痛点,还提供了一个有趣的交互方式。
希望这个项目能给大家一些启发。如果觉得有帮助,别忘了点赞收藏!
🎁 福利再提醒:点击链接,立即领取625万token,让你的机器人更智能!