def message(): if request.method == 'POST': if not out_channel.get_me()['username'] == self.verify: logger.debug("Invalid access token, check it " "matches Telegram") return "failed" update = Update.de_json(request.get_json(force=True), out_channel) if self._is_button(update): msg = update.callback_query.message text = update.callback_query.data else: msg = update.message if self._is_user_message(msg): text = msg.text.replace('/bot', '') elif self._is_location(msg): text = ('{{"lng":{0}, "lat":{1}}}' ''.format(msg.location.longitude, msg.location.latitude)) else: return "success" sender_id = msg.chat.id try: if (text == '_restart' or text == constants.USER_INTENT_RESTART): on_new_message( UserMessage(text, out_channel, sender_id, input_channel=self.name())) on_new_message( UserMessage('/start', out_channel, sender_id, input_channel=self.name())) else: on_new_message( UserMessage(text, out_channel, sender_id, input_channel=self.name())) except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.debug(e, exc_info=True) if self.debug_mode: raise pass return "success"
def say(self, request, cid): message, = request.args.get(b"message", []) _payload = request.args.get(b"payload", []) _display_name = request.args.get(b"display_name", []) _uuid = request.args.get(b"uuid", []) logger.info(message) if len(_display_name) > 0: display_name, = _display_name tracker = self.agent.tracker_store.get_or_create_tracker(cid) if ("display_name" in tracker.current_slot_values() and tracker.get_slot("display_name") != display_name): tracker.update( SlotSet("display_name", display_name.decode("utf-8"))) self.agent.tracker_store.save(tracker) if message == "_restart": self.message_store.clear(cid) else: if len(_uuid) > 0: self.message_store.log( cid, cid, { "type": "text", "text": message.decode("utf-8") }, _uuid[0].decode("utf-8"), ) else: self.message_store.log(cid, cid, { "type": "text", "text": message.decode("utf-8") }) if len(_payload) > 0: self.on_message( UserMessage( _payload[0].decode("utf-8"), output_channel=BotServerOutputChannel(self.message_store), sender_id=cid, )) else: self.on_message( UserMessage( message.decode("utf-8"), output_channel=BotServerOutputChannel(self.message_store), sender_id=cid, ))
def say(cid): print(cid) print(request.args.get("message")) message = bytes(request.args.get("message", default="")) _payload = bytes(request.args.get("payload", default="")) _display_name = bytes(request.args.get("display_name", default="")) _uuid = bytes(request.args.get("uuid", default="")) logger.info(message) if len(_display_name) > 0 and self.agent: display_name, = _display_name tracker = self.agent.tracker_store.get_or_create_tracker(cid) if ( "display_name" in tracker.current_slot_values() and tracker.get_slot("display_name") != display_name ): tracker.update(SlotSet("display_name", display_name.decode("utf-8"))) self.agent.tracker_store.save(tracker) if message == "_restart": self.message_store.clear(cid) else: if len(_uuid) > 0: self.message_store.log( cid, cid, {"type": "text", "text": message.decode("utf-8")}, _uuid.decode("utf-8"), ) if len(_payload) > 0: on_new_message( UserMessage( _payload.decode("utf-8"), output_channel=BotServerOutputChannel(self.message_store), sender_id=cid, ), preprocessor=self.preprocessor ) else: on_new_message( UserMessage( message.decode("utf-8"), output_channel=BotServerOutputChannel(self.message_store), sender_id=cid, ), preprocessor=self.preprocessor ) return make_response("OK", 200)
def handle_reminder(self, reminder_event: LineReminderScheduled, dispatcher: LineDispatcher) -> None: """Handle a reminder that is triggered asynchronously.""" tracker = self._get_tracker(dispatcher.sender_id) if not tracker: logger.warning("Failed to retrieve or create tracker for sender " "'{}'.".format(dispatcher.sender_id)) return None if (reminder_event.kill_on_user_message and self._has_message_after_reminder(tracker, reminder_event) or not self._is_reminder_still_valid(tracker, reminder_event)): logger.debug("Canceled reminder because it is outdated. " "(event: {} id: {})".format( reminder_event.action_name, reminder_event.name)) else: # necessary for proper featurization, otherwise the previous # unrelated message would influence featurization tracker.update(UserUttered.empty()) # clear replied messages dispatcher.output_channel.clear_messages() dispatcher.reminder_data = reminder_event.data action = self._get_action(reminder_event.action_name) should_continue = self._run_action(action, tracker, dispatcher) if should_continue: user_msg = UserMessage(None, dispatcher.output_channel, dispatcher.sender_id) self._predict_and_execute_next_action(user_msg, tracker) # send push to line api dispatcher.output_channel.send_push() # save tracker state to continue conversation from this state self._save_tracker(tracker)
def event(): # Echo the URL verification challenge code if request.json.get('type') == "url_verification": return request.json.get('challenge'), 200 print(request.json) if request.json.get( 'token') == self.slack_client and request.json.get( 'type') == "event_callback": #verify token print(self.slack_client) print(self.slack_verification_token) payload = request.json data = payload messaging_events = data.get('event') channel = messaging_events.get('channel') user = messaging_events.get('user') text = messaging_events.get('text') bot = messaging_events.get('bot_id') if bot == None: #check if it's a new message from the user. Bot users will not have userids on_new_message( UserMessage( text, SlackBot(self.slack_verification_token, channel))) return Response(), 200
def _record_messages(self, on_message, max_message_limit=None): utils.print_color("Bot loaded. Type a message and press enter : ", utils.bcolors.OKGREEN) client = None my_user_name = '' self.client = SlackClient(self.token) self.client.rtm_connect() self.my_user_name = self.client.server.username print("Connected to Slack.") num_messages = 0 while max_message_limit is None or num_messages < max_message_limit: try: input = self.client.rtm_read() if input: for action in input: if self.debug_mode: print(action) if 'type' in action and action['type'] == "message": # Uncomment to only respond to messages addressed to us. # if 'text' in action # and action['text'].lower().startswith(self.my_user_name): #print(action['text']) text = action["text"] channel = action["channel"] #print("User said",text) # self.process_message(action) out_channel = SlackRTMOutputChannel( self.client, channel) on_message(UserMessage(text, out_channel)) num_messages += 1 else: sleep(1) except Exception as e: print("Exception: ", e.message)
def run_story_test(agent, domain, input_channel, sender_id, story): global failed utils.print_color('\n## ' + story['title'].upper(), utils.bcolors.OKBLUE) failed = False for index, step in enumerate(story['steps']): if failed is True: return failed utterance = step.pop(0) def on_response(response, recipient_id, proc): global failed if len(step) > 0: expected = step.pop(0) if response == expected: utils.print_color(" - {}".format(response), utils.bcolors.OKGREEN) else: utils.print_color(" - {} (exp: {})".format(response, expected), utils.bcolors.FAIL) utils.print_color("TEST CASE INTERRUPTED)".format(response, expected), utils.bcolors.FAIL) # _print_slot_values(proc, recipient_id) _restart_tracker(proc, recipient_id) failed = True else: utils.print_color(" - {} (not in case)".format(response), utils.bcolors.BOLD) utils.print_color(utterance, utils.bcolors.OKGREEN) input_channel.on_message( UserMessage(utterance, TestOutputChannel(on_response, domain, agent.processor), sender_id)) return failed
def send_message(self, text, sender_name, recipient_id, on_new_message): if sender_name != self.user: output_channel = RocketChatBot( self.user, self.password, self.server_url) user_msg = UserMessage(text, output_channel, recipient_id) on_new_message(user_msg)
def send_message(self, text, sender_name, recipient_id, on_new_message): if sender_name != self.user: user_msg = UserMessage(text, self.output_channel, recipient_id, input_channel=self.name()) on_new_message(user_msg)
def process_message(self, on_new_message, text, sender_id): """Slack retry to post messages up to 3 times based on failure conditions defined here: https://api.slack.com/events-api#failure_conditions """ retry_reason = request.headers.environ.get('HTTP_X_SLACK_RETRY_REASON') retry_count = request.headers.environ.get('HTTP_X_SLACK_RETRY_NUM') if retry_count and retry_reason in self.errors_ignore_retry: logger.warning("Received retry #{} request from slack" " due to {}".format(retry_count, retry_reason)) return Response(status=201, headers={'X-Slack-No-Retry': 1}) try: out_channel = SlackBot(self.slack_token, self.slack_channel) user_msg = UserMessage(text, out_channel, sender_id, input_channel=self.name()) on_new_message(user_msg) except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.error(str(e), exc_info=True) return make_response()
def handle_message(sid, data): output_channel = SocketIOOutput(sio, sid, self.bot_message_evt) ##convert audio message to text and pass it to the Rasa Core ds = Model('models_stt/output_graph.pbmm', 26, 9, 'models_stt/alphabet.txt', 500) fs, audio = wav.read('LDC93S1.wav') audio_length = len(audio) * (1 / 16000) message = ds.stt(audio, fs) if self.session_persistence: if not data.get("session_id"): logger.warning("A message without a valid sender_id " "was received. This message will be " "ignored. Make sure to set a proper " "session id using the " "`session_request` socketIO event.") return sender_id = data['session_id'] else: sender_id = sid message = UserMessage(data['message'], output_channel, sender_id, input_channel=self.name()) on_new_message(message)
def message(): payload = request.json print(f"Payload received: {payload}") sender_id = payload.get("sender", None) text = payload.get("message", None) try: if text == '/start': on_new_message( UserMessage('/start', out_channel, sender_id)) else: on_new_message(UserMessage(text, out_channel, sender_id)) except Exception as ex: logger.error(f'Exception trying to handle mesage: {ex}') return "success"
def compute(self, input, request_id, max_message_limit=None): if max_message_limit is None or num_messages < max_message_limit: if input == self.INTENT_MESSAGE_PREFIX + 'stop': return self.handler(UserMessage(input, self.outPutChannel, request_id)) self.num_messages += 1 return self.outPutChannel.output
def handle_message(sid, data): output_channel = SocketIOOutput(sio, self.bot_message_evt) message = UserMessage(data['message'], output_channel, sid, input_channel=self.name()) on_new_message(message)
def receive(): payload = json.loads(request.data) sender_id = payload['user']['userId'] intent = payload['inputs'][0]['intent'] text = payload['inputs'][0]['rawInputs'][0]['query'] if intent == 'actions.intent.MAIN': message = "<speak>Hello! <break time=\"1\"/> Welcome to the Google Assistant skill. You can start by saying hi." else: out = CollectingOutputChannel() on_new_message(UserMessage(text, out, sender_id)) responses = [m["text"] for m in out.messages] message = responses[0] r = json.dumps({ "conversationToken": "{\"state\":null,\"data\":{}}", "expectUserResponse": 'true', "expectedInputs": [{ "inputPrompt": { "initialPrompts": [{ "ssml": message }] }, "possibleIntents": [{ "intent": "actions.intent.TEXT" }] }] }) return r
def receive(): payload = request.json sender_id = payload.get("sender", None) text = payload.get("message", None) out = CollectingOutputChannel() # processor.MessageProcessor.handleMessage on_new_message(UserMessage(text, out, sender_id)) #tracker_store = TrackerStore() #tracker = tracker_store.get_or_create_tracker(sender_id) responses = [m for _, m in out.messages] recipes = [] for response in responses: search_recipes = SearchUtil.search({ 'q': response, 'portions': 2, 'fields': 'title,ingress,url,ingredients', 'size': 5 }) if len(search_recipes) > 0: recipes.append(search_recipes) if len(recipes) > 0: return jsonify(recipes) else: return jsonify(responses)
def webhook(): request.get_data() if request.json: output = request.json # splitting to get rid of the @botmention # trigger we are using for this text = output['text'].split(" ", 1) text = text[1] sender_id = output['user_id'] self.bot_channel = output['channel_id'] try: out_channel = MattermostBot(self.url, self.team, self.user, self.pw, self.bot_channel) user_msg = UserMessage(text, out_channel, sender_id, input_channel=self.name()) on_new_message(user_msg) except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.debug(e, exc_info=True) pass return make_response()
def event(): if request.json.get('type') == 'url_verification': logger.info( "SlackInput : Got a url_verification POST method call") return request.json.get('challenge'), 200 if request.json.get( 'token') == self.slack_client and request.json.get( 'type') == 'event_callback': data = request.json messaging_events = data.get('event') channel = messaging_events.get('channel') user = messaging_events.get('user') text = messaging_events.get('text') bot = messaging_events.get('bot_id') logger.info( "actual query from slack channel:\ndata=%s\messaging_event=%s\nchannel=%s\nuser=%s\ntext=%s\nbot=%s" % (str(data), str(messaging_events), str(channel), str(user), str(text), str(bot))) if bot == None: on_new_message( UserMessage( text, SlackBot(self.slack_verification_token, channel))) return Response(), 200
def webhook(): request.get_data() if request.json: output = request.json if "challenge" in output: return make_response(output.get("challenge"), 200, {"content_type": "application/json"}) elif self._is_user_message(output): text = output['event']['text'] sender_id = output.get('event').get('user') else: return make_response() elif request.form: output = dict(request.form) if self._is_button_reply(output): text = self._get_button_reply(output) sender_id = json.loads(output['payload'][0]).get( 'user').get('id') else: return make_response() else: return make_response() try: out_channel = SlackBot(self.slack_token) user_msg = UserMessage(text, out_channel, sender_id) on_new_message(user_msg) except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.error(e, exc_info=True) pass return make_response()
def webhook(): postdata = request.get_json(force=True) logger.info(json.dumps(postdata, indent=4)) try: if postdata["type"] == "message": out_channel = BotFramework(self.bf_id, self.bf_secret, postdata["conversation"], postdata["recipient"], postdata["serviceUrl"]) text = "" value = "" if postdata.get("value"): raw_value = postdata.get("value") # value = raw_value.get("value") value = raw_value else: if postdata.get("text"): text = postdata.get("text") user_msg = UserMessage( "{}{}".format(text, json.dumps(value)), out_channel, postdata["from"]["id"]) on_new_message(user_msg) else: logger.info("Not received message type") except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.error(e, exc_info=True) pass return "success"
def replace_last_intent(sender_id): """Replaces the last intent from the user in the tracker state with the one provided and executes the next actions.""" request_params = request_parameters() if 'intent' in request_params: intent = request_params.get('intent') else: return Response(jsonify(error="No intent parameter specified."), status=400, mimetype="application/json") tracker = agent().tracker_store.get_or_create_tracker(sender_id) while len(tracker.events) > 0 and not isinstance( tracker.events[-1], UserUttered): tracker.events.pop() if len(tracker.events) == 0: logger.debug("No user utterance in history of tracker") return jsonify(tracker.current_state()) user_utterance = tracker.events.pop() tracker.update( UserUttered(text=user_utterance.text, intent={ "name": intent, "confidence": 1.0, }, entities=user_utterance.entities)) out = CollectingOutputChannel() message = UserMessage(text=user_utterance.text, output_channel=out, sender_id=sender_id) processor = agent()._create_processor() processor._predict_and_execute_next_action(message, tracker) agent().tracker_store.save(tracker) response = { "responses": message.output_channel.messages, "confidence": 1, "alternatives": [], } # save utterance in training data for nlu file_path = "/app/nlu/" + os.environ[ "RASA_NLU_PROJECT_NAME"] + "/user_input/" + intent + ".md" add_intent_definition = False if not os.path.exists(file_path): add_intent_definition = True with open(file_path, "a") as file: if add_intent_definition: file.write("## intent:" + intent + "\n") file.write("- " + user_utterance.text + "\n") return jsonify(response)
async def on_message_wrapper(on_new_message, text, queue, sender_id): collector = QueueOutputChannel(queue) message = UserMessage(text, collector, sender_id, input_channel=BotServerInputChannel.name()) await on_new_message(message) await queue.put("DONE")
def receive(): payload = request.json sender_id = payload.get("sender", None) text = payload.get("message", None) out = CollectingOutputChannel() on_new_message(UserMessage(text, out, sender_id)) responses = [m for _, m in out.messages] return jsonify(responses)
def _record_messages(self, on_message): with io.open(self.file_name, 'r') as f: for i, line in enumerate(f): m = self.message_filter.match(line) if m is not None: message = m.group(1 if m.lastindex else 0) on_message(UserMessage(message, self.output_channel)) if self.max_messages is not None and i >= self.max_messages: break
def receive(): user = self.fetch_user(request) msg = request.json["message"] on_new_message( UserMessage(msg, CollectingOutputChannel(), sender_id=user["username"])) return jsonify({"status": "ok"})
def _record_messages(self, on_message): while True: if self.rocketchat_bot.logged_in and not self.message_queue.empty(): msg = self.message_queue.get() on_message( UserMessage(msg['msg'], self.rocketchat_bot, msg['rid']) ) else: self.rocketchat_bot.login()
def on_message_wrapper(on_new_message, text, queue, sender_id): collector = QueueOutputChannel(queue) message = UserMessage(text, collector, sender_id, input_channel=RestInput.name()) on_new_message(message) queue.put("DONE")
def receive(): print("Received POST Request on endpoint /app") print("Request ", request) payload = request.json print(payload) sender = payload.get("sender", None) text = payload["text"] print(text) on_new_message(UserMessage(text, self.out_channel, sender)) return "success"
async def process_message(self, on_new_message, text, sender_id): try: out_channel = WebexTeamsBot(self.token, self.room) user_msg = UserMessage(text, out_channel, sender_id, input_channel=self.name()) await on_new_message(user_msg) except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.error(str(e), exc_info=True)
def receive(): payload = json.loads(request.data) sender_id = payload["sender"] text = payload["message"] print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print(sender_id) print(text) out = CollectingOutputChannel() on_new_message(UserMessage(text, out, sender_id)) responses = [m for _, m in out.messages] return jsonify(responses)