This repository has been archived by the owner on Feb 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
dialogflow.py
executable file
·64 lines (46 loc) · 2.03 KB
/
dialogflow.py
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
from handler.base_plugin import BasePlugin
import aiohttp
class DialogflowPlugin(BasePlugin):
__slots__ = ("prefixes", "client_token", "base_url", "base_version")
def __init__(self, client_token="6872cbf5cb1c4d1bb63a6fbed8678aff", prefixes=("",)):
"""Plugin for integrating Dialogflow."""
super().__init__()
self.prefixes = prefixes
self.client_token = client_token
self.base_url = "https://api.dialogflow.com/v1/query"
self.base_version = "20170712"
async def check_message(self, msg):
if msg.is_out or msg.is_forwarded:
return False
for prefix in self.prefixes:
if msg.text.startswith(prefix):
msg.meta["__text_wo_prefix"] = msg.text.replace(prefix, "", 1).strip()
return True
return False
async def process_message(self, msg):
headers = {
"Authorization": f"Bearer {self.client_token}",
}
body = {
"lang": "ru",
"contexts": ["chat"],
"query": msg.meta["__text_wo_prefix"],
"sessionId": str(self.api.get_current_id()) + "_" + str(msg.user_id),
}
params = {
"v": self.base_version
}
async with aiohttp.ClientSession() as sess:
async with sess.post(self.base_url, json=body, headers=headers, params=params) as resp:
resp_json = await resp.json()
code = resp_json.get("status", {}).get("code")
if code != 200:
if code == 429:
self.api.logger.warning("429 - too_many_requests")
elif code == 400:
self.api.logger.warning(str(code) + " - " + resp_json["status"]["errorDetails"])
return await msg.answer("Простите, я потерялся. Попробуйте позже.")
text = resp_json.get("result", {}).get("fulfillment", {}).get("speech")
if not text:
return await msg.answer("Я не понял.")
return await msg.answer(text)