-
Notifications
You must be signed in to change notification settings - Fork 3
/
chatbot.py
180 lines (156 loc) · 5.96 KB
/
chatbot.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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""Main program"""
from pywsd.utils import lemmatize_sentence
from searchData import search
from matchData import match
from numpy.random import choice
from googleSearch import google_search
import json
import requests
from telegram_bot import TelegramChatbot, speech2text
from time import sleep
from weather import currentWeather
with open("data/talk.json", "rb") as file:
greetDic = json.load(file)
file.close()
def greet(inpText):
"""This function creates a greeting
based on the input if required."""
global greetDic
flag = False
for key in greetDic.keys():
if " ".join(process(key)) in " ".join(process(inpText)):
randGreet = choice(greetDic[key], size=1)[0]
flag = True
bot.sendMessage(randGreet, from_)
return flag
def process(inpText):
"""This function lemmatizes
the input sentence."""
l = lemmatize_sentence(inpText, keepWordPOS=True)
return l[1]
update_id = None
bot = TelegramChatbot()
def getMessage(update_id, from_ = None):
# updates contains all the details about the latest message sent by user.
updates = bot.getUpdates(offset=update_id)
updates = updates["result"]
# Extracting required fields from updates.
if updates:
for item in updates:
# It helps us to fetch the latest message instead of the whole chat history.
update_id = item["update_id"]
# Contains all the details of the message.
try:
message = item["message"]
except:
message = item["edited_message"]
from_ = message["chat"]["id"] # chat_id of the user.
# text ---> text query from user.
# voice ---> voice message from user.
inputMsg = ""
# Handling the text input from user.
try:
inputMsg = message["text"].strip(" ")
except:
pass
# Handling voice input from user.
try:
file_id = message["voice"]["file_id"]
bot.downloadFile(file_id)
inputMsg = speech2text('query.wav').strip(" ")
print("User said:", inputMsg)
except:
pass
return inputMsg, update_id, from_
# Writing main loop.
mainFlag = True
altInpMsg = ''
while(mainFlag):
print("........")
# obtaining the input.
if altInpMsg == '':
inputMsg, update_id, from_ = getMessage(update_id, from_ = None)
inputMsg = inputMsg.strip()
else:
inputMsg = ' '.join(altInpMsg)
command = ""
try:
command = inputMsg.split()[0]
except:
pass
# checking if message is related to coding
# or not.
if command == "/start":
bot.sendMessage("Hi! Glad to know that you've chosen to take my help! What can I assist you with ?", from_)
altInpMsg = ''
elif command == "!code":
bot.sendMessage("Plese refer to the following link: ", from_)
bot.sendMessage(google_search(" ".join(inputMsg.split(" ")[1:])), from_)
altInpMsg = ''
elif command == "!faq":
ansMatch = match(inputMsg, "data/final_concat.csv")
bot.sendMessage(ansMatch, from_)
altInpMsg = ''
elif command == "!weather":
try:
city = " ".join(inputMsg.split()[1:])
bot.sendMessage(currentWeather(city), from_)
except Exception as e:
bot.sendMessage("Unable to process the request.", from_)
altInpMsg = ''
else:
processedMsg = process(inputMsg)
# greeting if needed.
greetFlag = greet(inputMsg)
# getting data to create an answer.
ans, altans1 = search(processedMsg, "data/abtCollege.json")
altans = dict()
for key in altans1:
altans[key.lower()] = altans1[key]
ans = "\n".join(list(ans))
# handling if only greet is present inside input.
if (ans == "" and greetFlag):
altInpMsg = ''
continue
elif (ans == "" and not greetFlag):
bot.sendMessage("Answer not found in main database...", from_)
bot.sendMessage("Do you want me to search in the Facebook groups of previous year and other sites like Quora ?", from_)
altInpMsg, update_id, from_ = getMessage(update_id, from_)
altInpMsg = altInpMsg.strip().lower().split()
if "yes" in altInpMsg or "yup" in altInpMsg:
ansMatch = match(inputMsg, "data/final_concat.csv")
bot.sendMessage(ansMatch, from_)
altInpMsg = ''
elif "no" in altInpMsg or "nope" in altInpMsg:
bot.sendMessage("Your choice.. I was just trying to help.", from_)
altInpMsg = ''
else:
continue
else:
bot.sendMessage(ans, from_)
randAltAns = choice(list(altans.keys()),
size=2, replace=False)
if len(altans) != 0:
QUES = "Do you wish to know more about "
# alternate answers
bot.sendMessage(QUES + ", ".join(randAltAns) + "?", from_)
altInpMsg, update_id, from_ = getMessage(update_id, from_)
altInpMsg = altInpMsg.strip().lower().split()
if ("yes" in altInpMsg):
string = ""
if len(altans1) != 0:
for w in randAltAns:
if w in altInpMsg:
string += altans[w] + "\n"
if string == "":
for w in randAltAns:
string += altans[w] + "\n"
if string != "":
bot.sendMessage("Okay! Here you go.", from_)
bot.sendMessage(string, from_)
altInpMsg = ''
elif ("no" in altInpMsg or "nope" in altInpMsg):
bot.sendMessage("Your choice.. I was just trying to help.", from_)
altInpMsg = ''
else:
continue