def webhook(self, request): manager = ChatManager() text = request.POST.get('message') payload = None if request.POST.get('payload'): payload = json.loads(request.POST.get('payload')) if not text and not payload: logging.warning("[Webchat] Neither text nor payload was provided") return False webchat_id = request.session["webchat_id"] msg_type = ChatMessage.BUTTON if payload else ChatMessage.MESSAGE raw_message = RawMessage(interface=self, raw_user_id=webchat_id, raw_conversation_id=webchat_id, conversation_meta={}, type=msg_type, text=text, payload=payload, timestamp=time.time()) self.on_message_received(raw_message) logging.info("[Webchat] Received raw message: %s", raw_message) run_async(manager.accept, raw_message=raw_message) return True
def message(): yield RawMessage(interface=_TestInterface(), raw_user_id="foo", raw_conversation_id="chat_id", conversation_meta={}, type="message", text="Hello world!", payload=None, timestamp=time())
def _parse_raw_message(self, event): timestamp = event['timestamp'] / 1000 user_id = event['sender']['id'] page_id = event['recipient']['id'] raw_conversation_id = user_id conversation_meta = {"page_id": page_id} text = None if 'postback' in event: payload = json.loads(event['postback']['payload']) type = ChatMessage.BUTTON elif 'message' in event: message = event['message'] type = ChatMessage.MESSAGE payload = None if 'text' in message: text = message['text'] # Parse payload from special messages if 'sticker_id' in message: payload = {'sticker_id': message['sticker_id']} if message['sticker_id'] in [ 369239383222810, 369239343222814, 369239263222822 ]: payload['intent'] = 'thumbs_up' elif 'attachments' in message: payload = {'current_location': [], 'attachment': []} for attachment in message['attachments']: if 'coordinates' in attachment['payload']: payload['current_location'].append({ 'value': attachment['title'], 'name': attachment['title'], 'coordinates': attachment['payload']['coordinates'] }) if 'url' in attachment['payload']: url = attachment['payload']['url'] # TODO: add attachment type by extension payload['attachment'].append({'value': url}) payload['intent'] = 'attachment' elif 'quick_reply' in message: payload = json.loads(message['quick_reply'].get('payload')) else: logging.warning( "Ignoring unrecognized Messenger webhook event: %s", event) return None return RawMessage(interface=self, raw_user_id=user_id, raw_conversation_id=raw_conversation_id, conversation_meta=conversation_meta, type=type, text=text, payload=payload, timestamp=timestamp)
def _parse_callback_query(self, callback): query_id = callback['id'] user_id = callback['from']['id'] chat_instance_id = callback['chat_instance'] # this isn't chat_id message = callback.get('message') data_key = callback.get('data') # TODO: sanitize if not message: logging.warning( "Ignoring telegram callback without original message") return None if not data_key: logging.warning("Ignoring telegram callback without data") return None chat_id = message['chat']['id'] message_id = message['message_id'] data = self._retrieve_callback(data_key) data = json.loads(data) # answer query to hide loading bar in frontend url = self.base_url + 'answerCallbackQuery' payload = {'callback_query_id': query_id} response = requests.post(url, data=payload) if not response.json()['ok']: logging.error( 'Error occurred while answering to telegram callback: {}'. format(response.json())) # hide keyboard with buttons (not quick replies) if self.should_hide_keyboard: url = self.base_url + 'editMessageReplyMarkup' payload = { 'chat_id': chat_id, 'message_id': message_id, 'reply_markup': '' } response = requests.post(url, data=payload) if not response.json()['ok']: logging.error( 'Error occurred while hiding telegram keyboard: {}'.format( response.json())) return RawMessage(interface=self, raw_user_id=user_id, raw_conversation_id=chat_id, conversation_meta={}, type=ChatMessage.BUTTON, text=None, payload=data, timestamp=time())
def test_accept(self, chat_mgr, mock_processor): chat_id = 'chat_id' message = RawMessage(interface=_TestInterface(), raw_user_id="foo", raw_conversation_id=chat_id, conversation_meta={}, type="message", text="Hello world!", payload=None, timestamp=time()) chat_mgr.accept(message) model = ChatConversation.objects.get(raw_conversation_id=chat_id, interface_name="test") assert mock_processor.called assert model is not None
def parse_raw_message(self, request): print(request) req_data = request['request'] type = req_data['type'] user_id = request['session']['user']['userId'] is_new_session = request['session'].get('new', False) timestamp = time() # int(req_data['timestamp']) entities = {} if type == 'LaunchRequest': entities['intent'] = [{ "value": self.greeting_intent, "source": self.name, "confidence": 1.0 }] elif type == 'IntentRequest': intent = req_data['intent']['name'] if intent == "AMAZON.FallbackIntent" and is_new_session: entities['intent'] = [{ "value": self.greeting_intent, "source": self.name, "confidence": 1.0 }] else: entities['intent'] = [{ "value": intent, "source": self.name, "confidence": 1.0 }] parsed_entities = self._parse_entities( req_data['intent'].get('slots')) entities.update(parsed_entities) elif type == 'SessionEndedRequest': pass message = RawMessage(interface=self, raw_user_id=user_id, raw_conversation_id=user_id, conversation_meta={}, type=ChatMessage.MESSAGE, text=None, payload=None, timestamp=timestamp) return message, entities
def parse_raw_message(self, request): print(request) utterance = request.get('utterance') user_id = request.get('user_id') timestamp = time() # int(req_data['timestamp']) if not user_id: raise Exception() message = RawMessage(interface=self, raw_user_id=user_id, raw_conversation_id=user_id, conversation_meta={}, type=ChatMessage.MESSAGE, text=utterance, payload=None, timestamp=timestamp) return message
def _parse_raw_message(self, message): chat_id = message['chat']['id'] user_id = message.get('from', {}).get( 'id') # empty for messages sent to channels meta = {} date = message['date'] text = None if 'text' in message: text = message['text'] # UTF-8, 0-4096 characters else: logging.warning("Ignoring unsupported telegram message") return None return RawMessage(interface=self, raw_user_id=user_id, raw_conversation_id=chat_id, conversation_meta=meta, type=ChatMessage.MESSAGE, text=text, payload=None, timestamp=date)