python连接自己的机器人接口在微信聊天

机器人有连接到数据库,所以可以长记忆对话,多线程可以使得机器人同时和几个好友聊天。将消息发送到远程API进行处理,并回复处理后的消息。脚本还允许为每个好友分配一个唯一的随机 ID,以便跟不同的好友聊天并维护聊天记忆。

python 复制代码
# encoding:utf-8
import io
from itchat.content import *
import itchat
import threading
import requests
import random
import string
import configparser

# 存储每个好友的记忆和随机 ID 的映射
friend_memories = {}
friend_ids = {}
# 初始化配置文件
config = configparser.ConfigParser()
config.read('config.ini', encoding='utf-8')
role_id = "001"  # 机器人id


def qrCallback(uuid, status, qrcode):
    if status == "0":
        try:
            from PIL import Image

            img = Image.open(io.BytesIO(qrcode))
            _thread = threading.Thread(target=img.show, args=("QRCode",))
            _thread.setDaemon(True)
            _thread.start()
        except Exception as e:
            pass
        import qrcode
        url = f"https://login.weixin.qq.com/l/{uuid}"
        qr_api1 = "https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}".format(url)
        qr_api2 = "https://api.qrserver.com/v1/create-qr-code/?size=400×400&data={}".format(url)
        qr_api3 = "https://api.pwmqr.com/qrcode/create/?url={}".format(url)
        qr_api4 = "https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text={}".format(url)
        print("You can also scan QRCode in any website below:")
        print(qr_api3)
        print(qr_api4)
        print(qr_api2)
        print(qr_api1)
        qr = qrcode.QRCode(border=1)
        qr.add_data(url)
        qr.make(fit=True)
        qr.print_ascii(invert=True)


# 生成随机 ID
def generate_random_id():
    return ''.join(random.choices(string.ascii_letters + string.digits, k=10))


# 读取用户ID
def get_user_id(username):
    try:
        user_id = config.get('UserIDs', username)
        return user_id
    except configparser.NoOptionError:
        return None


# 更新用户ID
def update_user_id(username, user_id):
    config.set('UserIDs', username, user_id)
    with open('config.ini', 'w') as configfile:
        config.write(configfile)


# 处理消息的函数
def process_message(msg):
    user_text = msg.text
    friend_name = msg.user.nickName  # 使用好友的昵称作为标识
    print(friend_name)
    # 初始化好友的记忆和随机 ID,如果没有的话
    if friend_name not in friend_memories:
        friend_memories[friend_name] = ""
        friend_id = get_user_id(friend_name)
        if friend_id is None:
            friend_id = generate_random_id()  # 生成新的ID
            update_user_id(friend_name, friend_id)  # 保存到配置文件
        friend_ids[friend_name] = friend_id  # 将好友昵称和对应的ID关联起来
        print(f"{friend_name} 的用户ID是:{friend_ids[friend_name]}")

    print(f"Processing message from {friend_name} (ID: {friend_ids[friend_name]}): {user_text}")
    api_url = "http://xxxxxx:8080/ask"
    data = {'content': user_text, 'role_id': role_id, 'uid': friend_ids[friend_name]}  # 使用好友的随机 ID 作为 uid
    response = requests.post(api_url, data=data)
    print(data)
    if response.status_code == 200:
        # 从API获取聊天响应
        chat_response = response.json().get('data', [])
        send_message = " ".join(chat_response)  # 将聊天响应连接成一个字符串

        # 更新好友的记忆
        friend_memories[friend_name] = send_message
        print("friend_memories:", friend_memories)
        # 自动回复给发送消息的用户
        msg.user.send(send_message)
        print(f"Reply to {friend_name} (ID: {friend_ids[friend_name]}): {send_message}")
    else:
        print(f"Error processing message from {friend_name} (ID: {friend_ids[friend_name]})")


# 处理接收消息的函数
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    # 使用线程处理消息
    thread = threading.Thread(target=process_message, args=(msg,))
    thread.start()


if __name__ == "__main__":
    itchat.auto_login(hotReload=True)
    itchat.run()
相关推荐
这里有鱼汤9 分钟前
熟练掌握MACD这8种形态,让你少走三年弯路(附Python量化代码)| 建议收藏
后端·python
404.Not Found17 分钟前
Day46 Python打卡训练营
开发语言·python
love530love19 分钟前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm
运维开发王义杰26 分钟前
Python: 告别 ModuleNotFoundError, 解决 pipx 环境下 sshuttle 缺少 pydivert 依赖的终极指南
开发语言·python
DanCheng-studio1 小时前
毕设 基于机器视觉的驾驶疲劳检测系统(源码+论文)
python·毕业设计·毕设
carpell1 小时前
【语义分割专栏】3:Segnet实战篇(附上完整可运行的代码pytorch)
人工智能·python·深度学习·计算机视觉·语义分割
一只小波波呀2 小时前
打卡第48天
python
zstar-_2 小时前
一套个人知识储备库构建方案
python
Amo Xiang2 小时前
《100天精通Python——基础篇 2025 第5天:巩固核心知识,选择题实战演练基础语法》
python·选择题·基础语法
江梦寻2 小时前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式