async def message(request: Request): if request.method == "POST": if not out_channel.get_me()["username"] == self.verify: logger.debug( "Invalid access token, check it matches Telegram") return response.text("failed") update = Update.de_json(request.json, 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 response.text("success") sender_id = msg.chat.id try: if text == (INTENT_MESSAGE_PREFIX + USER_INTENT_RESTART): await on_new_message( UserMessage(text, out_channel, sender_id, input_channel=self.name())) await on_new_message( UserMessage( "/start", out_channel, sender_id, input_channel=self.name(), )) else: await 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 response.text("success")
async def webhook(request: Request): postdata = request.json try: if postdata["type"] == "message": out_channel = BotFramework( self.app_id, self.app_password, postdata["conversation"], postdata["recipient"], postdata["serviceUrl"], ) user_msg = UserMessage( postdata["text"], out_channel, postdata["from"]["id"], input_channel=self.name(), ) await 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.debug(e, exc_info=True) pass return response.text("success")
async def handle_text( self, text_message: Union[Text, Dict[Text, Any]], message_preprocessor: Optional[Callable[[Text], Text]] = None, output_channel: Optional[OutputChannel] = None, sender_id: Optional[Text] = UserMessage.DEFAULT_SENDER_ID, ) -> Optional[List[Dict[Text, Any]]]: """Handle a single message. If a message preprocessor is passed, the message will be passed to that function first and the return value is then used as the input for the dialogue engine. The return value of this function depends on the ``output_channel``. If the output channel is not set, set to ``None``, or set to ``CollectingOutputChannel`` this function will return the messages the bot wants to respond. :Example: >>> from rasa.core.agent import Agent >>> from rasa.core.interpreter import RasaNLUInterpreter >>> agent = Agent.load("examples/restaurantbot/models/current") >>> await agent.handle_text("hello") [u'how can I help you?'] """ if isinstance(text_message, str): text_message = {"text": text_message} msg = UserMessage(text_message.get("text"), output_channel, sender_id) return await self.handle_message(msg, message_preprocessor)
async def parse_message_using_nlu_interpreter( self, message_data: Text) -> Dict[Text, Any]: """ 解析数据 Handles message text and intent payload input messages. The return value of this function is parsed_data. Args: message_data (Text): Contain the received message in text or\ intent payload format. Returns: The parsed message. Example: {\ "text": '/greet{"name":"Rasa"}',\ "intent": {"name": "greet", "confidence": 1.0},\ "intent_ranking": [{"name": "greet", "confidence": 1.0}],\ "entities": [{"entity": "name", "start": 6,\ "end": 21, "value": "Rasa"}],\ } """ processor = self.create_processor() message = UserMessage(message_data) return await processor._parse_message(message)
async def message(request: Request): sender = request.form.get("From", None) text = request.form.get("Body", None) out_channel = TwilioOutput( self.account_sid, self.auth_token, self.twilio_number ) if sender is not None and message is not None: try: # @ signs get corrupted in SMSes by some carriers text = text.replace("¡", "@") await on_new_message( UserMessage( text, out_channel, sender, 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 else: logger.debug("Invalid message") return response.text("success")
async def handle_reminder( self, reminder_event: ReminderScheduled, sender_id: Text, output_channel: OutputChannel, nlg: NaturalLanguageGenerator, ) -> None: """Handle a reminder that is triggered asynchronously.""" tracker = self._get_tracker(sender_id) if not tracker: logger.warning("Failed to retrieve or create tracker for sender " "'{}'.".format(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()) action = self._get_action(reminder_event.action_name) should_continue = await self._run_action(action, tracker, output_channel, nlg) if should_continue: user_msg = UserMessage(None, output_channel, sender_id) await self._predict_and_execute_next_action(user_msg, tracker) # save tracker state to continue conversation from this state self._save_tracker(tracker)
async def process_message(self, request: Request, on_new_message, text, sender_id): """Slack retries 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.get("HTTP_X_SLACK_RETRY_REASON") retry_count = request.headers.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.text(None, 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()) 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) return response.text("")
async def webhook(request: Request): sender_id = await self._extract_sender(request) text = self._extract_message(request) collector = CallbackOutput(self.callback_endpoint) await on_new_message( UserMessage(text, collector, sender_id, input_channel=self.name())) return response.text("success")
async 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, input_channel=self.name()) await on_new_message(user_msg)
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)
async def log_message( self, message: UserMessage) -> Optional[DialogueStateTracker]: # preprocess message if necessary if self.message_preprocessor is not None: message.text = self.message_preprocessor(message.text) # we have a Tracker instance for each user # which maintains conversation state tracker = self._get_tracker(message.sender_id) if tracker: await self._handle_message_with_tracker(message, tracker) # save tracker state to continue conversation from this state self._save_tracker(tracker) else: logger.warning("Failed to retrieve or create tracker for sender " "'{}'.".format(message.sender_id)) return tracker
async def handle_message(sid, data): output_channel = SocketIOOutput(sio, sid, self.bot_message_evt) 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()) await on_new_message(message)
async def webhook(request: Request): output = request.json if output: # 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() ) await 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 response.text("")