-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.py
126 lines (104 loc) · 4.34 KB
/
bot.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
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
import telepot
import time
from elasticsearch import Elasticsearch
import os
import re
from flask import Flask, request
import action_providers
hello_words = ['привет', 'приветики', 'здарова', 'приветствую', 'здравствуйте', 'приффки',
'хай', 'хей', 'добрый', 'доброе', 'доброго']
bye_words = ['спасибо', 'ладно', 'ок', 'доброго', 'пока', 'свидания', 'встреч', 'спокойной',
'наилучшего', 'хорошо', 'отлично', 'спс']
hello_w = 'Здравствуйте. '
bye_w = ' Если ко мне вопросов больше нет, всего доброго, до свидания.'
app = Flask(__name__)
TELEGRAM_API_KEY = os.getenv('TELEGRAM_API_KEY')
bot = telepot.Bot(TELEGRAM_API_KEY)
ES_HOST = os.getenv('ES_HOST', default='localhost')
es = Elasticsearch([ES_HOST])
good = False
while not good:
good = False
time.sleep(1)
try:
while not es.ping():
print("Waiting for elasticsearch to launch...")
time.sleep(1)
good = True
except:
good = False
def answer_message(chat_id, text, telegram_message=None):
if (telegram_message):
print(action_providers.current_chat_handlers)
print(chat_id)
if (chat_id in action_providers.current_chat_handlers and
action_providers.current_chat_handlers[chat_id] is not None):
provider_name = action_providers.current_chat_handlers[chat_id]
provider_func = action_providers.providers_list[provider_name]
if telegram_message:
message = provider_func(chat_id, text, telegram_message, bot)
else:
message = provider_func(chat_id, text)
return message
if text in action_providers.providers_list:
provider_name = text
provider_func = action_providers.providers_list[provider_name]
if telegram_message:
message = provider_func(chat_id, text, telegram_message, bot)
else:
message = provider_func(chat_id, text)
return message
vq = re.split("[\'\"\:\-\.!?\s=\(\)]+", text)
text = " ".join([x.lower() for x in vq])
hello = False
bye = False
for h in hello_words:
if h in vq:
hello = True
for b in bye_words:
if b in vq:
bye = True
res = es.search(body={"query": {"query_string": {"query": text, "fields": ["question^3", "answer"]}}})
if (len(res['hits']['hits']) == 0 or res['hits']['hits'][0]['_score'] < 1.1):
if telegram_message is not None:
bot.sendSticker(chat_id,
'BQADAgADKwAD4mVWBHQ_r1atEEueAg')
return 'В данный момент я не могу ответить на ваш вопрос. Попробуйте позже.'
else:
ques = res['hits']['hits'][0]['_source']['question']
ans = res['hits']['hits'][0]['_source']['answer']
if hello:
ans = hello_w + ans
if bye:
ans += bye_w
score = res['hits']['hits'][0]['_score']
format_string = "{answer}"
formatted = format_string.format(rel=score, question=ques, answer=ans)
return formatted
def handle(msg):
chat_id = msg['chat']['id']
currently_handled_by_provider = (chat_id in action_providers.current_chat_handlers and
action_providers.current_chat_handlers[chat_id] is not None)
if 'text' not in msg and not currently_handled_by_provider:
bot.sendSticker(msg['chat']['id'],
'BQADAgADKwAD4mVWBHQ_r1atEEueAg')
bot.sendMessage(msg['chat']['id'],
'Извините, я могу отвечать только на текстовые сообщения.')
return
if ('text' in msg):
text = msg['text']
else:
text = None
ans = answer_message(chat_id, text, msg)
bot.sendMessage(chat_id, ans)
print(bot.getMe())
bot.message_loop(handle)
@app.route('/', methods=['POST'])
def handleHTTPRequest():
try:
dat = request.get_data().decode("utf-8")
return answer_message(0, dat)
except Exception as e:
print(e)
print('Listening ...')
app.run(host='0.0.0.0', port=8000)