def start_the_game(self, request_json): money = user_login.get_luck_point_by_sender_id(request_json['senderId'])['value'] if money < Bet.minimum_init_bet: chatbots.get(request_json['chatbotUserId']).send_text("100金币开局,没钱你还是先靠边站吧...") return dark_show_hand_listener = DarkShowHandListener(request_json, self.listener_manager) self.listener_manager.put_new_listener(dark_show_hand_listener)
def display_result(self, scores): daily_salary = float(scores['DAILY_SALARY']) working_hours = float(scores['WORKING_HOURS']) commuting_hours = float(scores['COMMUTING_HOURS']) playing_hours = float(scores['PLAYING_HOURS']) working_area_score = WORKING_AREA_SCORE_MAP.get(scores['WORKING_AREA_SCORE']) study_score = STUDY_SCORE_MAP.get(scores['STUDY_SCORE']) sexy_area_score = SEXY_AREA_SCORE_MAP.get(scores['SEXY_AREA_SCORE']) guys_area_score = GUYS_AREA_SCORE_MAP.get(scores['GUYS_AREA_SCORE']) evil_morning_score = EVIL_MORNING_SCORE_MAP.get(scores['EVIL_MORNING_SCORE']) result_1 = daily_salary * working_area_score * sexy_area_score * guys_area_score * evil_morning_score result_2 = 35 * study_score * (working_hours + commuting_hours - 0.5 * playing_hours) result = result_1 / result_2 text = '爽到爆炸' if result < 0.8: text = '很惨' elif result < 1.5: text = '一般' elif result < 2: text = '很爽' chatbots.get(self.chatbot_user_id).send_action_card( ActionCard( title="计算完成", text="### 得分:{0}\n ### 你的工作性价比:「{1}」".format(result, text), btns=[CardItem( title="重新计算", url="**工作性价比:开启")] ))
def do_handle(self, request_object, request_json): id = uuid.uuid1() image = self.get_image() words = self.get_words() if image == '': chatbots.get( request_json['chatbotUserId']).send_text('正在生成中,这可能需要一些时间...') body = {} word_cloud_dict = {} while len(word_cloud_dict) < 200: response = requests.post(dark_jikipedia.browse_definitions_url, json=body, headers=dark_jikipedia.header).json() for data in response: word_cloud_dict[data.get('term').get('title')] = data.get( 'view_count') if len(word_cloud_dict) == 200: break time.sleep(1) image = cloudMaker.make_word_cloud_to_image(word_cloud_dict) self.put_image(image) id = uuid.uuid1() words = self.put_words(word_cloud_dict) title = "小鸡骚词" img_url = f"http://{config.public_ip}/dark_buddy/dark_ji_word_cloud/image/get?session_id={request_json['chatbotUserId']}&uuid={id}" text = f"![screenshot]({img_url})\n### 小鸡骚词\n{words}" action_card = ActionCard(title=title, text=text, btns=[], img_url=img_url) chatbots.get( request_json['chatbotUserId']).send_action_card(action_card)
def do_handle(self, request_array, request_json): if request_array[2] == '金币': money = user_login.get_luck_point_by_sender_id(request_json['senderId'])['value'] chatbots.get(request_json['chatbotUserId']).send_text( "当前的金币数:{0}".format(money)) return True return False
def display_guess_number(self, data): tried_record = data['tried_record'] text = "# 暗黑数字:{0}\n 给出你的答案!输入:\n# **游戏:猜数字:猜:「你的答案」。\n 你还有「{1}」次机会,以下是记录。\n".format('*' * self.digit_count, self.turn - int( data['try_time'])) for record in tried_record: text = text + "- 【{0}】\t「{1}」个数字数位皆同,「{2}」个数字数同位不同\n".format(record['try_number'], record['a'], record['b']) chatbots.get(self.chatbot_user_id).send_markdown(title="猜数字", text=text)
def ask(self, choices, question: str): self.current_answer = None self.set_listener_session_choices(str(choices.encode())) if question: chatbots.get(self.chatbot_user_id).send_text(question) while self.current_answer is None: eventlet.sleep(1) return self.current_answer
def shut_down_dark_spy(self, request_json): redis.delete( self.get_dark_spy_session_name(request_json['chatbotUserId'])) chatbots.get(request_json['chatbotUserId']).send_action_card( ActionCard(title="游戏结束", text="### 游戏已经回归虚无......", btns=[CardItem(title="再来一把", url="**游戏:谁是卧底:开启")])) return
def display_mc_quiz(self, redis_data, request_json): btns = [] for i, choice in enumerate(redis_data['choices']): btns.append( CardItem(title=choice, url="**游戏:暗黑答题:答题:1:{0}".format(i))) chatbots.get(request_json['chatbotUserId']).send_action_card( ActionCard(title="暗黑答题", text="### 答对加20金币,答错扣5金币\n{0}".format( redis_data['title']), btns=btns))
def shut_down_guess_number(chatbot_user_id): redis.delete(get_dark_guess_number_session_name(chatbot_user_id)) chatbots.get(chatbot_user_id).send_action_card( ActionCard( title="游戏结束", text="### 数字已经忘记......", btns=[CardItem( title="再来一把", url="**游戏:猜数字:开启")] )) return
def shut_down_work_shuang_rank(chatbot_user_id): redis.delete(get_dark_work_shuang_rank_session_name(chatbot_user_id)) chatbots.get(chatbot_user_id).send_action_card( ActionCard( title="计算已关闭", text="### 计算已关闭......", btns=[CardItem( title="重新计算", url="**工作性价比:开启")] )) return
def start_dark_maze(self): if redis.get(get_dark_maze_session_name(self.chatbot_user_id)) is None: chatbots.get(self.chatbot_user_id).send_text('正在生成迷宫......') maze_session_data = self.build_maze() chatbots.get(self.chatbot_user_id).send_text('正在生成人物......') redis.setex(name=get_dark_maze_session_name(self.chatbot_user_id), time=3600, value=str(maze_session_data)) self.listener.current_answer = ' ' while self.treat_maze(self.listener.current_answer): self.listener.ask(maze_operator, '输入wsad移动') shut_down_dark_maze(self.chatbot_user_id)
def start_guess_number(self): if redis.get(get_dark_guess_number_session_name(self.chatbot_user_id)) is None: chatbots.get(self.chatbot_user_id).send_text('正在生成数字......') guess_number_session_data = self.build_guess_number() redis.setex(name=get_dark_guess_number_session_name(self.chatbot_user_id), time=3600, value=str(guess_number_session_data)) self.display_guess_number( data=eval(redis.get(get_dark_guess_number_session_name(self.chatbot_user_id)).decode())) number = '' while self.treat_guess_number(number): number = self.listener.ask(guess_number_operator, '输入任意数字') shut_down_guess_number(self.chatbot_user_id)
def do_handle(self, request_object, request_json): id = uuid.uuid1() image = self.get_image() if image == '': chatbots.get(request_json['chatbotUserId']).send_text('正在生成中,这可能需要一些时间...') image = self.get_word_cloud_image() self.put_image(image) title = "暗黑热搜" img_url = f"http://{config.public_ip}/dark_buddy/dark_word_cloud/image/get?session_id={request_json['chatbotUserId']}&uuid={id}" text = f"![screenshot]({img_url})\n# 暗黑热搜榜" action_card = ActionCard(title=title, text=text, btns=[]) chatbots.get(request_json['chatbotUserId']).send_action_card(action_card)
def treat_maze(self, steps): maze_data = redis.get(get_dark_maze_session_name(self.chatbot_user_id)) if maze_data is None: chatbots.get(self.chatbot_user_id).send_text('你要不先对我说:**游戏:迷宫:开启') return False data = eval( redis.get(get_dark_maze_session_name( self.chatbot_user_id)).decode()) preview_location = data['player']['location'] map_location_data = data['map'][preview_location[0]][ preview_location[1]] for step in steps: if step == 'a': if map_location_data[0] == 0 or preview_location[1] == 0: self.display_maze(data, message='那是一条死路诶...') return True preview_location[1] = preview_location[1] - 1 map_location_data = data['map'][preview_location[0]][ preview_location[1]] elif step == 'w': if map_location_data[1] == 0 or preview_location[0] == 0: self.display_maze(data, message='那是一条死路诶...') return True preview_location[0] = preview_location[0] - 1 map_location_data = data['map'][preview_location[0]][ preview_location[1]] elif step == 'd': if map_location_data[2] == 0 or preview_location[ 1] == self.maze_col - 1: self.display_maze(data, message='那是一条死路诶...') return True preview_location[1] = preview_location[1] + 1 map_location_data = data['map'][preview_location[0]][ preview_location[1]] elif step == 's': if map_location_data[3] == 0 or preview_location[ 0] == self.maze_row - 1: self.display_maze(data, message='那是一条死路诶...') return True preview_location[0] = preview_location[0] + 1 map_location_data = data['map'][preview_location[0]][ preview_location[1]] elif step == ' ': continue if preview_location[1] == self.maze_col - 1 and preview_location[ 0] == self.maze_row - 1: chatbots.get(self.chatbot_user_id).send_text('卧槽牛逼啊!这你都走出来了!') user_login.rewards(50, self.user_id, chatbots.get(self.chatbot_user_id), '') return False self.display_maze(data, message='接下来是...') return True
def display_maze(self, data, message): redis.set(name=get_dark_maze_session_name(self.chatbot_user_id), value=str(data)) title = "暗黑迷宫" img_url = 'http://{2}/dark_buddy/dark_maze/image/get?session_id={0}&uuid={1}'.format( self.chatbot_user_id, uuid.uuid1(), config.public_ip) text = '![screenshot]({0})\n# {1}'.format(img_url, message) action_card = ActionCard(title=title, text=text, btns=[], img_url=img_url) chatbots.get(self.chatbot_user_id).send_action_card(action_card) return
def treat_guess_number(self, number): guess_number_data = redis.get(get_dark_guess_number_session_name(self.chatbot_user_id)) if guess_number_data is None: chatbots.get(self.chatbot_user_id).send_text('你要不先对我说:**游戏:猜数字:开启') return False data = eval(redis.get(get_dark_guess_number_session_name(self.chatbot_user_id)).decode()) if number == '': self.display_guess_number(data) return True current_number = data['current_number'] tried_record = data['tried_record'] if len(number) != self.digit_count or not number.isdigit(): chatbots.get(self.chatbot_user_id).send_text( '咱这个数字答案是{0}位数字,我寻思着你在这输的啥JB玩意儿呢!'.format(self.digit_count)) return True a, b = self.calculate_guess_number(current_number, number) if a == self.digit_count: chatbots.get(self.chatbot_user_id).send_text( '哇你好屌,正确答案就是:「{0}」,秀秀秀!'.format(str(current_number))) user_login.get_luck_point_by_sender_id(50, self.user_id) return False tried_record.append({ "try_number": number, "a": a, "b": b }) data['try_time'] += 1 if data['try_time'] >= self.turn: chatbots.get(self.chatbot_user_id).send_text( '游戏结束,正确答案是:「{0}」,小朋友你不行啊!'.format(str(current_number))) return False redis.setex(name=get_dark_guess_number_session_name(self.chatbot_user_id), time=3600, value=str(data)) self.display_guess_number(data) return True
def login(self, json): user = { 'sender_id': json['senderId'], 'name': json['senderNick'], 'status': 0 } update_user(user) founded_user = select_by_senderId(json['senderId']) if founded_user.get('banned_time') and founded_user.get( 'banned_time') > now_date.now(): chatbots.get(json['chatbotUserId']).send_text( "{0},你被禁言了!解禁时间:{1}".format(json['senderNick'], founded_user.banned_time)) return None return founded_user
def get_cai_hong_pi_by_user_id(self, request_json): do_api = random.random() > 0.7 if do_api: self.let_api_do(request_json) else: sender = select_by_senderId(request_json['senderId']) user_id = sender['id'] records = select_by_user_id(user_id) if len(records) == 0: self.let_api_do(request_json) else: record = random.choice(records) str = '远哥拍了拍{0}的头,说:{1}'.format(sender['name'], record['sweet_talk']) chatbots.get(request_json['chatbotUserId']).send_text(str)
def get_simsimi_chat(self, request_json): request = request_json["text"]["content"] body = get_simsimi_body(request) header = simsimi_header response = requests.post(self.url, json=body, headers=header) text = response.text.replace("true", "True").replace("false", "False").replace("null", "None") response_json = eval(text) if response_json["status"] != 200: log.error(traceback.format_exc()) log.error(response.text) chatbots.get(request_json['chatbotUserId']).send_text("你这是说的什么弟弟鬼话呢!") return False datas = response_json["atext"] chatbots.get(request_json['chatbotUserId']).send_text(datas) return True
def show_gamer_info(self, request_json): game_session_data = self.get_game_session_data(request_json) gamer = list( filter(lambda x: x.name == request_json['name'], game_session_data.get_gamers())) if not gamer: chatbots.get(request_json['chatbotUserId']).send_text( "{0}!你还没有参加...".format(request_json['name'])) gamer = gamer[0] word = "" if gamer.role == GamerRolesEnum.BLACK: word = game_session_data.black_word if gamer.role == GamerRolesEnum.WHITE: word = game_session_data.white_word result = {"name": gamer.name, "word": word} return result
def do_handle(self, request_object, request_json): body = {} response = requests.post(self.browse_definitions_url, json=body, headers=self.header).json() # log.info(json.dumps(response, indent=4)) content = "### 骚词推荐\n" for data in response: if data.get('scaled_image') != '': title = data.get('term').get('title') content += "[{0}](dtmd://dingtalkclient/sendMessage?content={1})/".format( title, quote(title)) action_card = ActionCard(title="骚词推荐", text=content[:-1], btns=[CardItem(title="查看更多", url="**骚词:推荐")]) chatbots.get( request_json['chatbotUserId']).send_action_card(action_card) return True
def start_game(self, request_json): game_session_data = self.get_game_session_data(request_json) if game_session_data.game_status == GameStatusEnum.END: chatbots.get(request_json['chatbotUserId']).send_text("游戏已经结束...") return gamers = game_session_data.get_gamers() if len(gamers) < 4: chatbots.get(request_json['chatbotUserId']).send_text("人太少了...") return game_session_data = self.build_game(game_session_data) game_session_data_str = json.dumps(game_session_data, cls=DarkSpyGameSessionDataEncoder, indent=4) redis.set(name=self.get_dark_spy_session_name( request_json['chatbotUserId']), value=game_session_data_str) self.render_game(game_session_data, request_json) return
def get_dark_jikipedia(self, request_json): text = request_json["text"]["content"].strip() # 1:补全搜索条件 if self.auto_complete(text, request_json): return True # 2:搜TMD search_definition_data = self.search_definitions(text) # 3: 发TMD if search_definition_data == {}: chatbots.get( request_json['chatbotUserId']).send_text("小鸡我搜不到东西了,你换个方式再问一遍") else: action_card = self.action_card_content(search_definition_data) chatbots.get( request_json['chatbotUserId']).send_action_card(action_card) return True
def do_handle(self, request_object, request_json): sender_id = request_json['senderId'] sender_nick = request_json['senderNick'] redis.setex(name=self.get_sign_in_lock_name(sender_id), time=60, value=sender_nick) btns = [] btn = CardItem( title='点击注册', url='http://{2}/dark_buddy/web/bindid/{0}?uuid={1}'.format( sender_id, uuid.uuid1(), public_ip)) btns.append(btn) title = "欢迎注册" text = "# {0}你好, 请点击下方按钮注册。".format(sender_nick) action_card = ActionCard(title=title, text=text, btns=btns, btn_orientation=1) chatbots.get( request_json['chatbotUserId']).send_action_card(action_card)
def get_request(self, matched, json): request = self.function_map.get(matched) if matched == "constellation": # 拿这个人的星座,是最骚的 ding_id = json["senderId"] user = mapper.mapper_user.select_by_senderId(ding_id) user_status = mapper.mapper_user_status.select_by_statusCode_and_userId('constellation', user.id) if not user_status: log.error('{0}这个人没星座这个属性。'.format(json["senderNick"])) return None constellation = self.status_constellation_map.get(user_status.value) if not constellation: log.error('{0}这个人星座这个属性乱写:{1}。'.format(json["senderNick"], user_status.value)) return None year = time.strftime("%Y", time.localtime(int(time.time()) / 1000)) month = time.strftime("%m", time.localtime(int(time.time()) / 1000)) day = time.strftime("%d", time.localtime(int(time.time()) / 1000)) request = request % (constellation, year, month, day) elif matched == "laohuangli": date = time.strftime("%Y-%m-%d", time.localtime(int(time.time()) / 1000)) request = request % date elif matched == "dongtu": self.random = random.randint(0,5000) request = request % self.random elif matched == "today": date = time.strftime("%-m/%-d", time.localtime(int(time.time()) / 1000)) request = request + date if not request: chatbots.get(json['chatbotUserId']).send_text("你并不能得到这个信息,你觉得是为什么呢?") return True response = requests.request("GET", request, headers=self.header) content = codecs.decode(response.content, "utf-8") content.replace("null", "None") response_json = eval(content) try: self.send_message_by_response(matched, json, response_json) return True except: log.error(traceback.format_exc()) log.error(content) return False
def join_in(self, request_json): game_session_data = self.get_game_session_data(request_json) if game_session_data.game_status == GameStatusEnum.END: chatbots.get(request_json['chatbotUserId']).send_text("游戏已经结束...") return if game_session_data.game_status == GameStatusEnum.GAMING: chatbots.get(request_json['chatbotUserId']).send_text("游戏已经开始...") return gamer = list( filter(lambda x: x.sender_id == request_json['senderId'], game_session_data.get_gamers())) if gamer: chatbots.get(request_json['chatbotUserId']).send_text("你已经参加了...") return new_gamer = Gamers() new_gamer.name = request_json['senderNick'] new_gamer.sender_id = request_json['senderId'] game_session_data.gamers.append(new_gamer) game_session_data_str = json.dumps(game_session_data, cls=DarkSpyGameSessionDataEncoder, indent=4) redis.set(name=self.get_dark_spy_session_name( request_json['chatbotUserId']), value=game_session_data_str) self.render_game(game_session_data, request_json) return
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 auto_complete(self, text, request_json): body = {"phrase": text} response = requests.post(self.auto_complete_url, json=body, headers=self.header) # log.info(json.dumps(response.json(), indent=4)) auto_complete_result = response.json()['data'] if len(auto_complete_result) > 0: btns = [] for word in auto_complete_result: if text == word['word']: return False title = word['word'] btn = CardItem(title=title, url=quote(title)) btns.append(btn) title = "你是想问?" text = "### 你是想问?" action_card = ActionCard(title=title, text=text, btns=btns) chatbots.get( request_json['chatbotUserId']).send_action_card(action_card) return True return False
def treat_dark_quiz(self, answer, type, request_json): redis_data_str = redis.get( self.get_session_name_by_type(request_json['chatbotUserId'], int(type))) if redis_data_str is None: return redis_data = eval(redis_data_str) if redis_data['answer'] == int(answer): chatbots.get(request_json['chatbotUserId']).send_action_card( ActionCard(title="暗黑答题", text="### 回答正确!6六6!", btns=[ CardItem(title="再来一题是非题", url="**游戏:暗黑答题:是非题(10金币)"), CardItem(title="再来一题单选题", url="**游戏:暗黑答题:单选题(20金币)") ])) if type == '0': user_login.rewards_to_sender_id(10, request_json) if type == '1': user_login.rewards_to_sender_id(20, request_json) else: chatbots.get(request_json['chatbotUserId']).send_action_card( ActionCard(title="暗黑答题", text="### GG!回答错误!正确答案是「{0}」,相关信息:{1}".format( redis_data['answer_str'], redis_data['analytic']), btns=[ CardItem(title="再来一题是非题", url="**游戏:暗黑答题:是非题(10金币)"), CardItem(title="再来一题单选题", url="**游戏:暗黑答题:单选题(20金币)") ])) user_login.rewards_to_sender_id(-5, request_json) redis.delete( self.get_session_name_by_type(request_json['chatbotUserId'], int(type)))
def switch_dark_mode(self, request_json): request = request_json["text"]["content"] if "开启暗黑模式" in request: self.dark_mode_flag = 0 chatbots.get( request_json['chatbotUserId']).send_text("所以我就开启了暗黑模式") return True if "开启智能模式" in request: self.dark_mode_flag = 2 chatbots.get( request_json['chatbotUserId']).send_text("所以我就开启了智能模式") return True if "开启小鸡模式" in request: self.dark_mode_flag = 3 chatbots.get( request_json['chatbotUserId']).send_text("所以我就开启了小鸡模式") return True return False