message.py
Go to the documentation of this file.
1 # Copyright 2017 Mycroft AI Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 import json
16 import re
17 from mycroft.util.parse import normalize
18 
19 
20 class Message:
21  """Holds and manipulates data sent over the websocket
22 
23  Message objects will be used to send information back and forth
24  between processes of Mycroft.
25 
26  Attributes:
27  type (str): type of data sent within the message.
28  data (dict): data sent within the message
29  context: info about the message not part of data such as source,
30  destination or domain.
31  """
32 
33  def __init__(self, type, data=None, context=None):
34  """Used to construct a message object
35 
36  Message objects will be used to send information back and fourth
37  bettween processes of mycroft service, voice, skill and cli
38  """
39  self.type = type
40  self.data = data or {}
41  self.context = context or {}
42 
43  def serialize(self):
44  """This returns a string of the message info.
45 
46  This makes it easy to send over a websocket. This uses
47  json dumps to generate the string with type, data and context
48 
49  Returns:
50  str: a json string representation of the message.
51  """
52  return json.dumps({
53  'type': self.type,
54  'data': self.data,
55  'context': self.context
56  })
57 
58  @staticmethod
59  def deserialize(value):
60  """This takes a string and constructs a message object.
61 
62  This makes it easy to take strings from the websocket and create
63  a message object. This uses json loads to get the info and generate
64  the message object.
65 
66  Args:
67  value(str): This is the json string received from the websocket
68 
69  Returns:
70  Message: message object constructed from the json string passed
71  int the function.
72  value(str): This is the string received from the websocket
73  """
74  obj = json.loads(value)
75  return Message(obj.get('type') or '',
76  obj.get('data') or {},
77  obj.get('context') or {})
78 
79  def reply(self, type, data=None, context=None):
80  """Construct a reply message for a given message
81 
82  This will take the same parameters as a message object but use
83  the current message object as a reference. It will copy the context
84  from the existing message object and add any context passed in to
85  the function. Check for a target passed in to the function from
86  the data object and add that to the context as a target. If the
87  context has a client name then that will become the target in the
88  context. The new message will then have data passed in plus the
89  new context generated.
90 
91  Args:
92  type (str): type of message
93  data (dict): data for message
94  context: intented context for new message
95 
96  Returns:
97  Message: Message object to be used on the reply to the message
98  """
99  data = data or {}
100  context = context or {}
101 
102  new_context = self.context
103  for key in context:
104  new_context[key] = context[key]
105  if 'target' in data:
106  new_context['target'] = data['target']
107  elif 'client_name' in context:
108  context['target'] = context['client_name']
109  return Message(type, data, context=new_context)
110 
111  def response(self, data=None, context=None):
112  """Construct a response message for the message
113 
114  Constructs a reply with the data and appends the expected
115  ".response" to the message
116 
117  Args:
118  data (dict): message data
119  context (dict): message context
120  Returns
121  (Message) message with the type modified to match default response
122  """
123  response_message = self.reply(self.type, data or {}, context)
124  response_message.type += '.response'
125  return response_message
126 
127  def publish(self, type, data, context=None):
128  """
129  Copy the original context and add passed in context. Delete
130  any target in the new context. Return a new message object with
131  passed in data and new context. Type remains unchanged.
132 
133  Args:
134  type (str): type of message
135  data (dict): date to send with message
136  context: context added to existing context
137 
138  Returns:
139  Message: Message object to publish
140  """
141  context = context or {}
142  new_context = self.context.copy()
143  for key in context:
144  new_context[key] = context[key]
145 
146  if 'target' in new_context:
147  del new_context['target']
148 
149  return Message(type, data, context=new_context)
150 
152  """
153  For intents get the portion not consumed by Adapt.
154 
155  For example: if they say 'Turn on the family room light' and there are
156  entity matches for "turn on" and "light", then it will leave behind
157  " the family room " which is then normalized to "family room".
158 
159  Returns:
160  str: Leftover words or None if not an utterance.
161  """
162  utt = normalize(self.data.get("utterance", ""))
163  if utt and "__tags__" in self.data:
164  for token in self.data["__tags__"]:
165  # Substitute only whole words matching the token
166  utt = re.sub(r'\b' + token.get("key", "") + r"\b", "", utt)
167  return normalize(utt)
def __init__(self, type, data=None, context=None)
Definition: message.py:33
def reply(self, type, data=None, context=None)
Definition: message.py:79
def publish(self, type, data, context=None)
Definition: message.py:127
def response(self, data=None, context=None)
Definition: message.py:111
def normalize(text, lang=None, remove_articles=True)
Definition: parse.py:281


mycroft_ros
Author(s):
autogenerated on Mon Apr 26 2021 02:35:40