基于wxauto的AI微信聊天助手
立即下载
资源介绍:
基于wxauto的AI微信聊天助手
import time
from wxauto import WeChat # wxauto Version: 3.9.11.17.4
from AIUtil import ZhipuAIUtil
from Logger import LoggerClass
from datetime import datetime
"""
自动监听并用AI分析两人的对话
"""
class WeChatWindow:
def __init__(self, n=1, lens=5, api_key="55f67457af44ddaf5f53ab6dcd50b89d.KRnAjz8uOMaiJPbL", question="",
wait_for_oppo=1):
self.lens = lens
self.wx = WeChat()
self.currentWindow = []
self.msg5 = []
self.loggerClass = LoggerClass(datetime.now().date().strftime('%Y-%m-%d') + ".log")
self.aiUtil = ZhipuAIUtil(api_key=api_key)
self.wait_for_oppo = wait_for_oppo
self.question = question
self.cycle = n
self.update_current_window() # 启动时获取当前聊天记录
def update_current_window(self):
# 获取当前聊天窗口消息
msgs = self.wx.GetAllMessage(savevoice=True)
self.currentWindow = []
for msg in msgs:
if msg.type == 'friend' or msg.type == 'self':
self.currentWindow.append(msg.sender + ": " + msg.content)
self.msg5 = self.currentWindow[-self.lens:]
self.log(".\n".join(self.currentWindow))
# def chat_with(self, who): #默认监听当前窗口,不指定对象
# self.wx.ChatWith(who)
# self.update_current_window()
def print_last_messages(self):
print("=" * 100)
print("捕捉到当前5条消息: ")
for i in self.msg5:
print(i.encode('gbk', 'ignore').decode('gbk'))
print()
def print_AI_messages(self):
strs = ' '.join(self.msg5)
ans = self.aiUtil.get_answer(strs + self.question)
print("智谱AI:")
print(ans.encode('gbk', 'ignore').decode('gbk'))
def listen_for_new_messages(self):
i = 0
lastMsg5 = self.msg5
while True:
# 获取下一条新消息
msgs = self.wx.GetNextNewMessage(savevoice=True)
for msgList in msgs.values():
for item in msgList:
# if item[0] != 'SYS':
if item[0] != 'SYS' and item[1] != '[动画表情]' and item[1] != '[图片]': # 不计入表情包和图片
self.currentWindow.append(item[0] + ": " + item[1])
self.msg5 = self.currentWindow[-self.lens:]
if self.msg5 != lastMsg5:
self.log(self.currentWindow[-1])
lastMsg5 = self.msg5
self.print_last_messages()
i += 1
if i % self.cycle == 0: # 每隔cycle个消息AI分析一次
if self.wait_for_oppo == 1:
if not self.currentWindow[-1].startswith('Self'): # 只要最后一条消息不是自己的(是别人的),就调用AI回答
self.print_AI_messages()
else:
self.print_AI_messages()
time.sleep(0.5)
def log(self, msg):
self.loggerClass.log_message(msg.encode('gbk', 'ignore').decode('gbk'))
if __name__ == '__main__':
chat_window = WeChatWindow(n=1, # 每发1次监听一次
lens=5, # 监听最近5个对话
api_key="55f67457af44ddaf5f53ab6dcd50b89d.KRnAjz8uOMaiJPbL", # 连接国内大模型智谱清言密钥
question="以上是一段对话,请你站在Self的角度并且模仿Self的语气(Self是年轻人),替他回复,给出一个参考回答就可以了,请你反驳对面",
wait_for_oppo=1)
chat_window.print_last_messages()
chat_window.print_AI_messages()
chat_window.listen_for_new_messages()