itchat打造微信智能助手(二)消息自动回复、撤回消息监控

2019年1月27日 Jerry 7756 2019年6月22日

        itchat提供了一个简单的注册函数,可以时刻检测微信收到的各种消息(文本、音频、视频、图片、群消息、私聊消息等),可以用来包装自动回复。

def msg_register(self, msgType, isFriendChat=False, isGroupChat=False, isMpChat=False):

    raise NotImplementedError()

isFriendChat、isGroupChat、isMpChat 分别是私聊消息标记、群组消息标记和公众号消息标记。msgType消息类型有如下几种:

参数                类型
TEXT            文本
MAP             地图
CARD            名片
SHARING         分享
PICTURE         图片
RECODRDING      录音
ATTACHMENT      附件
VIDEO           视频
FRIENDS         朋友添加申请
SYSTEM          系统消息
NOTE            通知

1、自动回复私聊消息

包装以下函数,可以用于私聊消息的检测与回复:

# 检测来自私聊的文本类型、录音类型、图片类型的消息
@itchat.msg_register([TEXT, RECORDING, PICTURE], isFriendChat=True)
def reply_friend(msg):
    #print(msg, flush=True)
    global g_autoReplyFriend

    if msg['Type'] == "Text":            #文本消息,直接获取内容
        msg_content = msg['Text']
    elif msg['Type'] == "Recording" or msg['Type'] == "Picture":   #录音和图片
        msg_content = msg['FileName']
        msg['Text'](str(msg_content))    #下载文件

    if g_autoReplyFriend == True:         #回复标记位 Ture 则自动回复
        itchat.send_msg('[自动回复]: 你的消息已收到!', toUserName = msg['FromUserName'])
        logging("收到[%s]的[%s]消息[%s],已经自动回复!" %(msg['User']['NickName'], msg['Type'], msg_content))

2、自动回复群@消息

群消息的检测类似,只不过参数为 isGroupChat=True ,msg.isAt 可以判断是否@了自己:

# 检测来自群组的文本类型的消息
@itchat.msg_register(TEXT, isGroupChat=True)
def reply_group(msg):
    #print(msg, flush=True)
    global g_autoReplyGroup
    if g_autoReplyGroup == True:
        if (msg.isAt):          #只处理 @我 的消息
            msg_content = msg['Content'].split("\u2005", 1)[1] # 文字分割,获取@我 之后的消息内容
            itchat.send_msg('[自动回复]: 你的消息已收到!', toUserName = msg['FromUserName'])

3、自动添加好友

自动加好友的函数,收到的消息类型为 FRIENDS

# 检测加好友的消息通知
@itchat.msg_register([FRIENDS])
def add_friend(msg):
    #print(msg, flush=True)
    global g_autoAddFriend
    if g_autoAddFriend == True:
        itchat.add_friend(**msg['Text'])
        itchat.send_msg('你好!很高兴认识你!', msg['RecommendInfo']['UserName'])
        logging("收到[%s]添加好友请求,已经自动通过!" %msg['RecommendInfo']['NickName'])

以上代码便可以实现 自动通过好友申请,并发一条打招呼的消息。

4、消息撤回监控

       微信这个撤回消息让人有时比较头疼,尤其对强迫症患者来说。你说撤回就撤回吧,还TM的发个消息告诉我对方撤回了,我又不知道具体的内容,实在难受啊!不过有了这个itchat,便可以轻松实现一个撤回消息监控的功能。

      思路很简单,监控所有好友发来的消息(这里只实现了文本、图片、语音消息)存储起来,当好友撤回时,根据撤回的消息ID查找我们保存的消息,提取其中内容来提示用户。对之前回复私聊的函数稍加改动。直接上代码:

# 检测来自私聊的文本类型、录音类型、图片类型的消息
@itchat.msg_register([TEXT, RECORDING, PICTURE], isFriendChat=True)
def reply_friend(msg):
    #print(msg, flush=True)
    global g_autoReplyFriend

    if msg['Type'] == "Text":            #文本消息,直接获取内容
        msg_content = msg['Text']
    elif msg['Type'] == "Recording" or msg['Type'] == "Picture":   #录音和图片
        msg_content = msg['FileName']
        msg['Text'](str(msg_content))    #下载文件

    if g_autoReplyFriend == True:         #回复标记位 Ture 则自动回复
        itchat.send_msg('[自动回复]: 你的消息已收到!', toUserName = msg['FromUserName'])

    # 将信息存储在字典中,每一个msg_id对应一条信息
    msg_information.update(
    {
        msg['MsgId']: {
            "msg_type": msg["Type"],
            "msg_content": msg_content,
            }
        }
    )

    if g_autoReplyFriend == True:
        itchat.send_msg('[自动回复]: 你的消息已收到!', toUserName = msg['FromUserName'])


@itchat.msg_register([NOTE], isFriendChat=True)
def check_callback(msg):
    global g_checkIfCallback
    if g_checkIfCallback == True:
        if '撤回了一条消息' in msg['Content']:
            #在返回的content查找撤回的消息的id
            old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)  
            old_msg = msg_information.get(old_msg_id)    #得到消息

            old_msg_type = old_msg["msg_type"]
            old_msg_content =  old_msg['msg_content']

            if old_msg_type == "Text":
                msg_body = '%s,内容是[%s]' %(msg['Text'], old_msg_content)
                #把消息发送给文件传输助手
                itchat.send_msg(msg_body, toUserName='filehelper')           

            elif old_msg_type == "Recording" or old_msg_type == "Picture":
                msg_body = '%s,内容是下面这个文件' %(msg['Text'])
                itchat.send_msg(msg_body, toUserName='filehelper')
                file = '@fil@%s' % (old_msg_content)
                itchat.send(msg=file, toUserName='filehelper')       

            # 删除旧消息
            msg_information.pop(old_msg_id)

最后主函数添加以下login函数实现登陆,run函数实现消息接收,便可以实现以上所有功能。

itchat.login(enableCmdQR=1)
itchat.run()

最后上效果图:

1、自动答复:

2、自动监控消息撤回


原创文章,转载请注明出处: https://jerrycoding.com/article/wechat-tool-2

微信
jerry微信赞助
支付宝
jerry支付宝赞助

您尚未登录,暂时无法评论。请先 登录 或者 注册

0 人参与 | 0 条评论