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.

165 line
7.4KB

  1. import threading
  2. from common import kafka_helper,redis_helper,utils
  3. import json,time,re,random,os
  4. from common.log import logger, log_exception
  5. from wechat import gewe_chat
  6. def wx_messages_process_callback(agent_tel,message):
  7. try:
  8. # print(f'手机号 {agent_tel}')
  9. wxchat = gewe_chat.wxchat
  10. msg_content = message
  11. cleaned_content = clean_json_string(msg_content)
  12. content = json.loads(cleaned_content)
  13. data = content.get("data", {})
  14. msg_type_data = data.get("msg_type", None)
  15. content_data = data.get("content", {})
  16. agent_tel = content_data.get("agent_tel", None)
  17. if msg_type_data == 'group-sending':
  18. process_group_sending(wxchat, content_data, agent_tel)
  19. except json.JSONDecodeError as e:
  20. print(f"JSON解码错误: {e}, 消息内容: {message}")
  21. except Exception as e:
  22. print(f"处理消息时发生错误: {e}, 消息内容: {message}")
  23. def process_group_sending(wxchat:gewe_chat.GeWeChatCom, content_data, agent_tel:str):
  24. # 获取登录信息
  25. hash_key = f"__AI_OPS_WX__:LOGININFO:{agent_tel}"
  26. logininfo = redis_helper.redis_helper.get_hash(hash_key)
  27. if not logininfo:
  28. logger.warning(f"未找到 {agent_tel} 的登录信息")
  29. return
  30. token_id = logininfo.get('tokenId')
  31. app_id = logininfo.get('appId')
  32. agent_wxid = logininfo.get('wxid')
  33. # 获取联系人列表并计算交集
  34. # contacts_list = wxchat.fetch_contacts_list(token_id, app_id)
  35. # contacts_list = wxchat.fetch_contacts_list(token_id, app_id)
  36. # friend_wxids = contacts_list['friends']
  37. hash_key = f"__AI_OPS_WX__:CONTACTS_BRIEF:{agent_wxid}"
  38. friend_wxids_str=redis_helper.redis_helper.get_hash_field(hash_key,"data")
  39. friend_wxids_list=json.loads(friend_wxids_str) if friend_wxids_str else []
  40. friend_wxids=[f["userName"] for f in friend_wxids_list]
  41. print(friend_wxids)
  42. wxid_contact_list_content_data = [c['wxid'] for c in content_data.get("contact_list", [])]
  43. intersection_wxids = list(set(friend_wxids) & set(wxid_contact_list_content_data))
  44. # 发送消息
  45. wx_content_list = content_data.get("wx_content", [])
  46. for wx_content in wx_content_list:
  47. if wx_content["type"] == "text":
  48. send_text_message(wxchat, token_id, app_id, agent_wxid, intersection_wxids, wx_content["text"])
  49. elif wx_content["type"] == "image_url":
  50. send_image_message(wxchat, token_id, app_id, agent_wxid, intersection_wxids, wx_content.get("image_url", {}).get("url"))
  51. elif wx_content["type"] == "tts":
  52. send_tts_message(wxchat, token_id, app_id, agent_wxid, intersection_wxids, wx_content["text"])
  53. def send_text_message(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, agent_wxid, intersection_wxids, text):
  54. for t in intersection_wxids:
  55. # 发送文本消息
  56. ret,ret_msg,res = wxchat.post_text(token_id, app_id, t, text)
  57. logger.info(f'{agent_wxid} 向 {t} 发送文字【{text}】')
  58. # 构造对话消息并发送到 Kafka
  59. input_wx_content_dialogue_message = [{"type": "text", "text": text}]
  60. input_message = utils.dialogue_message(agent_wxid, t, input_wx_content_dialogue_message)
  61. kafka_helper.kafka_client.produce_message(input_message)
  62. logger.info("发送对话 %s", input_message)
  63. # 等待随机时间
  64. time.sleep(random.uniform(5, 15))
  65. def send_image_message(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, agent_wxid, intersection_wxids, image_url):
  66. aeskey, cdnthumburl, cdnthumblength, cdnthumbheight, cdnthumbwidth, length, md5 = "", "", 0, 0, 0, 0, ""
  67. for t in intersection_wxids:
  68. if t == intersection_wxids[0]:
  69. # 发送图片
  70. ret,ret_msg,res = wxchat.post_image(token_id, app_id, t, image_url)
  71. if ret==200:
  72. aeskey = res["aesKey"]
  73. cdnthumburl = res["fileId"]
  74. cdnthumblength = res["cdnThumbLength"]
  75. cdnthumbheight = res["height"]
  76. cdnthumbwidth = res["width"]
  77. length = res["length"]
  78. md5 = res["md5"]
  79. logger.info(f'{agent_wxid} 向 {t} 发送图片【{image_url}】{ret_msg}')
  80. else:
  81. logger.warning(f'{agent_wxid} 向 {t} 发送图片【{image_url}】{ret_msg}')
  82. else:
  83. if aeskey !="":
  84. # 转发图片
  85. res,ret,ret_msg= wxchat.forward_image(token_id, app_id, t, aeskey, cdnthumburl, cdnthumblength, cdnthumbheight, cdnthumbwidth, length, md5)
  86. logger.info(f'{agent_wxid} 向 {t} 转发图片【{image_url}】{ret_msg}')
  87. else:
  88. # 发送图片
  89. ret,ret_msg,res = wxchat.post_image(token_id, app_id, t, image_url)
  90. if ret==200:
  91. aeskey = res["aesKey"]
  92. cdnthumburl = res["fileId"]
  93. cdnthumblength = res["cdnThumbLength"]
  94. cdnthumbheight = res["height"]
  95. cdnthumbwidth = res["width"]
  96. length = res["length"]
  97. md5 = res["md5"]
  98. logger.info(f'{agent_wxid} 向 {t} 发送图片【{image_url}】{ret_msg}')
  99. else:
  100. logger.warning(f'{agent_wxid} 向 {t} 发送图片【{image_url}】{ret_msg}')
  101. # 构造对话消息并发送到 Kafka
  102. wx_content_dialogue_message = [{"type": "image_url", "image_url": {"url": image_url}}]
  103. input_message = utils.dialogue_message(agent_wxid, t, wx_content_dialogue_message)
  104. kafka_helper.kafka_client.produce_message(input_message)
  105. logger.info("发送对话 %s", input_message)
  106. # 等待随机时间
  107. time.sleep(random.uniform(5, 15))
  108. def send_tts_message(wxchat:gewe_chat.GeWeChatCom, token_id, app_id, agent_wxid, intersection_wxids, text):
  109. voice_during,voice_url=utils.wx_voice(text)
  110. for t in intersection_wxids:
  111. # 发送送语音消息
  112. if voice_url:
  113. ret,ret_msg,res = wxchat.post_voice(token_id, app_id, t, voice_url,voice_during)
  114. if ret==200:
  115. logger.info(f'{agent_wxid} 向 {t} 发送语音文本【{text}】{ret_msg}')
  116. # 构造对话消息并发送到 Kafka
  117. input_wx_content_dialogue_message = [{"type": "text", "text": text}]
  118. input_message = utils.dialogue_message(agent_wxid, t, input_wx_content_dialogue_message)
  119. kafka_helper.kafka_client.produce_message(input_message)
  120. logger.info("发送对话 %s", input_message)
  121. else:
  122. logger.warning((f'{agent_wxid} 向 {t} 发送语音文本【{text}】{ret_msg}'))
  123. else:
  124. logger.warning((f'{agent_wxid} 向 {t} 发送语音文本【{text}】出错'))
  125. # 等待随机时间
  126. time.sleep(random.uniform(5, 15))
  127. def clean_json_string(json_str):
  128. # 删除所有控制字符(非打印字符),包括换行符、回车符等
  129. return re.sub(r'[\x00-\x1f\x7f]', '', json_str)
  130. # 启动 Kafka 消费者线程
  131. def start_kafka_consumer_thread():
  132. agent_tel=os.environ.get('tel', '18029274615')
  133. consumer_thread = threading.Thread(target=kafka_helper.kafka_client.consume_messages, args=(agent_tel,wx_messages_process_callback,))
  134. consumer_thread.daemon = True # 设置为守护线程,应用退出时会自动结束
  135. consumer_thread.start()