ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

使用 Python 来自动回微信

2022-04-30 10:34:50  阅读:213  来源: 互联网

标签:itchat Python db re 自动 msg import pymongo 回微信


准备

  • Python3
  • Python Itchat库(可以通过pip install itchat来安装)
  • (可选)Python Pymongo库(可以通过pip install pymongo来安装)
  • (可选)MongoDB(请自行百度)
    那现在开始吧!

引入库

代码:

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

其中:

  • import pymongo请根据自己的情况导入
  • re(正则表达式)库用于剔除多余的AI表情字符(如{face:14}这种)
  • 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()

程序效果


数据库里:

(此为部分数据)

标签:itchat,Python,db,re,自动,msg,import,pymongo,回微信
来源: https://www.cnblogs.com/WindowsRegedit/p/16209529.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有