def feishu(): try: if request.method == 'OPTIONS': response = jsonify(response_lib.SUCCESS_CODE) return response if request.method == 'POST': json_object = request.json log.info(json.dumps(json_object, indent=4, ensure_ascii=False)) # do verification if json_object.get('type') == "url_verification": return json_object socketio.start_background_task( target=convert_feishu_json_and_do_request, json_object=json_object) response = jsonify(response_lib.SUCCESS_CODE) return response if request.method == 'GET': log.error('Why you got GET method?') log.info(request) response = jsonify(response_lib.SUCCESS_CODE) return response except: log.error(traceback.format_exc()) response = jsonify(response_lib.ERROR_CODE) return response
def post(self, data): """ 发送消息(内容UTF-8编码) :param data: 消息数据(字典) :return: 返回发送结果 """ if not self.is_live_chat: lock.acquire() self.times += 1 if self.times % 20 == 0: if time.time() - self.start_time < 60: log.info('钉钉官方限制每个机器人每分钟最多发送20条,当前消息发送频率已达到限制条件,休眠一分钟') time.sleep(61 - time.time() + self.start_time) self.start_time = time.time() lock.release() post_data = json.dumps(data) try: log.info( f"Sending: \n {json.dumps(json.loads(post_data, encoding='utf-8'), indent=4, ensure_ascii=False)}" ) if env_config.get("DEBUG_MODE") == '0': return if self.is_live_chat: from dark_live_chat import socketio session_id = dark_local.session_id socketio.emit("answer", json.dumps(json.loads(post_data, encoding='utf-8'), ensure_ascii=False), room=session_id, namespace=namespace) return response = requests.post(self.webhook, headers=self.headers, data=post_data) except requests.exceptions.HTTPError as exc: log.error("消息发送失败, HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason)) raise except requests.exceptions.ConnectionError: log.error("消息发送失败,HTTP connection error!") raise except requests.exceptions.Timeout: log.error("消息发送失败,Timeout error!") raise except requests.exceptions.RequestException: log.error("消息发送失败, Request Exception!") raise else: try: result = response.json() except JSONDecodeError: log.error("服务器响应异常,状态码:%s,响应内容:%s" % (response.status_code, response.text)) return {'errcode': 500, 'errmsg': '服务器响应异常'} else: log.debug('发送结果:%s' % result)
def darkSpyGetWord(): try: if request.method == 'OPTIONS': response = jsonify(response_lib.SUCCESS_CODE) return response if request.method == 'POST': json_object = request.json log.info(json.dumps(json_object, indent=4, ensure_ascii=False)) return dark_spy.show_gamer_info(json_object) except: log.error(traceback.format_exc()) response = jsonify(response_lib.ERROR_CODE) return response
def dark_buddy_listener(): try: if request.method == 'OPTIONS': response = jsonify(response_lib.SUCCESS_CODE) return response if request.method == 'POST': json_object = request.json log.info(json.dumps(json_object, indent=4, ensure_ascii=False)) do_listener(json_object) response = jsonify(response_lib.SUCCESS_CODE) return response except: log.error(traceback.format_exc()) response = jsonify(response_lib.ERROR_CODE) return response
def sign_in(): try: if request.method == 'OPTIONS': response = jsonify(response_lib.SUCCESS_CODE) return response if request.method == 'POST': json_object = request.json log.info(json.dumps(json_object, indent=4, ensure_ascii=False)) sender_id = json_object['sender_id'] if user_login.check_lock(sender_id): return jsonify(response_lib.SUCCESS_CODE) else: return jsonify(response_lib.ERROR_CODE) except: log.error(traceback.format_exc()) response = jsonify(response_lib.ERROR_CODE) return response
def dark_buddy(): try: if request.method == 'OPTIONS': response = jsonify(response_lib.SUCCESS_CODE) return response if request.method == 'POST': json_object = request.json log.info(json.dumps(json_object, indent=4, ensure_ascii=False)) do_request(json_object) response = jsonify(response_lib.SUCCESS_CODE) return response if request.method == 'GET': log.error('Why you got GET method?') log.info(request) response = jsonify(response_lib.SUCCESS_CODE) return response except: log.error(traceback.format_exc()) response = jsonify(response_lib.ERROR_CODE) chatbots.get(request.json['chatbotUserId']).send_text( traceback.format_exc()) return response
def get_dark_qa(self, request_json, debug_mode=False): request = request_json["text"]["content"] try: datas = self.qa(request) if debug_mode: log.info('datas:' + str(datas)) return True except: log.error(traceback.format_exc()) log.error(request) chatbots.get( request_json['chatbotUserId']).send_text("你这是说的什么弟弟鬼话呢!") return False if datas: log.info(str(datas)) if datas['type'] == 'text': chatbots.get(request_json['chatbotUserId']).send_markdown( str(datas['from']), str(datas['value'])) if datas['type'] == 'img': chatbots.get(request_json['chatbotUserId']).send_image( datas['value'][0]) return True
def on_say_a_word(data): log.info( f"Receiving: \n {json.dumps(data, indent=4, ensure_ascii=False)}") dark_local.session_id = request.sid do_live_chat_request(data)
def on_disconnect(): log.info('Client disconnected')
def on_connect(): user_login.init_luck_point_4_temp_user(1000, f'/dark_buddy#{request.sid}') log.info('Client connected')
def on_join(): log.info("on_join, session_id: {0}".format(request.sid)) user_login.init_luck_point_4_temp_user(1000, f'/dark_buddy#{request.sid}') join_room(request.sid)
def send_message_by_response(self, matched, request_json, response_json): if matched == "joke": for i in range(0, 3): joke = response_json["result"][i] chatbots.get(request_json['chatbotUserId']).send_text(joke["content"]) elif matched == "toutiao": feed_links = [] datas = response_json.get('result').get('data') for i in range(0, 4): data = datas[i] feed_link = FeedLink(title=data.get('title'), message_url=data.get('url'), pic_url=data.get('thumbnail_pic_s')) feed_links.append(feed_link) chatbots.get(request_json['chatbotUserId']).send_feed_card(feed_links) elif matched == "weixin": log.info(str(response_json)) chatbots.get(request_json['chatbotUserId']).send_text("敬请期待...") elif matched == "constellation": name = request_json["senderNick"] text = "" for i in range(len(response_json["newslist"])): text+=response_json["newslist"][i]["type"] text+=": " text+=response_json["newslist"][i]["content"] text+="\n\n" chatbots.get(request_json['chatbotUserId']).send_markdown(title="%s,这就是你今天的暗黑星座运势" % name, text=text) elif matched == "laohuangli": log.info(str(response_json)) datas = response_json.get('result') chatbots.get(request_json['chatbotUserId']).send_markdown(title="今日黄历", text="### 宜:" + datas["yi"] + "\n" + "### 忌:" + datas["ji"]) elif matched == "dongtu": log.info(str(response_json)) datas = response_json["data"]["result"][0] action_card = ActionCard(title=datas["title"], text="![screenshot](" + datas["gifurl"] + ")\n" + "#### " + datas["title"], btns=[CardItem(title="查看更多", url="**小功能:动图")], img_url=datas["gifurl"]) chatbots.get(request_json['chatbotUserId']).send_action_card(action_card) elif matched == "today": log.info(str(response_json)) dataCollection = response_json["result"] data = random.choice(dataCollection) chatbots.get(request_json['chatbotUserId']).send_text( "早啊!^_^ 历史上的今天--" + data["date"] + " " + data["title"]) elif matched == "honey": log.info(str(response_json)) chatbots.get(request_json['chatbotUserId']).send_text(response_json["newslist"][0]["content"]) elif matched == "name": log.info(str(response_json)) chatbots.get(request_json['chatbotUserId']).send_text(response_json["newslist"][0]["naming"]) elif matched == "sweet": log.info(str(response_json)) chatbots.get(request_json['chatbotUserId']).send_text(response_json["newslist"][0]["content"]) elif matched == "shit": log.info(str(response_json)) chatbots.get(request_json['chatbotUserId']).send_text(response_json["newslist"][0]["content"]) else: chatbots.get(request_json['chatbotUserId']).send_text("你TM说啥呢!滚犊子")
def do_fetch(): for chatbot in chatbots.values(): chatbot.send_text("我要开始裂开了,期间请不要和我说话 ") os.chdir("/data/User/tianhao/Dark_buddy") log.info("Dark buddy helper starts to set the config...") os.system( "git config --global credential.helper.store --file /data/User/tianhao/git-credentials/global.gitcredentials" ) # os.system("yum install -y lsof") # os.system("yum install -y net-tools") # os.system("yum install tk-devel") log.info("Dark buddy helper starts to pull codes...") os.system("git pull") log.info("Dark buddy helper starts to shut down the service...") try: # os.system("ps -ef | grep `netstat -nlp | grep :9000 | awk '{print $7}' | awk -F / '{ print $1 }'` | awk '{print $2}' | xargs kill -9") os.system( "ps -ef | grep 'python -u app.py' | awk '{print $2}' | xargs kill -9" ) except: log.info("Dark buddy helper doesn't find the old service...") log.info("Dark buddy helper starts to install the pip...") # os.system("pip config set install.trusted-host mirrors.aliyun.com") # os.system("pip config set global.index-url http://mirrors.aliyun.com/pypi/simple/") # os.system("pip install -r requirements.txt") log.info("Dark buddy helper starts to up the service...") os.system("nohup python -u app.py > app.log 2>&1 &") log.info("Dark buddy helper makes everything well done!") pass