最近比較閑就隨便瞎看,看到了微信防撤回就順便跟著學著實現一下
使用的是wxpy,安裝方法pip install wxpy(我使用的是python2.7),這樣實現起來比較快,反正也只是練手
首現看了兩個別人實現的代碼,然后看了看wxpy的文檔:http://wxpy.readthedocs.io/zh/latest/utils.html(萌新,順便鍛煉下看文檔)
我實現的代碼:
import wxpyimport re # 實例化微信對象bot = wxpy.Bot(cache_path=True) # 啟用puid 并指定puid所需映射數據保存的路徑bot.enable_puid(path='wxpy_puid.pkl') # 用于存放每個用戶最近發送的消息msgs = dict() # 信息的類型msg_types = { 'Text': '文本', 'Map': '位置', 'Picture': '圖片', 'Video': '視頻', 'Attachment': '文件', 'Sharing': '分享', 'Card': '名片', 'Recording': '語音',}  @bot.register()def handle_receive_msg(msg): """ 監聽消息 :param msg: 接收到的消息 :return: """ # 原信息數據 raw = msg.raw  # 如果消息的狀態碼是4 即撤回消息 if raw.get('Status') == 4:  # 如果是群消息  if isinstance(msg.chat, wxpy.api.chats.group.Group):   # 獲取群成員的puid   puid = msg.member.puid   # 獲取發送者的昵稱   name = msg.member.nick_name  # 如果是好友消息  elif isinstance(msg.chat, wxpy.api.chats.friend.Friend):   # 獲取好友的puid   puid = msg.chat.puid   # 獲取好友的昵稱   name = msg.chat.nick_name  else:   puid = None   name = None  if puid:   # 被撤回消息的msgid的匹配規則   msg_id_regex = re.compile('<msgid>(/d+)</msgid>')   # 獲取被撤回消息的msgid   old_msg_id = msg_id_regex.findall(raw.get('Content'))[0]   # 獲取該發送者的最后5次的消息記錄   chat_msgs = msgs.get(puid)   # 遍歷消息記錄   for chat_msg in chat_msgs[::-1]:    # 跳過不是被撤回的信息    if str(chat_msg.id) != old_msg_id:     continue    chat = chat_msg.chat    # 如果被撤回的信息是文本信息    if chat_msg.type == "Text":     # 如果消息長度過長 則不予處理     if len(chat_msg.text) >= 150:      warning = "【您撤回的消息過長,有炸群嫌疑,不予處理?。?!】"      bot.file_helper.send('%s撤回了一條文本消息--【%s】'.decode('utf-8') % (name, warning))      break     # 將此消息轉發出來     chat_msg.forward(chat, prefix='%s撤回了一條文本消息,消息內容為:'.decode('utf-8') % name)    # 如果被撤回的是位置信息    elif chat_msg.type == "Map":     # 位置信息的匹配規則     map_regex = re.compile(r'label="(.+?)"')     # 獲取位置信息中的位置     map = map_regex.findall(chat_msg.raw.get("OriContent"))[0]     # 將位置信息發出來     msg.reply('%s撤回了一條位置消息,位置信息為:【%s】'.decode('utf-8') % (name, map))    else:     # 獲取信息的類型     msg_type = msg_types.get(chat_msg.type).decode('utf-8')     # 將信息轉發出來     chat_msg.forward(chat, prefix='%s撤回了一條%s消息, 消息內容為:'.decode('utf-8') % (name, msg_type))    break else:  # 如果是群消息  if isinstance(msg.chat, wxpy.api.chats.group.Group):   # 獲取群成員的puid   puid = msg.member.puid  # 如果是好友消息  elif isinstance(msg.chat, wxpy.api.chats.friend.Friend):   # 獲取好友的puid   puid = msg.chat.puid  else:   puid = None  if puid:   # 記錄消息   msgs.setdefault(puid, []).append(msg)   # 截取消息 保留最大5條記錄   msgs[puid] = msg[puid][-5:] # 使機器人后臺運行,并進入交互模式wxpy.embed()            
新聞熱點
疑難解答