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


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

    1. # encoding:utf-8
    2. import io
    3. from itchat.content import *
    4. import itchat
    5. import threading
    6. import requests
    7. import random
    8. import string
    9. import configparser
    10. # 存储每个好友的记忆和随机 ID 的映射
    11. friend_memories = {}
    12. friend_ids = {}
    13. # 初始化配置文件
    14. config = configparser.ConfigParser()
    15. config.read('config.ini', encoding='utf-8')
    16. role_id = "001" # 机器人id
    17. def qrCallback(uuid, status, qrcode):
    18. if status == "0":
    19. try:
    20. from PIL import Image
    21. img = Image.open(io.BytesIO(qrcode))
    22. _thread = threading.Thread(target=img.show, args=("QRCode",))
    23. _thread.setDaemon(True)
    24. _thread.start()
    25. except Exception as e:
    26. pass
    27. import qrcode
    28. url = f"https://login.weixin.qq.com/l/{uuid}"
    29. qr_api1 = "https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}".format(url)
    30. qr_api2 = "https://api.qrserver.com/v1/create-qr-code/?size=400×400&data={}".format(url)
    31. qr_api3 = "https://api.pwmqr.com/qrcode/create/?url={}".format(url)
    32. qr_api4 = "https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text={}".format(url)
    33. print("You can also scan QRCode in any website below:")
    34. print(qr_api3)
    35. print(qr_api4)
    36. print(qr_api2)
    37. print(qr_api1)
    38. qr = qrcode.QRCode(border=1)
    39. qr.add_data(url)
    40. qr.make(fit=True)
    41. qr.print_ascii(invert=True)
    42. # 生成随机 ID
    43. def generate_random_id():
    44. return ''.join(random.choices(string.ascii_letters + string.digits, k=10))
    45. # 读取用户ID
    46. def get_user_id(username):
    47. try:
    48. user_id = config.get('UserIDs', username)
    49. return user_id
    50. except configparser.NoOptionError:
    51. return None
    52. # 更新用户ID
    53. def update_user_id(username, user_id):
    54. config.set('UserIDs', username, user_id)
    55. with open('config.ini', 'w') as configfile:
    56. config.write(configfile)
    57. # 处理消息的函数
    58. def process_message(msg):
    59. user_text = msg.text
    60. friend_name = msg.user.nickName # 使用好友的昵称作为标识
    61. print(friend_name)
    62. # 初始化好友的记忆和随机 ID,如果没有的话
    63. if friend_name not in friend_memories:
    64. friend_memories[friend_name] = ""
    65. friend_id = get_user_id(friend_name)
    66. if friend_id is None:
    67. friend_id = generate_random_id() # 生成新的ID
    68. update_user_id(friend_name, friend_id) # 保存到配置文件
    69. friend_ids[friend_name] = friend_id # 将好友昵称和对应的ID关联起来
    70. print(f"{friend_name} 的用户ID是:{friend_ids[friend_name]}")
    71. print(f"Processing message from {friend_name} (ID: {friend_ids[friend_name]}): {user_text}")
    72. api_url = "http://xxxxxx:8080/ask"
    73. data = {'content': user_text, 'role_id': role_id, 'uid': friend_ids[friend_name]} # 使用好友的随机 ID 作为 uid
    74. response = requests.post(api_url, data=data)
    75. print(data)
    76. if response.status_code == 200:
    77. # 从API获取聊天响应
    78. chat_response = response.json().get('data', [])
    79. send_message = " ".join(chat_response) # 将聊天响应连接成一个字符串
    80. # 更新好友的记忆
    81. friend_memories[friend_name] = send_message
    82. print("friend_memories:", friend_memories)
    83. # 自动回复给发送消息的用户
    84. msg.user.send(send_message)
    85. print(f"Reply to {friend_name} (ID: {friend_ids[friend_name]}): {send_message}")
    86. else:
    87. print(f"Error processing message from {friend_name} (ID: {friend_ids[friend_name]})")
    88. # 处理接收消息的函数
    89. @itchat.msg_register(itchat.content.TEXT)
    90. def text_reply(msg):
    91. # 使用线程处理消息
    92. thread = threading.Thread(target=process_message, args=(msg,))
    93. thread.start()
    94. if __name__ == "__main__":
    95. itchat.auto_login(hotReload=True)
    96. itchat.run()

  • 相关阅读:
    npm更换成淘宝镜像源及cnpm使用
    LVGL基础教程 – LVGL 简介
    【AGC】巧用团队帐号功能让未实名帐号也能登录AGC
    std::function
    05-Zookeeper典型使用场景实战
    【虹科案例】基于3D相机组装家具
    15-弹性盒模型
    树莓派交叉编译之带有wiringpi库的交叉编译,以及软硬链接的建立(面试)
    导数差分近似公式总结
    华为云DevCloud平台部署bootdo博客论坛实战【开发者专属集市】
  • 原文地址:https://blog.csdn.net/weixin_44740756/article/details/132686850