def send_work_weixin_msg(user_message): workWeixin = Setting.get_settings("workWeixin") weixin = WorkWeiXin(corp_id=workWeixin['WEIXIN_CORP_ID'], corp_secret=workWeixin['WEIXIN_CORP_SECRET'], agent_id=workWeixin['WEIXIN_AGENT_ID']) text = get_msg_content(user_message) content = {'content': text} token = get_work_weixin_token(False) res = weixin.send_markdown_msg(receivers=user_message.receive, content=content, token=token) if res.success: user_message.receive_status = UserMessage.MESSAGE_RECEIVE_STATUS_SUCCESS user_message.save() elif res.data['errcode'] == 40014: token = get_work_weixin_token(True) res = weixin.send_markdown_msg(receivers=user_message.receive, content=content, token=token) if res.success: user_message.receive_status = UserMessage.MESSAGE_RECEIVE_STATUS_SUCCESS user_message.save() else: logger.error(msg="send workweixin error message_id=" + str(user_message.message_id) + "reason:" + str(res.data), exc_info=True)
def get_work_weixin_token(force): redis_cli = redis.StrictRedis(host=kubeoperator.settings.REDIS_HOST, port=kubeoperator.settings.REDIS_PORT) if redis_cli.exists('WORK_WEIXIN_TOKEN') == False or force == True: workWeixin = Setting.get_settings("workWeixin") weixin = WorkWeiXin(corp_id=workWeixin['WEIXIN_CORP_ID'], corp_secret=workWeixin['WEIXIN_CORP_SECRET'], agent_id=workWeixin['WEIXIN_AGENT_ID']) result = weixin.get_token() redis_cli.set('WORK_WEIXIN_TOKEN', result.data['access_token'], result.data['expires_in']) return result.data['access_token'] else: return redis_cli.get('WORK_WEIXIN_TOKEN')
def post(self, request, *args, **kwargs): weixin_config = request.data weixin = WorkWeiXin(corp_id=weixin_config['WEIXIN_CORP_ID'], corp_secret=weixin_config['WEIXIN_CORP_SECRET'], agent_id=weixin_config['WEIXIN_AGENT_ID']) result = weixin.get_token() if result.success: redis_cli = redis.StrictRedis(host=kubeoperator.settings.REDIS_HOST, port=kubeoperator.settings.REDIS_PORT) redis_cli.set('WORK_WEIXIN_TOKEN',result.data['access_token'],result.data['expires_in']) return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK) else: return Response(data={'msg': '校验失败!' + json.dumps(result.data)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)