基于ChatGpt实现的微信回复机器人

# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: [email protected]
@file: test.py
@time: 2023/7/10 20:21
@desc:

"""
import re
import json
import requests
from datetime import datetime
from wcferry import Wcf


class ChatBotSelf():

    def get_user_status(self, user_map, user_id):
        """

        :param user_map:
        :param user_id:
        :return:0:正常接收,1:不回复,2:重新开始回复
        """
        if user_map.get(user_id) is None:
            user_map[user_id] = 0
        return user_map.get(user_id)

    def set_user_status(self, user_map, user_id, status):
        """

        :param user_map:
        :param user_id:
        :param status:0:正常回复,1:不回复
        :return:
        """
        user_map[user_id] = status

    def get_result(self, args):
        """
        获取回复内容
        :param args:
        :return:
        """
        headers = {
            "authority": "api.binjie.fun",
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/json",
            "dnt": "1",
            "origin": "https://chat.jinshutuan.com",
            "pragma": "no-cache",
            "referer": "https://chat.jinshutuan.com/",
            "sec-ch-ua": "\"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not:A-Brand\";v=\"99\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "cross-site",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
        }
        url = "https://api.binjie.fun/api/generateStream"

        data = {
            "prompt": "{}".format(args),
            "userId": "#/chat/1683173371474",
            "network": True,
            "system": "",
            "withoutContext": True,
            "stream": True
        }
        data = json.dumps(data, separators=(',', ':'))
        try:
            response = requests.post(
                url, headers=headers, data=data, timeout=10)
            response.encoding = "utf-8"
            if response.status_code == 200:
                return response.text
        except BaseException:
            return "查询失败"

    def get_friends_map(self, wcf):
        """
        获取微信所有联系人,群信息
        :param wcf:
        :return:
        """
        friends_map = {}
        friends_list = wcf.get_contacts()
        for args in friends_list:
            name = args["name"]
            remark = args["remark"]
            wxid = args["wxid"]
            friends_map[wxid] = "{} ({})".format(name, remark)
        return friends_map

    def get_sender_msg(self, msg):
        """
        解析收到的消息
        :param msg:
        :return:
        """
        print(msg)
        wx_id_sender = re.findall("(.*?)\\[\\]\\:", msg)[0]
        print("wx_id_sender", wx_id_sender)
        wx_id_msg = re.findall("msgsource>\n(.*)", msg)[0]
        print("wx_id_msg", wx_id_msg)
        return wx_id_sender, wx_id_msg

    def recode_info(self, history_map, wx_id, question, answer):
        """
        记录历史信息
        :param history_map:
        :param wx_id:
        :param msg:
        :return:
        """
        max_chat = 10
        if history_map.get(wx_id) is not None:
            if len(history_map[wx_id]) >= max_chat:
                history_map[wx_id].pop(0)
            history_map[wx_id].append(
                self._recode_info_get_args(
                    question, answer))
        else:
            history_map[wx_id] = [self._recode_info_get_args(question, answer)]
        print(history_map)
        return history_map

    def _recode_info_get_args(self, question, answer):
        """

        :param question:
        :param answer:
        :return:
        """
        return {
            "question": question,
            "answer": answer,
            "times": 1,
            "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }

    def process(self):
        """

        :return:
        """
        wcf = Wcf()
        # wcf.is_login()

        friends_map = self.get_friends_map(wcf)
        history_map = {}
        user_map = {}
        recv_status = wcf.enable_receiving_msg()
        while recv_status:
            while not wcf.msgQ.qsize():
                continue
            msg = str(wcf.get_msg())
            wx_id_sender, wx_id_msg = self.get_sender_msg(msg)

            status = self.get_user_status(user_map, wx_id_sender)
            # 清空历史记录
            if wx_id_msg == "#reset":
                wcf.send_text("历史记录已清理", wx_id_sender)
                history_map[wx_id_sender].clear()
            # 暂停回复
            elif wx_id_msg == "#stop":
                self.set_user_status(user_map, wx_id_sender, 1)
                wcf.send_text("已暂停回复", wx_id_sender)
            # 终止服务
            elif wx_id_msg == "#kill":
                wcf.send_text("服务已终止", wx_id_sender)
                wcf.disable_recv_msg()
                break
            # 重新开启回复
            elif wx_id_msg == "#restart":
                self.set_user_status(user_map, wx_id_sender, 0)
                wcf.send_text("已重启回复", wx_id_sender)
                history_map = {}
            # 获取近十条历史记录
            elif wx_id_msg == "#history":
                wcf.send_text("近十条问答:{}".format(history_map), wx_id_sender)
            # 正常回复
            else:
                if status == 0:
                    answer = self.get_result(wx_id_msg)
                    history_map = self.recode_info(
                        history_map, wx_id_sender, wx_id_msg, answer)
                    wcf.send_text("您好,{}\n"
                                  "【下面是问题:[ {} ]的回复】\n"
                                  "{}".format(friends_map.get(wx_id_sender), wx_id_msg, answer), wx_id_sender)


if __name__ == '__main__':
    cbs = ChatBotSelf()
    cbs.process()

你可能感兴趣的:(无用良品,chatgpt,微信,机器人)