def user_stats_listener(username, source): user_id = BotDatabase.userid_from_username(username, source) if user_id == None: return None user_detail = BotDatabase.user_stats(user_id) print("user_stats********") print(str(user_detail)) return Message.get_user_stats_payload(user_detail)
def match_innings_change(): match_id = Helper.get_match_params(request)['match_id'] chat_id = request['originalDetectIntentRequest']['payload']['data'][ 'chat']['id'] bot = BotDatabase(match_id) batsman_list = bot.get_available_batsman() TelegramHelper.send_keyboard_message(chat_id, "strike-batsman name?", batsman_list)
def out_with_fielder_action(match_id, chat_id, request, out_type): bot = BotDatabase(match_id) bot.out_with_fielder(out_type) fielder_list = bot.get_available_bowlers() TelegramHelper.send_keyboard_message(chat_id, "Fielder name?", fielder_list) return json.dumps({})
def test_noball_back(): match_params = Helper.get_match_params(request) chat_id = request['originalDetectIntentRequest']['payload']['data'][ 'chat']['id'] match_id = match_params['match_id'] bot = BotDatabase(match_id) match_info = bot.get_live_match_info() TelegramHelper.send_scoring_keyboard(chat_id, match_info) return json.dumps({})
def get_last_txn_from_history(match_id, status=None): print("status from get_last_txn_from_history:") print(status) if status == 'resume': BotDatabase.set_match_status(match_id, from_status="resume", to_status="live") last_txn = BotDatabase.get_last_txn(match_id) return last_txn
def runout_update(match_id, chat_id, request, out_type, run): #TODO bowler stats update, personnel bot = BotDatabase(match_id) bot.run_out_update(out_type, int(run)) fielder_list = bot.get_available_bowlers() TelegramHelper.send_keyboard_message(chat_id, "Fielder name?", fielder_list) return json.dumps({})
def undo_listener(chat_id, match_id): bot = BotDatabase(match_id) bot.undo_match() match_info = bot.get_live_match_info() if match_info["ball_number"] == 6: TelegramHelper.send_scoring_keyboard(chat_id, match_info, undo=True) else: TelegramHelper.send_scoring_keyboard(chat_id, match_info)
def add_players_action(team_name, team_players_list, match_id, chat_id, intent_name): bot = BotDatabase(match_id) bot.add_players(team_name, team_players_list) if intent_name == 'match.team2players': batsman_list = bot.get_available_batsman() TelegramHelper.send_keyboard_message(chat_id, "strike-batsman name?", batsman_list) return json.dumps({})
def exit_conversation(match_id, request): # session = request['session'] # SESSION_ID = session.rpartition('/')[2] BotDatabase.set_match_status(match_id, from_status="live", to_status="end") exit_payload = Message.exit_payload() if not 'outputContexts' in request['queryResult']: return exit_payload return Helper.append_clear_context_payload(exit_payload, request)
def ball_action_listener(run, match_id, chat_id, request, SESSION_ID, action, intent_name, user_text, response): #TODO bowler stats update bot = BotDatabase(match_id) bot.players_stats_update(int(run)) res = bot.run_update(int(run)) #for resume match only #TODO below BotDatabase.push_history(match_id, SESSION_ID, action, intent_name, user_text, res["response"]) if res["type"] == "ask_next_bowler": bowler_list = bot.get_available_bowlers() TelegramHelper.send_keyboard_message( chat_id, res['response'] + "\n\nNext Bowler?", bowler_list) return json.dumps({}) elif res["type"] == "end": # end_message = Message.end_match_payload() # res = Helper.append_clear_context_payload(end_message,request) clear = Helper.clear_contexts(match_id, request) TelegramHelper.remove_keyboard(chat_id) return clear elif res["type"] == "change": TelegramHelper.send_keyboard_general(chat_id, "change innings?", [[{ "text": "change" }, { "text": "Undo" }]]) return json.dumps({}) match_info = bot.get_live_match_info() TelegramHelper.send_scoring_keyboard(chat_id, match_info) return json.dumps({})
def link_bot_user(): print('in ********* link_bot_user') username = '' if "from" in request['originalDetectIntentRequest']['payload'][ "data"] and "username" in request['originalDetectIntentRequest'][ 'payload']["data"]["from"]: username = request['originalDetectIntentRequest']['payload']['data'][ 'from']['username'] else: return json.dumps( Message.general_message( "ValidationError: Telegram username is required, please go to settings and create one" )) if username[:1] == '@': username = username[1:] bot_user = '******' + username platform_user = username print(bot_user) print(platform_user) if "." in bot_user or "$" in bot_user: return json.dumps( Message.general_message( "ValidationError: < '.' or '$' > not allowed in usernames e.g pankaj.singh is invalid, pankajsingh is valid,\nPlease change your telegram username" )) try: source = request['originalDetectIntentRequest']['source'] res = '' if source == 'telegram': if not TelegramHelper.validate_platform_user_request_message( request): res = Message.get_invalid_request_payload() return json.dumps(res) print(source) if not BotDatabase.user_already_exist(bot_user): res = BotDatabase.link_users(bot_user, platform_user, source) print("res=") print(res) if res == False: return json.dumps(Message.get_invalid_request_payload()) else: return json.dumps(Message.general_message("done")) else: res = Message.get_invalid_request_payload() return json.dumps(res) except Exception as e: return Message.get_invalid_request_payload()
def match_start(): logger.info(request) print(request) match_params = Helper.get_match_params(request) match_id = match_params['match_id'] username = match_params['username'] #TODO add dialogflow prompt instead of returning normal message if username == '': return json.dumps( Message.general_message( "ValidationError: Telegram username is required, please go to settings and create one" )) if match_id == None: return json.dumps( Message.general_message( "ValidationError: Please say 'Add me' to register yourself")) match = BotDatabase.get_match_document(match_id) if match != None: print("found match") return json.dumps( Message.general_message( "You already have a live match in db, should I delete it?")) else: print("No match") return json.dumps( Message.general_message("Enter team names e.g Pexa vs Lexa?"))
def batsman_change_action_listener(batsman, match_id, chat_id): bot = BotDatabase(match_id) response = bot.batsman_change(batsman) if response["type"] == 'ask_next_bowler': bowler_list = bot.get_available_bowlers() TelegramHelper.send_keyboard_message( chat_id, response['response'] + "\n\nNext Bowler?", bowler_list) return json.dumps({}) elif response["type"] == 'next': match_info = bot.get_live_match_info() TelegramHelper.send_scoring_keyboard(chat_id, match_info) # TelegramHelper.send_ball_keyboard_message(chat_id) return json.dumps({}) return json.dumps({})
def toss_action_listener(team1, team2, decision, toss_team, overs, match_id, start_date): _id = BotDatabase.update_teams(team1, team2, decision, toss_team, overs, start_date, match_id) if group_notification_enabled: TelegramHelper.send_general_message( group_id, Message.match_start_group_payload(front_end_url + str(_id), team1, team2, match_id)) return json.dumps( Message.match_start_payload(front_end_url + str(_id), team1))
def pause_match_listner(match_id, username, request): success = BotDatabase.set_match_status(match_id=match_id, from_status="live", to_status="pause") if not success: return json.dumps(Message.get_invalid_request_payload()) else: #exit_payload = ActionListener.exit_listner(match_id,request) pause_payload = Message.get_match_pause_payload(username) pause_payload = Helper.append_clear_context_payload( pause_payload, request) return json.dumps(pause_payload)
def test_batsman_change(batsman): match_params = Helper.get_match_params(request) match_id = match_params['match_id'] chat_id = request['originalDetectIntentRequest']['payload']['data'][ 'chat']['id'] if 'exit' in match_params: TelegramHelper.remove_keyboard(chat_id) return match_params['exit'] match = BotDatabase.get_match_document(match_id) send_live_data(match) return ActionListener.batsman_change_action_listener( batsman, match_params['match_id'], chat_id)
def out_fielder_update_listner(match_id, chat_id, request, fielder): bot = BotDatabase(match_id) response = bot.out_fielder_update(fielder) if response["type"] == 'ask_next_batsman': batsman_list = bot.get_available_batsman() TelegramHelper.send_keyboard_message(chat_id, "Next Batsman?", batsman_list) return json.dumps({}) elif response["type"] == "end": BotDatabase.set_match_status(match_id=match_id, from_status="live", to_status="end") clear = Helper.clear_contexts(match_id, request) TelegramHelper.remove_keyboard(chat_id) return clear elif response["type"] == "change": TelegramHelper.send_keyboard_general(chat_id, "change innings?", [[{ "text": "change" }, { "text": "Undo" }]]) return json.dumps({}) return json.dumps(response['response'])
def strike_change_action(chat_id, match_id): bot = BotDatabase(match_id) bot.strike_change() bot.match["undo_count"] = 1 bot.match.save() match_info = bot.get_live_match_info() TelegramHelper.send_scoring_keyboard(chat_id, match_info) return json.dumps({})
def noball_with_number(number): #test.noball_with_number match_params = Helper.get_match_params(request) chat_id = request['originalDetectIntentRequest']['payload']['data'][ 'chat']['id'] match_id = match_params['match_id'] if 'exit' in match_params: TelegramHelper.remove_keyboard(chat_id) return match_params['exit'] response = ActionListener.noball_with_number_number_action_listener( number, match_params['match_id'], chat_id) #websocket response start match = BotDatabase.get_match_document(match_id) send_live_data(match) #websocket response end return response
def update_on_strike_batsmen_listener(batsman, match_id, chat_id, batsman_type): bot = BotDatabase(match_id) bot.on_strike_batsmen_update(batsman, batsman_type) player_list = [] if batsman_type == "strike_batsman": player_list = bot.get_available_batsman() TelegramHelper.send_keyboard_message(chat_id, "non-strike batsman?", player_list) else: player_list = bot.get_available_bowlers() TelegramHelper.send_keyboard_message(chat_id, "Opening Bowler?", player_list) return json.dumps({})
def get_match_params(request): match_params = {} source = '' match_id = '' username = '' start_date = '' if 'source' in request['originalDetectIntentRequest']: source = request['originalDetectIntentRequest']['source'] # else: # return json.dumps(Message.get_invalid_request_payload()) #have to update for other platforms if source == 'telegram': if "from" in request['originalDetectIntentRequest']['payload'][ 'data'] and "username" in request[ 'originalDetectIntentRequest']['payload']['data'][ "from"]: username = request['originalDetectIntentRequest']['payload'][ 'data']['from']['username'] start_date = request['originalDetectIntentRequest']['payload'][ 'data']['date'] if username != '' and username[:1] == '@': username = username[1:] if username != '': match_id = BotDatabase.userid_from_username(username, source) else: match_id = "test" start_date = '' match_params["username"] = username match_params["match_id"] = match_id match_params["start_date"] = start_date match_params["source"] = source if request['queryResult']['queryText'] in exit_set: match_params['exit'] = Helper.clear_contexts(match_id, request) if request['queryResult']['queryText'].lower() == 'undo': match_params['undo'] = True return match_params
def test_ball_listener(bowler, match_id, chat_id): bot = BotDatabase(match_id) bot.current_bowler_update(bowler) match_info = bot.get_live_match_info() TelegramHelper.send_scoring_keyboard(chat_id, match_info)
def match_resume(scorer_id): match_id = Helper.get_match_params(request)['match_id'] scorer_username = scorer_id if scorer_username[:1] == '@': scorer_username = scorer_username[1:] print("userid from intent:") print(scorer_username) scorer_id = BotDatabase.userid_from_username(scorer_username, 'telegram') print("userid after conversion:") print(scorer_id) #-------------------------------------------------------------- print("processing......") last_txn = ActionListener.get_last_txn_from_history(scorer_id) match_status = BotDatabase.get_match_status(scorer_id) if match_status == 'live': BotDatabase.set_match_status(match_id=scorer_id, from_status="live", to_status="pause") SESSION_ID = last_txn['SESSION_ID'] intent_name = last_txn['intent_name'] user_text = last_txn['user_text'] print("last_txn") print(last_txn) input_context = MatchDatabase.get_input_context_from_intent_name( intent_name) print(input_context) session_client = dialogflow_v2.SessionsClient() parameters = dialogflow_v2.types.struct_pb2.Struct() parameters["match_id"] = match_id context_1 = dialogflow_v2.types.context_pb2.Context( name="projects/cricbot-qegqqr/agent/sessions/" + SESSION_ID + "/contexts/" + input_context, lifespan_count=2, parameters=parameters) query_params = {"contexts": [context_1]} session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID) text_input = dialogflow_v2.types.TextInput(text=user_text, language_code="en-us") query_input = dialogflow_v2.types.QueryInput(text=text_input) try: response = session_client.detect_intent(session=session, query_input=query_input, query_params=query_params) except InvalidArgument: raise print("respose from resume:") print(response) print("Query text:", response.query_result.query_text) print("Detected intent:", response.query_result.intent.display_name) print("Detected intent confidence:", response.query_result.intent_detection_confidence) print("Fulfillment text:", response.query_result.fulfillment_text) output = { "fullfillmentText": 'valid', "fulfillmentMessages": [{ "text": { "text": ["Match is On!"] } }] } output['outputContexts'] = [{ "name": "projects/cricbot-qegqqr/agent/sessions/b630631f-19ae-396b-9477-6ba29737d8e8/contexts/ball", "lifespan_count": 5 }] logger.info("output=") logger.info(output) return json.dumps(output)
def delete_live_matches_action(match_id): bot = BotDatabase(match_id) bot.delete_live_matches_of_user()
def most_runs_listener(): user_detail = BotDatabase.get_most_runs_user() return Message.get_user_stats_payload(user_detail)
def undo_next_over_action(chat_id, match_id): bot = BotDatabase(match_id) bowler_list = bot.get_available_bowlers() TelegramHelper.send_keyboard_message(chat_id, "Next Bowler?", bowler_list)
def bowler_change_action_listener(bowler, match_id, chat_id): bot = BotDatabase(match_id) bot.current_bowler_update(bowler) match_info = bot.get_live_match_info() TelegramHelper.send_scoring_keyboard(chat_id, match_info) return json.dumps({})
def noball_with_number_number_action_listener(run, match_id, chat_id): bot = BotDatabase(match_id) bot.noball_update(int(run)) match_info = bot.get_live_match_info() TelegramHelper.send_scoring_keyboard(chat_id, match_info) return json.dumps({})
def runout_batsman_action(match_id, chat_id, batsman_type): bot = BotDatabase(match_id) bot.runout_batsman_out_update(batsman_type)
def get_match_data(id): match_doc = BotDatabase.get_match_document_by_id(id) print(dumps(match_doc)) return dumps(match_doc)