itchat监听公众号消息

cooolr 于 2021-11-13 发布
import itchat
from itchat.content import INCOME_MSG

@itchat.msg_register(INCOME_MSG, isMpChat=True)
def msg_reply(msg):
    print(msg)

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

接收公众号视频并转发到群里

# -*- coding: utf -8 -*-

import os
import re
import time
import itchat
import requests
from itchat.content import INCOME_MSG

send_chatrooms = ["蛋蛋的生活"]

def download(url):
    r = requests.get(url)
    video_url = re.findall(r'<source src="(.*?)" type="video/mp4">', r.text)[0]
    content = requests.get(video_url).content
    filename = time.strftime("%Y%m%d-%H%M%S.mp4")
    with open(filename, "wb") as f:
        f.write(content)
    return filename

def get_chatroom(nickname):
    chatrooms = itchat.get_chatrooms()
    for room in chatrooms:
        if room["NickName"] == nickname:
            return room["UserName"]

@itchat.msg_register(INCOME_MSG, isMpChat=True)
def msg_reply(msg):
    if msg["User"]["NickName"] == "创米科技":
        filename = download(msg.Url)
        f = open(filename, "rb")
        for nickname in send_chatrooms:
            toUserName = get_chatroom(nickname)
            itchat.send_file(fileDir=os.getcwd(), toUserName=toUserName, file_=f)
        f.close()

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