机器人有连接到数据库,所以可以长记忆对话,多线程可以使得机器人同时和几个好友聊天。将消息发送到远程API进行处理,并回复处理后的消息。脚本还允许为每个好友分配一个唯一的随机 ID,以便跟不同的好友聊天并维护聊天记忆。
# encoding:utf-8import iofrom itchat.content import *import itchatimport threadingimport requestsimport randomimport stringimport configparser# 存储每个好友的记忆和随机 ID 的映射friend_memories = {}friend_ids = {}# 初始化配置文件config = configparser.ConfigParser()config.read('config.ini', encoding='utf-8')role_id = "001"# 机器人iddef qrCallback(uuid, status, qrcode):if status == "0":try:from PIL import Imageimg = Image.open(io.BytesIO(qrcode))_thread = threading.Thread(target=img.show, args=("QRCode",))_thread.setDaemon(True)_thread.start()except Exception as e:passimport qrcodeurl = 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)# 生成随机 IDdef generate_random_id():return ''.join(random.choices(string.ascii_letters + string.digits, k=10))# 读取用户IDdef get_user_id(username):try:user_id = config.get('UserIDs', username)return user_idexcept configparser.NoOptionError:return None# 更新用户IDdef 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.textfriend_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()# 生成新的IDupdate_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 作为 uidresponse = 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_messageprint("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()