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()
相关推荐
叫我:松哥15 小时前
基于大数据和深度学习的智能空气质量监测与预测平台,采用Spark数据预处理,利用TensorFlow构建LSTM深度学习模型
大数据·python·深度学习·机器学习·spark·flask·lstm
吃茄子的猫21 小时前
quecpython中&的具体含义和使用场景
开发语言·python
じ☆冷颜〃1 天前
黎曼几何驱动的算法与系统设计:理论、实践与跨领域应用
笔记·python·深度学习·网络协议·算法·机器学习
数据大魔方1 天前
【期货量化实战】日内动量策略:顺势而为的短线交易法(Python源码)
开发语言·数据库·python·mysql·算法·github·程序员创富
APIshop1 天前
Python 爬虫获取 item_get_web —— 淘宝商品 SKU、详情图、券后价全流程解析
前端·爬虫·python
风送雨1 天前
FastMCP 2.0 服务端开发教学文档(下)
服务器·前端·网络·人工智能·python·ai
效率客栈老秦1 天前
Python Trae提示词开发实战(8):数据采集与清洗一体化方案让效率提升10倍
人工智能·python·ai·提示词·trae
哈里谢顿1 天前
一条 Python 语句在 C 扩展里到底怎么跑
python
才兄说1 天前
机器人租赁服务中的确定性:从客户反馈看现场支持安排
机器人
znhy_231 天前
day46打卡
python