使用 Python 实现自动回微信

Python 投稿 59700 3 评论

使用 Python 实现自动回微信

准备

  • Python3

  • Python Itchat库(可以通过来安装)

  • (可选)Python Pymongo库(可以通过来安装)

  • (可选)MongoDB(请自行百度)

引入库

代码:

import re
import itchat
import pymongo
import requests
from urllib.parse import quote

其中:

  • 请根据自己的情况导入

  • re(正则表达式)库用于剔除多余的AI表情字符(如这种)

  • itchat 库用于发微信

  • pymongo 库用于将接收的数据保存到数据库

  • requests 库用于获取AI通话的内容

  • urllib.parse.quote 用于将聊天的内容转换成URL

主函数

s = requests.Session()
msg_url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg={message}"
client = pymongo.MongoClient('localhost', 27017)
db = client['wechat']
collection = db['wechat']
@itchat.msg_register(itchat.content.TEXT)
def _(msg):
    print(msg)
    collection.insert_one(msg)
    if msg.toUserName == "filehelper":
        r = s.get(msg_url.format(message=quote(msg['Text'])))
        print(r.json())
        msg.user.send(re.sub('\{.*?\}', '', r.json()["content"]))

itchat.auto_login(hotReload=True)
itchat.run()

其中:

  • 定义client, db, collection的请根据自己的情况取舍

  • 其余代码请自行消化

全部代码

import re
import itchat
import pymongo
import requests
from urllib.parse import quote

s = requests.Session()
msg_url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg={message}"
client = pymongo.MongoClient('localhost', 27017)
db = client['wechat']
collection = db['wechat']
@itchat.msg_register(itchat.content.TEXT)
def _(msg):
    print(msg)
    collection.insert_one(msg)
    if msg.toUserName == "filehelper":
        r = s.get(msg_url.format(message=quote(msg['Text'])))
        print(r.json())
        msg.user.send(re.sub('\{.*?\}', '', r.json()["content"]))

itchat.auto_login(hotReload=True)
itchat.run()

程序效果

数据库里:
(此为部分数据)

编程笔记 » 使用 Python 实现自动回微信

赞同 (53) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(3)个小伙伴在吐槽
  1. 成绩真是让人惊叹!继续保持努力。
    神秘使者 2023-09-14 18:30 (1年前) 回复
  2. 让人可以产生共鸣。
    黄昏歌手 2023-09-13 13:00 (1年前) 回复
  3. 能够有效地与团队成员协作。
    病态美丽 2023-09-10 10:30 (2年前) 回复