You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 satır
2.7KB

  1. from bridge.context import ContextType
  2. from channel.chat_message import ChatMessage
  3. from common.tmp_dir import TmpDir
  4. from common.log import logger
  5. from lib.itchat.content import *
  6. from lib import itchat
  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("Unsupported message type: {}".format(itchat_msg['Type']))
  26. self.from_user_id = itchat_msg['FromUserName']
  27. self.to_user_id = itchat_msg['ToUserName']
  28. user_id = itchat.instance.storageClass.userName
  29. nickname = itchat.instance.storageClass.nickName
  30. # 虽然from_user_id和to_user_id用的少,但是为了保持一致性,还是要填充一下
  31. # 以下很繁琐,一句话总结:能填的都填了。
  32. if self.from_user_id == user_id:
  33. self.from_user_nickname = nickname
  34. if self.to_user_id == user_id:
  35. self.to_user_nickname = nickname
  36. try: # 陌生人时候, 'User'字段可能不存在
  37. self.other_user_id = itchat_msg['User']['UserName']
  38. self.other_user_nickname = itchat_msg['User']['NickName']
  39. if self.other_user_id == self.from_user_id:
  40. self.from_user_nickname = self.other_user_nickname
  41. if self.other_user_id == self.to_user_id:
  42. self.to_user_nickname = self.other_user_nickname
  43. except KeyError as e: # 处理偶尔没有对方信息的情况
  44. logger.warn("[WX]get other_user_id failed: " + str(e))
  45. if self.from_user_id == user_id:
  46. self.other_user_id = self.to_user_id
  47. else:
  48. self.other_user_id = self.from_user_id
  49. if self.is_group:
  50. self.is_at = itchat_msg['IsAt']
  51. self.actual_user_id = itchat_msg['ActualUserName']
  52. self.actual_user_nickname = itchat_msg['ActualNickName']