This repository was archived by the owner on Oct 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathbase_message.py
More file actions
158 lines (134 loc) · 5.35 KB
/
base_message.py
File metadata and controls
158 lines (134 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define the core attributes/methods on a Message instance."""
import json
import requests
import time
class InvalidMessageTypeError(Exception):
"""Error raised when attribute values are set on a
Message instance which is not compatible with the
the msg_type attribute.
"""
def __init___(self, val):
self.value = val
def __str__(self):
return repr(self.value)
class MessageTypes(object):
"""Defines message types."""
USER = "user"
AGENT = "agent"
class Message(object):
"""Base Message. modified based on older version
Define attributes present on all variants of the Message Class.
"""
def __init__(self,
api_key="",
platform="",
message="",
intent="",
version="",
user_id="",
time_stamp=None):
self.api_key = api_key
self.platform = platform
self.message = message
self.intent = intent
self.version = version
self.user_id = user_id
self.not_handled = False
self.feedback = False
if time_stamp == None:
self.time_stamp = Message.get_current_timestamp()
self.type = MessageTypes.USER
@staticmethod
def get_current_timestamp():
"""Returns the current epoch with MS precision."""
return int(round(time.time() * 1e3))
@staticmethod
def get_content_type():
"""Returns the content-type for requesting against the Chatbase API"""
return {'Content-type': 'application/json', 'Accept': 'text/plain'}
def set_as_type_user(self):
"""Set the message as type user."""
self.type = MessageTypes.USER
def set_as_type_agent(self):
"""Set the message as type agent."""
self.type = MessageTypes.AGENT
def set_as_not_handled(self):
"""Set the message's not_handled attribute to True.
Will throw if the message is of type Agent. Only user-type
Messages can have the not_handled attribute as True.
"""
if self.type == MessageTypes.AGENT:
raise InvalidMessageTypeError(
'Cannot set not_handled as True when msg is of type Agent')
self.not_handled = True
def set_as_handled(self):
"""Set the message's not_handled attribute to False."""
self.not_handled = False
def set_as_feedback(self):
"""Set the message's feedback attribute to True.
Will throw if the message is of type Agent. Only user-type
Messages can have the feedback attribute as True.
"""
if self.type == MessageTypes.AGENT:
raise InvalidMessageTypeError(
'Cannot set feedback as True when msg is of type Agent')
self.feedback = True
def set_as_not_feedback(self):
"""Set the message's feeback attribute to False."""
self.feedback = False
def to_json(self):
"""Return a JSON version for use with the Chatbase API"""
return json.dumps(self, default=lambda i: i.__dict__)
def send(self):
"""Send the message to the Chatbase API."""
url = "https://chatbase.com/api/message"
return requests.post(url,
data=self.to_json(),
headers=Message.get_content_type())
class MessageSet(object):
"""Message Set. modified based on older version
Add messages to a set and send to the Batch API.
"""
def __init__(self,
api_key="",
platform="",
version="",
user_id=""):
self.api_key = api_key
self.platform = platform
self.version = version
self.user_id = user_id
self.messages = []
def new_message(self, intent="", message="", time_stamp=None):
"""Add a message to the internal messages list and return it"""
self.messages.append(Message(api_key=self.api_key,
platform=self.platform,
version=self.version,
user_id=self.user_id,
intent=intent,
message=message,
time_stamp=time_stamp))
return self.messages[-1]
def to_json(self):
"""Return a JSON version for use with the Chatbase API"""
return json.dumps({'messages': self.messages},
default=lambda i: i.__dict__)
def send(self):
"""Send the message set to the Chatbase API"""
url = ("https://chatbase.com/api/messages?api_key=%s" % self.api_key)
return requests.post(url,
data=self.to_json(),
headers=Message.get_content_type())