Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

62 lignes
2.7KB

  1. from bridge.context import ContextType
  2. from channel.chat_message import ChatMessage
  3. from common.log import logger
  4. from common.tmp_dir import TmpDir
  5. from lib import itchat
  6. from lib.itchat.content import *
  7. class WeChatMessage(ChatMessage):
  8. def __init__(self, itchat_msg, is_group=False):
  9. super().__init__(itchat_msg)
  10. self.msg_id = itchat_msg["MsgId"]
  11. self.create_time = itchat_msg["CreateTime"]
  12. self.is_group = is_group
  13. if itchat_msg["Type"] == TEXT:
  14. self.ctype = ContextType.TEXT
  15. self.content = itchat_msg["Text"]
  16. elif itchat_msg["Type"] == VOICE:
  17. self.ctype = ContextType.VOICE
  18. self.content = TmpDir().path() + itchat_msg["FileName"] # content直接存临时目录路径
  19. self._prepare_fn = lambda: itchat_msg.download(self.content)
  20. elif itchat_msg["Type"] == PICTURE and itchat_msg["MsgType"] == 3:
  21. self.ctype = ContextType.IMAGE
  22. self.content = TmpDir().path() + itchat_msg["FileName"] # content直接存临时目录路径
  23. self._prepare_fn = lambda: itchat_msg.download(self.content)
  24. else:
  25. raise NotImplementedError(
  26. "Unsupported message type: {}".format(itchat_msg["Type"])
  27. )
  28. self.from_user_id = itchat_msg["FromUserName"]
  29. self.to_user_id = itchat_msg["ToUserName"]
  30. user_id = itchat.instance.storageClass.userName
  31. nickname = itchat.instance.storageClass.nickName
  32. # 虽然from_user_id和to_user_id用的少,但是为了保持一致性,还是要填充一下
  33. # 以下很繁琐,一句话总结:能填的都填了。
  34. if self.from_user_id == user_id:
  35. self.from_user_nickname = nickname
  36. if self.to_user_id == user_id:
  37. self.to_user_nickname = nickname
  38. try: # 陌生人时候, 'User'字段可能不存在
  39. self.other_user_id = itchat_msg["User"]["UserName"]
  40. self.other_user_nickname = itchat_msg["User"]["NickName"]
  41. if self.other_user_id == self.from_user_id:
  42. self.from_user_nickname = self.other_user_nickname
  43. if self.other_user_id == self.to_user_id:
  44. self.to_user_nickname = self.other_user_nickname
  45. except KeyError as e: # 处理偶尔没有对方信息的情况
  46. logger.warn("[WX]get other_user_id failed: " + str(e))
  47. if self.from_user_id == user_id:
  48. self.other_user_id = self.to_user_id
  49. else:
  50. self.other_user_id = self.from_user_id
  51. if self.is_group:
  52. self.is_at = itchat_msg["IsAt"]
  53. self.actual_user_id = itchat_msg["ActualUserName"]
  54. self.actual_user_nickname = itchat_msg["ActualNickName"]