欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python微信撤回监测代码

程序员文章站 2023-11-16 14:27:04
 本文实例为大家分享了python微信撤回的监测代码,供大家参考,具体内容如下 注意:这里用了一个wechat库,当然,wechat库是基于微信提供的官方接口实...

 本文实例为大家分享了python微信撤回的监测代码,供大家参考,具体内容如下

注意:这里用了一个wechat库,当然,wechat库是基于微信提供的官方接口实现的。

这里的核心就是通过网页登陆微信的方式,然后获取各个通讯信息,然后存进内存,最后检测各种微信的操作,最后写入微信里面的文件传输助手即可。

直接看代码,然后运行,慢慢调试几次,就明白咋回事了。

#coding=utf8
import itchat
import requests
import time
import os
import re
import threading

#全局变量,对于每个用户的机器人开关
user_bot_control_flag = {}
#全局变量,我的昵称
mynickname = ''

def bot_chat_init():
  # 获取好友列表
  friends = itchat.get_friends(update=true)[0:]
  #将标志位置为0
  for i in friends[1:]:
    user_bot_control_flag[i["username"]] = 0


@itchat.msg_register(itchat.content.text)
def tuling_reply(msg):
  #  获取到发送消息者身份,如果身份匹配,就做对应的事
  # itchat.send_msg('已经收到了文本消息,消息内容为%s' % msg['text'], tousername=msg['fromusername'])
  # 如果图灵key出现问题,那么reply将会是none
  if msg['text']=='service crond start':
    return u'你一看就是个程序员'
  if msg['text'] == 'dididididi':
    return u'开车了'
  reply = get_response(msg['text'])
  if not msg['fromusername'] == myusername:
    pass
    # 发送一条提示给文件助手
    # itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" %
    #         (time.strftime("%y-%m-%d %h:%m:%s", time.localtime(msg['createtime'])),
    #         msg['user']['nickname'],
    #         msg['text']), 'filehelper')
  # a or b的意思是,如果a有内容,那么返回a,否则返回b
  # 有内容一般就是指非空或者非none,你可以用`if a: print('true')`来测试
  return reply or u'[自动回复]您好,我现在有事不在,一会再和您联系。\n已经收到您的的信息:%s\n' % (msg['text'])


def friend():
  # 初始化计数器,有男有女,当然,有些人是不填的
  # 获取好友列表
  friends = itchat.get_friends(update=true)[0:]
  male = female = other = 0

  # 遍历这个列表,列表里第一位是自己,所以从"自己"之后开始计算
  # 1表示男性,2女性
  for i in friends[1:]:
    print (i)      #打印出签名
    sex = i["sex"]
    if sex == 1:
      male += 1
    elif sex == 2:
      female += 1
    else:
      other += 1
  # 总数算上,好计算比例啊~
  total = len(friends[1:])
  # 好了,打印结果
  print(u"共有好友:%d" % total)
  print (u"男性好友:%.2f%%" % (float(male) / total * 100))
  print (u"女性好友:%.2f%%" % (float(female) / total * 100))
  print (u"其他:%.2f%%" % (float(other) / total * 100))

def get_response(msg):
  # 这里我们就像在“3. 实现最简单的与图灵机器人的交互”中做的一样
  # 构造了要发送给服务器的数据
  apiurl = 'http://www.tuling123.com/openapi/api'
  data = {
    'key'  : key,
    'info'  : msg,
    'userid' : 'wechat-robot',
  }
  try:
    r = requests.post(apiurl, data=data).json()
    # 字典的get方法在字典没有'text'值的时候会返回none而不会抛出异常
    return r.get('text')+'----来自机器人小z的智能回复----'
  # 为了防止服务器没有正常响应导致程序异常退出,这里用try-except捕获了异常
  # 如果服务器没能正常交互(返回非json或无法连接),那么就会进入下面的return
  except:
    # 将会返回一个none
    return


@itchat.msg_register(itchat.content.text, isgroupchat=true) #msg['actualnickname'] 群里发消息的人名 #msg['user']['nickname'] 群名称
def text_reply(msg):
  # print (msg['user'])    #一个宏大的结构体
  # print ("群聊名字"+msg['user']['nickname']) #群聊名称
  # print (msg['fromusername'])
  #监控所有群的消息,后来做统计用,后面可以做关键词分析什么的
  file_object = open(mynickname+"群"+msg['user']['nickname'], 'a')
  write_data = ''.join(time.strftime("%y-%m-%d %h:%m:%s" , time.localtime(msg['createtime'])))+" "+msg['actualnickname']+": "+msg['text']+"\n"
  file_object.write(write_data)
  file_object.close()
  #指定群聊可以智能群聊
  if msg['user']['nickname'] == '184':
    print (" 184 ok")
    itchat.send(get_response(msg['text']),msg['fromusername'])
  #监控群聊内容发送到文件助手,已经被自己屏蔽掉了
  # itchat.send_msg(u"[%s]收到%s群 %s 的信息:%s\n" %
  #         (time.strftime("%y-%m-%d %h:%m:%s", time.localtime(msg['createtime']))
  #         ,msg['user']['nickname'],msg['actualnickname'],
  #         msg['text']), 'filehelper')
  # 判断是否有人@自己
  if (msg.isat):
   # 如果有人@自己,就发一个消息告诉对方我已经收到了信息
    itchat.send_msg("我已经收到了来自{0}的消息,实际内容为{1}".format(msg['actualnickname'], msg['text']),
      tousername=msg['fromusername'])

# def sendmsgtopsh():
#   while (true):
#     pass
#     # print ("123456")
#
# threads = []
# t1 = threading.thread(target=sendmsgtopsh())


# 说明:可以撤回的有文本文字、语音、视频、图片、位置、名片、分享、附件

# {msg_id:(msg_from,msg_to,msg_time,msg_time_rec,msg_type,msg_content,msg_share_url)}
msg_dict = {}

# 文件存储临时目录
rev_tmp_dir = "/home/seen/pycharmprojects/code"
if not os.path.exists(rev_tmp_dir): os.mkdir(rev_tmp_dir)

# 表情有一个问题 | 接受信息和接受note的msg_id不一致 巧合解决方案
face_bug = none


# # 将接收到的消息存放在字典中,当接收到新消息时对字典中超时的消息进行清理 | 不接受不具有撤回功能的信息
# # [text, picture, map, card, sharing, recording, attachment, video, friends, note]
# @itchat.msg_register([itchat.content.text, itchat.content.picture, itchat.content.map, itchat.content.card, itchat.content.sharing,
#            itchat.content.recording,itchat.content. attachment, itchat.content.video],isgroupchat=true)
# def handler_receive_msg(msg):
#   #回复特定用户消息
#   # if msg['user']['nickname']=='yyyyy' or msg['user']['nickname']=='彭芊芊':
#   #   print ("yhj ok")
#   #   itchat.send_msg(get_response(msg['text']), tousername=msg['fromusername'])
#   # 先获取对方说来的话
#   # 下面一行是获取发送消息者昵称
#   send_user_name = itchat.search_friends(username=msg['fromusername'])['nickname']
#   file_object = open(mynickname + "&" + msg['user']['nickname'], 'a')
#   write_data = ''.join(time.strftime("%y-%m-%d %h:%m:%s", time.localtime(msg['createtime']))) + " " + \
#         send_user_name + ": " + msg['text'] + "\n"
#   file_object.write(write_data)
#   file_object.close()
#
#   #控制指令检测模块
#   if msg['text'] == 'service robot start':
#     user_bot_control_flag[msg['fromusername']]=1   #检测到开启指令后开启机器人
#     itchat.send_msg("robot small z started...waiting for your service", tousername=msg['fromusername'])
#   if msg['text'] == 'service robot stop':
#     user_bot_control_flag[msg['fromusername']]=0   #检测到开启指令后关闭机器人
#     itchat.send_msg("robot small z stoped...get 'service robot start' restarted", tousername=msg['fromusername'])
#   #在开关开启的情况下回复对方对话
#   if not msg['fromusername'] == myusername:
#     if user_bot_control_flag[msg['fromusername']]:
#       # 存储单人对话模块
#       # 下面一行是获取发送消息者昵称
#       reply = get_response(msg['text'])
#       file_object = open(mynickname + "&" + msg['user']['nickname'], 'a')
#       write_data = ''.join(time.strftime("%y-%m-%d %h:%m:%s", time.localtime(msg['createtime']))) + " " + \
#             mynickname + ": " + reply + "\n"
#       file_object.write(write_data)
#       file_object.close()
#       itchat.send_msg(reply, tousername=msg['fromusername'])
#
#   global face_bug
#   # 获取的是本地时间戳并格式化本地时间戳 e: 2017-04-21 21:30:08
#   msg_time_rec = time.strftime("%y-%m-%d %h:%m:%s", time.localtime())
#   # 消息id
#   msg_id = msg['msgid']
#   # 消息时间
#   msg_time = msg['createtime']
#   # 消息发送人昵称 | 这里也可以使用remarkname备注 但是自己或者没有备注的人为none
#   msg_from = (itchat.search_friends(username=msg['fromusername']))["nickname"]
#   # 消息内容
#   msg_content = none
#   # 分享的链接
#   msg_share_url = none
#   if msg['type'] == 'text' \
#       or msg['type'] == 'friends':
#     msg_content = msg['text']
#   elif msg['type'] == 'recording' \
#       or msg['type'] == 'attachment' \
#       or msg['type'] == 'video' \
#       or msg['type'] == 'picture':
#     msg_content = r"" + msg['filename']
#     # 保存文件
#     msg['text'](rev_tmp_dir + msg['filename'])
#   elif msg['type'] == 'card':
#     msg_content = msg['recommendinfo']['nickname'] + r" 的名片"
#   elif msg['type'] == 'map':
#     x, y, location = re.search(
#       "<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['oricontent']).group(1, 2, 3)
#     if location is none:
#       msg_content = r"纬度->" + x.__str__() + " 经度->" + y.__str__()
#     else:
#       msg_content = r"" + location
#   elif msg['type'] == 'sharing':
#     msg_content = msg['text']
#     msg_share_url = msg['url']
#   face_bug = msg_content
#   # 更新字典
#   msg_dict.update(
#     {
#       msg_id: {
#         "msg_from": msg_from, "msg_time": msg_time, "msg_time_rec": msg_time_rec,
#         "msg_type": msg["type"],
#         "msg_content": msg_content, "msg_share_url": msg_share_url
#       }
#     }
#   )

# 将接收到的消息存放在字典中,当接收到新消息时对字典中超时的消息进行清理 | 不接受不具有撤回功能的信息
# [text, picture, map, card, sharing, recording, attachment, video, friends, note]
@itchat.msg_register([itchat.content.text, itchat.content.picture, itchat.content.map, itchat.content.card, itchat.content.sharing,
           itchat.content.recording,itchat.content. attachment, itchat.content.video])
def handler_receive_msg(msg):
  #回复特定用户消息
  # if msg['user']['nickname']=='yyyyy' or msg['user']['nickname']=='彭芊芊':
  #   print ("yhj ok")
  #   itchat.send_msg(get_response(msg['text']), tousername=msg['fromusername'])
  # 先获取对方说来的话
  # 下面一行是获取发送消息者昵称
  send_user_name = itchat.search_friends(username=msg['fromusername'])['nickname']
  file_object = open(mynickname + "&" + msg['user']['nickname'], 'a')
  write_data = ''.join(time.strftime("%y-%m-%d %h:%m:%s", time.localtime(msg['createtime']))) + " " + \
         send_user_name + ": " + msg['text'] + "\n"
  file_object.write(write_data)
  file_object.close()

  #控制指令检测模块
  if msg['text'] == 'service robot start':
    user_bot_control_flag[msg['fromusername']]=1   #检测到开启指令后开启机器人
    itchat.send_msg("robot small z started...waiting for your service", tousername=msg['fromusername'])
  if msg['text'] == 'service robot stop':
    user_bot_control_flag[msg['fromusername']]=0   #检测到开启指令后关闭机器人
    itchat.send_msg("robot small z stoped...get 'service robot start' restarted", tousername=msg['fromusername'])
  #在开关开启的情况下回复对方对话
  if not msg['fromusername'] == myusername:
    if user_bot_control_flag[msg['fromusername']]:
      # 存储单人对话模块
      # 下面一行是获取发送消息者昵称
      reply = get_response(msg['text'])
      file_object = open(mynickname + "&" + msg['user']['nickname'], 'a')
      write_data = ''.join(time.strftime("%y-%m-%d %h:%m:%s", time.localtime(msg['createtime']))) + " " + \
             mynickname + ": " + reply + "\n"
      file_object.write(write_data)
      file_object.close()
      itchat.send_msg(reply, tousername=msg['fromusername'])

  global face_bug
  # 获取的是本地时间戳并格式化本地时间戳 e: 2017-04-21 21:30:08
  msg_time_rec = time.strftime("%y-%m-%d %h:%m:%s", time.localtime())
  # 消息id
  msg_id = msg['msgid']
  # 消息时间
  msg_time = msg['createtime']
  # 消息发送人昵称 | 这里也可以使用remarkname备注 但是自己或者没有备注的人为none
  msg_from = (itchat.search_friends(username=msg['fromusername']))["nickname"]
  # 消息内容
  msg_content = none
  # 分享的链接
  msg_share_url = none
  if msg['type'] == 'text' \
      or msg['type'] == 'friends':
    msg_content = msg['text']
  elif msg['type'] == 'recording' \
      or msg['type'] == 'attachment' \
      or msg['type'] == 'video' \
      or msg['type'] == 'picture':
    msg_content = r"" + msg['filename']
    # 保存文件
    msg['text'](rev_tmp_dir + msg['filename'])
  elif msg['type'] == 'card':
    msg_content = msg['recommendinfo']['nickname'] + r" 的名片"
  elif msg['type'] == 'map':
    x, y, location = re.search(
      "<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['oricontent']).group(1, 2, 3)
    if location is none:
      msg_content = r"纬度->" + x.__str__() + " 经度->" + y.__str__()
    else:
      msg_content = r"" + location
  elif msg['type'] == 'sharing':
    msg_content = msg['text']
    msg_share_url = msg['url']
  face_bug = msg_content
  # 更新字典
  msg_dict.update(
    {
      msg_id: {
        "msg_from": msg_from, "msg_time": msg_time, "msg_time_rec": msg_time_rec,
        "msg_type": msg["type"],
        "msg_content": msg_content, "msg_share_url": msg_share_url
      }
    }
  )


# # 收到note通知类消息,判断是不是撤回并进行相应操作,针对于群
# @itchat.msg_register([itchat.content.note],isgroupchat=true)
# def send_msg_helper(msg):
#   global face_bug
#   if re.search(r"\<\!\[cdata\[.*撤回了一条消息\]\]\>", msg['content']) is not none:
#     # 获取消息的id
#     old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['content']).group(1)
#     old_msg = msg_dict.get(old_msg_id, {})
#     if len(old_msg_id) < 11:
#       itchat.send_file(rev_tmp_dir + face_bug, tousername='filehelper')
#       os.remove(rev_tmp_dir + face_bug)
#     else:
#       msg_body = "告诉你一个秘密~" + "\n" \
#            + old_msg.get('msg_from') + " 撤回了 " + old_msg.get("msg_type") + " 消息" + "\n" \
#            + old_msg.get('msg_time_rec') + "\n" \
#            + "撤回了什么 ⇣" + "\n" \
#            + r"" + old_msg.get('msg_content')
#       # 如果是分享存在链接
#       if old_msg['msg_type'] == "sharing": msg_body += "\n就是这个链接➣ " + old_msg.get('msg_share_url')
#
#       # 将撤回消息发送到文件助手
#       itchat.send(msg_body, tousername='filehelper')
#       # 有文件的话也要将文件发送回去
#       if old_msg["msg_type"] == "picture" \
#           or old_msg["msg_type"] == "recording" \
#           or old_msg["msg_type"] == "video" \
#           or old_msg["msg_type"] == "attachment":
#         file = '@fil@%s' % (rev_tmp_dir + old_msg['msg_content'])
#         itchat.send(msg=file, tousername='filehelper')
#         os.remove(rev_tmp_dir + old_msg['msg_content'])
#       # 删除字典旧消息
#       msg_dict.pop(old_msg_id)

# 收到note通知类消息,判断是不是撤回并进行相应操作
@itchat.msg_register([itchat.content.note])
def send_msg_helper(msg):
  global face_bug
  if re.search(r"\<\!\[cdata\[.*撤回了一条消息\]\]\>", msg['content']) is not none:
    # 获取消息的id
    old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['content']).group(1)
    old_msg = msg_dict.get(old_msg_id, {})
    if len(old_msg_id) < 11:
      itchat.send_file(rev_tmp_dir + face_bug, tousername='filehelper')
      os.remove(rev_tmp_dir + face_bug)
    else:
      msg_body = "告诉你一个秘密~" + "\n" \
            + old_msg.get('msg_from') + " 撤回了 " + old_msg.get("msg_type") + " 消息" + "\n" \
            + old_msg.get('msg_time_rec') + "\n" \
            + "撤回了什么 ⇣" + "\n" \
            + r"" + old_msg.get('msg_content')
      # 如果是分享存在链接
      if old_msg['msg_type'] == "sharing": msg_body += "\n就是这个链接➣ " + old_msg.get('msg_share_url')

      # 将撤回消息发送到文件助手
      itchat.send(msg_body, tousername='filehelper')
      # 有文件的话也要将文件发送回去
      if old_msg["msg_type"] == "picture" \
          or old_msg["msg_type"] == "recording" \
          or old_msg["msg_type"] == "video" \
          or old_msg["msg_type"] == "attachment":
        file = '@fil@%s' % (rev_tmp_dir + old_msg['msg_content'])
        itchat.send(msg=file, tousername='filehelper')
        os.remove(rev_tmp_dir + old_msg['msg_content'])
      # 删除字典旧消息
      msg_dict.pop(old_msg_id)




key = '02dd1dd1b5594e179aa4aca9a6a690a6'
if __name__ == '__main__':
  itchat.auto_login(hotreload=true)
  # 获取自己的username
  mynickname = itchat.get_friends(update=true)[0]["nickname"]
  myusername = itchat.get_friends(update=true)[0]["username"]
  #做函数功能的实验
  # print (itchat.search_friends(name='彭芊芊')[0]['username'])    #我居然会用了这种办法我是真的猛
  # print(type(itchat.search_friends(name='彭芊芊')))
  #itchat.send("init messages to dindsong,a message from bangbangtang,distant areas...", tousername='@509f2668d9380a6aeb1951585256827dc1d475c2de885b62fae401401d522f9b')
  friend()     #获取朋友信息

  bot_chat_init()  #初始化开关模块
  itchat.run()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。