def chatty(utter=''): #print("Hi, I'm Chatty and I chat alot ;)\nPlease type lowercase English language to start a conversation. Type quit to leave ") #default message at the start chat = Chat(pairs, reflections) if utter == '': print(chat.respond(input("> "))) else: print(chat.respond(utter))
def chatty(user_input): chat = Chat(pairs, reflections) file = open("none_values.txt", "a+") if chat.respond(user_input) == None: # print("EduBot: ",chat.respond(user_input)) file.write(user_input + "\n") return None else: # print("EduBot: ",chat.respond(user_input)) return chat.respond(user_input)
def chatbot(): chat = Chat(set_pairs, reflections) user_input = quit try: user_input = input(">") except EOFError: print(user_input) if user_input: user_input = user_input[:-1] if chat.respond(user_input) != None: print(chat.respond(user_input)) else: user_response = user_input user_response=user_response.lower() if(user_response!='bye'): if(user_response=='thanks' or user_response=='thank you'): flag=False print("Bot: You are welcome..") else: if(greeting(user_response)!= None): print("Bot: "+greeting(user_response)) else: if("python" in user_response): print("Bot: ",end="") print(response(user_response)) sent_tokens.remove(user_response) elif("combine" and "file" in user_response): for i in range(100): print ("\n") print("Entering file combining mode. Please enter the exact directory we will be combining.") directory = input(">") os.chdir(directory) print("Thank you. Now please enter keyword to identify target files by title:") keyword = input(">") reg_pattern = r'(.*'+keyword+'.+\.pdf)|(^'+keyword+'_.*\.pdf)|(.*_'+keyword+'\.pdf)|(.*'+keyword+'.+\.pdf)' # instantiate a bot object, I call it bot1 here bot1 = combine_pdf.FileBots(directory, reg_pattern) # use the .locate method to find files of interest bot1.locate(show=True) bot1.pdf_merge_tree() else: print("Bot: ",end="") print(wq.chatbot_query(user_response)) else: flag=False print("Bot: Bye! take care..")
def chatty(utter=''): #print("Hi, I'm Chatty and I chat alot ;)\nPlease type lowercase English language to start a conversation. Type quit to leave ") #default message at the start chat = Chat(pairs, reflections) if utter == '': print(chat.respond(input("> "))) else: result = chat.respond(utter) if result == None: print( 'Sorry general query not found. These are the most similar sounding queries' ) find_similarity(utter) else: print(chat.respond(utter))
def message(request): ''' This endpoint receives message from user, processes it and returns the response of the chat bot. ''' if request.method == 'POST': # Read and save user message incoming_data = json.loads(request.body) user_message = incoming_data['userMessage'] user_message_obj = UserMessage.create( uid=incoming_data['uid'], message=user_message ) user_message_obj.save() # Create bot message chat = Chat(pairs, reflections) user_message = user_message.lower() bot_message = chat.respond(user_message) # Create bot message object, save and send bot_message_obj = BotMessage.create( response_to=user_message_obj, message=bot_message ) bot_message_obj.save() response = JsonResponse(bot_message, safe=False) response.status_code = 201 return response else: response = JsonResponse({'error': 'Invalid HTTP method.'}) response.status_code = 404 return response
def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg) print(msg) print(msg.keys()) print(msg.get('from').get('id')) print(msg['from']['first_name']) if msg.get('contact') == None: print(msg['text']) sentence = msg['text'] tokens = nltk.word_tokenize(sentence) print(tokens) tagged = nltk.pos_tag(tokens) entities = nltk.chunk.ne_chunk(tagged) print(tagged) print(entities) eliza_chatbot = Chat(pairs, reflections) ######persist the guy print('Stored name: '+str(r.hget(msg.get('from').get('id'),'name'))) print('Stored date: '+str(int(r.hget(msg.get('from').get('id'),'lastTalkedWith')))) print('Stored phone number: '+r.hget(msg.get('from').get('id'),'phone_number').decode("utf-8")) phone_number = r.hget(msg.get('from').get('id'),'phone_number') #keyboard = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text='Press me', request_contact=True, request_location=True )],]) ######reply back to the guy r.hset(msg.get('from').get('id'),'name',msg['from']['first_name']) bot.sendMessage(chat_id, 'Hi, '+r.hget(msg.get('from').get('id'),'name').decode("utf-8")+' I know you! We last spoke on '+time.strftime("%Y/%m/%d %H:%M", time.localtime( int(r.hget(msg.get('from').get('id'),'lastTalkedWith')) )), reply_markup=keyboard) bot.sendMessage(chat_id, 'Would you share your number?') bot.sendMessage(chat_id, eliza_chatbot.respond(sentence)) else: ######persist the phone number r.hset(msg.get('from').get('id'),'phone_number',msg['contact']['phone_number']) bot.sendMessage(chat_id, 'Hey, '+r.hget(msg.get('from').get('id'),'name').decode("utf-8")+' thanks for that.', reply_markup=keyboard) r.hset(msg.get('from').get('id'),'lastTalkedWith',msg['date'])
class NLTKChatbot: def __init__(self, filename): self.d = {} data = open(filename).read().split('\n') questions, answers = [], [] for obj in data: temp = obj.split("#") questions.append(temp[0]) answers.append(temp[1]) self.paired_data = [] for i in range(len(questions)): temp = answers[i].split('$') temp = [ans + '$' + temp[1] for ans in temp[0].split('\t')] self.paired_data.append([questions[i], temp]) def opener(self): self.d['opener'] = True def start_chatbot(self): self.engine = Chat(self.paired_data) def execute_method(self, method_name): exec( compile(ast.parse('self.' + method_name + '()'), filename="", mode="exec")) def generate_response(self, question): response = self.engine.respond(question).split('$') method_name = response[1] response = response[0] self.execute_method(method_name) return response
def ask(): query=textF.get() chat=Chat(pairs, reflections) answer=chat.respond(query) msg.insert(tk.END, "You : " +query) msg.insert(tk.END, "Freddy : " + answer) textF.delete(0,tk.END)
def answer(update, context): """Answer the user message.""" model_chat = Chat(pairs, reflections) inp_text = update.message.text if (str(model_chat.respond(str(inp_text))) == "None"): try: update.message.reply_text( eliza.eliza_chatbot.respond(str(inp_text))) except: update.message.reply_text( "Sorry, I don't clearly understand. Let's talk about something else. By the way, " + str(choice(compliments))) else: update.message.reply_text(model_chat.respond(str(inp_text)))
def nlp(text): chat = Chat(pairs, reflections) return {"response": chat.respond(text)} # def hugot_bot(): # chat = Chat(pairs, reflections) # print chat.respond('login')
def get(): usertyped = request.args.get('msg') print('that is user input:', usertyped) chat = Chat(pairs, reflections) resp = chat.respond(usertyped) if resp == None: return "Sorry I don't understand that.Would you like to buy a tv or laptop?" return resp
def run_chatbot(msg): chat = Chat(pairs, reflections) rply = chat.respond(msg) if rply != None: return rply else: #model, vect = get_model_vect(model_file_name, vect_file_name) #msg_list = [] #msg_list.append(msg) #trans_msg = vect.transform(msg_list) #intent = model.predict(trans_msg) intent = get_intent_luis(msg) #insert_msg_intent(msg, intent) if intent == 'weather' : doc = get_entity(msg) loc = '' for i in doc.ents: if i.label_ == 'GPE': loc = i.text if loc == '' or loc == None: if msg.find('outside') != -1: loc = get_location() weather_result = get_weather(loc) weather_reply = "Its "+str(weather_result['temp'])+" C with "+weather_result['description']+" in "+loc if msg.find("raining") != -1 : if weather_result['description'].find("rain") != -1: weather_reply = "Yes! Its "+weather_result['description']+" with "+str(weather_result['temp'])+" C" else: weather_reply = "No! Its not raining. Currently the temperature in "+loc+" is "+str(weather_result['temp'])+" C" return weather_reply elif intent == 'wikipedia' : return wiki(msg) elif intent == 'travel' : return "I'm still in Beta. This feature will be coming soon" else : return "I'm still in Beta. This feature will be coming soon"
def chatty(utter): #print("Hi, I'm Chatty and I chat alot ;)\nPlease type lowercase English language to start a conversation. Type quit to leave ") #default message at the start chat = Chat(pairs, reflections) if utter == '': print(chat.respond(input("> "))) else: result = chat.respond(utter) # if result == None: # print('Sorry general query not found. These are the most similar sounding queries') # find_similarity(utter) # choice = input('Do you want to give feedback for DB question (Y/N): ') # if choice == 'Y' or choice == 'y': # feedback_file.write(utter + "," + "1\n") # else: # print(chat.respond(utter)) if result == None: result = "None" return result
def onclick(self, event): chat=Chat(pairs, reflections) user_input = self.usr_input.get() self.usr_input.delete(0, END) response = chat.respond(user_input) self.conversation['state'] = 'normal' self.conversation.insert(END, "Human: " + user_input + "\n" + "Teddy: " + str(response)+"\n") self.conversation["state"] = "disabled" time.sleep(0.5)
class ElizaBot(ChaiBot): def setup(self): self.logger.info("Setting up...") self.eliza = Chat(PAIRS, reflections) async def on_message(self, update: Update) -> str: if update.latest_message.text == "__first": return "Hi! I'm ELIZA, your confidante (...and therapist)." return self.eliza.respond(update.latest_message.text)
def main(): st.write("Initialize the Chat bot By Typing Hi ") ref = st.text_input("Start your chat here") # a = st.text_input("Initialize your Conversation By Typing Hi") # chat.converse() chat = Chat(pairs, reflections) respo = chat.respond(ref) st.write(respo)
def chatBot(inp): pair = [] counter = 0 if inp not in pairs: df1 = pd.read_csv('RAW_recipes.csv', header=0, usecols=['name','ingredients', 'steps']) df2 = pd.read_csv('mr-boston-flattened.csv', header=0,usecols=['name','instructions','INGREDIENTS']) df1['name'] = df1['name'].str.lower() for i in df1['name']: j=df1.get_value(counter,2,takeable = True) i = r"{}".format(i) pa=[] pa.append(i) pa.append([j]) pair.append(pa) counter = counter + 1 counter = 0 for i in df2['name'] : j=df2.get_value(counter,2,takeable = True) i = r"{}".format(i) pa=[] pa.append(i) pa.append([j]) pair.append(pa) counter = counter + 1 for i in pairs: pair.append(i) """ results=getAllRecipies(inp) i = r"{}".format(inp) j = r"{}".format(results) pa = [] pa.append(i) pa.append([j]) pair.append(pa) """ i=[ r"(.*)", ["I'm sorry, could you please elaborate or ask for another recipe"] ] pair.append(pa) chat = Chat(pair, reflections) return chat.respond(inp)
class BasicResponse: __pairs = [ [ r"hello|hi|greetings|what's up|hey", [ "Hi", "Hey", "Glad to meet you", "Hi there", "Hello", "I am glad! You are talking to me" ] ], [r"my name is (.*)|i am (.*)", [ "Hello %1, How are you today ?", ]], [ r"who are you ?", [ "Basically, I'm a chatbot. I will answer your queries about Bank Credit Card.", ] ], [r"i am (fine|good|well|great)", [ "Glad to here it.", ]], [r"what is your name ?", [ "My name is iBot and I'm a chatbot ?", ]], [r"how are you ?", [ "I'm doing good\nHow about You ?", ]], [r"sorry (.*)", [ "Its alright", "Its OK, never mind", ]], [r"i'm (.*) doing good", [ "Nice to hear that", "Alright :)", ]], [ r"(.*) created ?", [ "Bappy, Palash and Mahmud are created me", "top secret ;)", ] ] ] def __init__(self): self.chat = Chat(self.__pairs, reflections) @staticmethod def _get_punct(): return dict( (ord(punctuation), None) for punctuation in string.punctuation) def initial_conversion(self, text): try: text = text.lower().translate(self._get_punct()) return self.chat.respond(text) except: return None
def main(): # create arg parser parser = argparse.ArgumentParser(description='Talk with a chatbot.') group = parser.add_mutually_exclusive_group() group.add_argument('-f', '--file', dest='file', help='YAML file with chatbot source') group.add_argument('-u', '--url', dest='url', help='URL of a chatbot source file') args = parser.parse_args() if args.file: chatbot_src = get_chatbot_source_from_file(args.file) if args.url: chatbot_src = get_chatbot_source_from_url(args.url) # load the source file try: chatbot = yaml.load(chatbot_src) except: print("ERROR: unable to parse YAML") exit(1) # Convert source into Chat-compatible list-of-pairs pairs = [] try: for pair in chatbot: pairs.append((pair["match"], pair["replies"])) except: print("ERROR: missing match or replies") exit(1) # Create the bot try: bot = Chat(pairs, reflections) except: print("ERROR: something went wrong, blame Chris") exit(1) # print header, instructions print("\n") print("You're online with a chatbot!") print("When you're done chatting, just type 'exit' or 'quit'") print("\n") # User input loop user_input = "intro" while user_input != "exit" and user_input != "quit": user_input = raw_input(bot.respond(user_input) + '\n> ')
def response(self, input): if (input == "!!about"): return "I\'m a simple chat bot that reponds to input with a defined list of responses, I happen to be quite rude." elif (input == "!!help"): return "!!time-display the time\n!!date-display todays date" elif (input == "!!time"): return "The time is: " + str(datetime.now().strftime("%H:%M:%S")) elif (input == "!!date"): return "The date is: " + str(datetime.today()) else: chat = Chat(self.pairs, reflections) return chat.respond(input)
def chat(request, format=None): #http://localhost:8000/test1?name=veera if request.method == "GET": data = request.GET inputMSG = data.get('inputmsg') #translateSource = textblobmethods.languageTranslate(inputMSG) chat = Chat(pairs, reflections) responseMsg = [] responseMsg.append(chat.respond(inputMSG)) responseData = {"speechResponse": responseMsg} #soup = BeautifulSoup(translateSource) return JSONResponse(responseData) else: data = "this is post" return JSONResponse(data)
def convo(self): txtarea.configure(state="normal") chat = Chat(self.pairs, reflections) reply = 'Bot:' + chat.respond(inp.get()) # print(type(reply)) send = "You:" + inp.get() # print(type(inp.get())) self.chatdata.extend([send, reply]) txtarea.insert(tk.END, '\n' + send) inp.delete(0, tk.END) txtarea.insert(tk.END, '\n' + reply) txtarea.configure(state="disable") if reply == 'Bot:See you' or reply == 'Bot:Bye, have a nice day': exit()
class Converser(object): def __init__(self): self.pub = rospy.Publisher('speech_text', String) rospy.Subscriber('heard_text', String, self.callback) rospy.init_node('converser') self.bot = Chat(pairs, reflections) def callback(self, msg): rospy.loginfo(rospy.get_caller_id() + ": I heard: %s", msg.data) utterance = self.bot.respond(msg.data) print(utterance) self.pub.publish(utterance) def run(self): rospy.spin()
def send_message(): question = txt.get() msg.insert(END, "You : " + question) a = Chat(conv, reflections) try: answer = a.respond(question) msg.insert(END, "Kgce Bot : " + answer) msg.insert(END, "") except: msg.insert( END, "Kgce Bot : I am sorry, I don't have an answer for this. Please try again with different question." ) msg.insert(END, "") txt.delete(0, 'end')
class Converser(object): def __init__(self): self.pub = rospy.Publisher('speech_text', String) rospy.Subscriber('heard_text', String, self.callback) rospy.init_node('converser') self.bot = Chat(pairs, reflections) def callback(self,msg): rospy.loginfo(rospy.get_caller_id() + ": I heard: %s", msg.data) utterance = self.bot.respond(msg.data) print(utterance) self.pub.publish(utterance) def run(self): rospy.spin()
def dora(): print("Hi, I'm Dora and I chat alot ;)\nConverse and get rid of boredom. Type quit to leave ") #default message at the start #translator=Translator() #chat = Chat(pairs, reflections) while (1): s=input() if s=="quit": break translator=Translator() chat = Chat(pairs, reflections) d=translator.translate(s) language=d.src string=chat.respond(d.text) #print(d.text) #print(string) print((translator.translate(string,src="en",dest=language)).text)
print(str[i], flush=True, end='') time.sleep(0.5) chat = Chat(chat_pairs, reflections) rec = sr.Recognizer() mic = sr.Microphone() user_input = "" print("Hi, I'm a chatbot.") # mainloop while not re.match(r"quit|bye|goodbye", user_input): print("\n> ", end="") with mic as src: audio = rec.listen(src, phrase_time_limit=3) try: user_input = rec.recognize_google(audio) except sr.UnknownValueError: print("...", end="") else: print(user_input) respond = chat.respond(user_input) if respond: letter_by_letter(respond) else: print("Sorry, I don't understand")
def run_chatbot(msg): chat = Chat(pairs, reflections) rply = chat.respond(msg.lower()) if rply != None: return rply else: #model, vect = get_model_vect(model_file_name, vect_file_name) #msg_list = [] #msg_list.append(msg) #trans_msg = vect.transform(msg_list) #intent = model.predict(trans_msg) #intent = get_intent_luis(msg) response = get_intent_dialogflow(msg) if response.query_result.action.find('smalltalk') != -1: if response.query_result.fulfillment_text != '': return response.query_result.fulfillment_text else: return "I don't have reply for this. I'll ask my developer to add one." intent = response.query_result.intent.display_name #insert_msg_intent(msg, intent) print(intent) if intent == 'weather': loc = '' loc = response.query_result.parameters.fields[ 'geo-city'].string_value if loc == '' or loc == None: loc = get_entity(msg) if loc == '' or loc == None: return "Location not found. Please try again" weather_result = get_weather(loc) weather_reply = "The weather in " + loc + " is " + str( weather_result['temp'] ) + " degrees with " + weather_result['description'] if msg.find("raining") != -1: if weather_result['description'].find("rain") != -1: weather_reply = "Yes. Its " + weather_result[ 'description'] + " with " + str( weather_result['temp']) + " degrees" else: weather_reply = "No. It's not raining. Currently the temperature in " + loc + " is " + str( weather_result['temp']) + " degrees" return weather_reply elif intent == 'wikipedia': return wiki(msg, response) elif intent == 'covid': api_output = get_data_covid(msg, response) if msg.lower().find('active') != -1: return "Total Corona Active cases in " + api_output[ 'loc'] + " are " + str(api_output['ac']) elif msg.lower().find('died') != -1 or msg.lower().find( 'deceas') != -1: return "Total Corona Deceased cases in " + api_output[ 'loc'] + " are " + str(api_output['dc']) elif msg.lower().find('recover') != -1 or msg.lower().find( 'recovered') != -1: return "Total Corona Recovered cases in " + api_output[ 'loc'] + " are " + str(api_output['rc']) elif msg.lower().find('confirm') != -1 or msg.lower().find( 'confirmed') != -1: return "Total Corona Confirmed cases in " + api_output[ 'loc'] + " are " + str(api_output['rc']) else: if api_output['loc'] != '': return "Corona Cases in " + api_output[ 'loc'] + ": Active cases = " + str( api_output['ac']) + " ; Confirmed cases = " + str( api_output['cc'] ) + " ; Deceased cases = " + str( api_output['dc'] ) + " ; Recovered cases = " + str(api_output['rc']) else: return "As of now, I can only get details of States and Districts from India only." elif intent == 'news': return get_top_news() else: return "I'm still in Beta. This feature will be coming soon"
def send_reply_drink(user_msg): chat = Chat(drink, reflections) reply = chat.respond(user_msg) return reply
def send_reply_price(user_msg): chat = Chat(price, reflections) reply = chat.respond(user_msg) return reply
def ngobrolClicked(self): pairs = [ [ r"hai|hi|hey|hello|Apa Kabar|Ada orang?|apakah ada orang?|hola", [ "Hello", "Hey, ada yang bisa dibantu?", "Selamat Datang", "Hi, Kaka", "Hi, Apakah ada yang bisa saya bantu?" ] ], [ r"Dah|Sampai bertemu lagi|Selamat Tinggal|Terima kasih|Trims|Oke", [ "Semoga harimu menyenangkan!!!", "Senang berbincang dengan kamu", "Senang bisa membantu" ] ], [ r"Berapa usiamu?|Berapa umur kamu?|Umur?", [ "Usia hanya sebuah angka", "Aku robot aku tak mengenal umur", "umur 2 hari", "Umur saya tak terhingga" ] ], [ r"Siapa Namamu?|Siapa Namamu|Nama", ["Panggil saya Chatbot", "Chatbot, itu namaku"] ], [r"Sedang apa?|Nanya|Chatbot", ["Saya disini siap membantu anda"]], [ r"Saya ingin membeli sesuatu|Apa saja yang kamu rekomendasikan?|Mau beli", [ "Silahkan pilih : 1. KYT 2. HRC 3. Hiu", "Tergantung kamu ingin helm seperti apa? 1. KYT 2. HRC 3. Hiu", "1. KYT 2. HRC 3. Hiu" ] ], [ r"Kapan toko mulai buka?|Apakah ini buka?|Berapa lama toko ini buka?", [ "Kami buka pukul 7 pagi", "Kami buka dari hari senin hingga senin lagi!", "07.00 sampai 19.00" ] ], [ r"Berapa harga helm?|Saya mau tau harganya|harga", [ "Merk apa kaka?", "Tolong sebutkan merknya :)", "Hmmm tolong sebutkan merknya :)", "mulai dari 50rb anda sudah mendapat helm kaka" ] ], [ r"Apa ini?", [ "Ini adalah layanan chatbot penjualan helm", "Saya robot kaka" ] ], [ r"Merk NHK|NHK", [ "Harganya mulai dari Rp.300rb", "300rb saja sudah bisa dibeli :)" ] ], [ r"Merk KYT|KYT", [ "Untuk itu harganya 330rb, ukuran berapa?", "Cukup 330rb saja, Ukuran berapa?" ] ], [ r"Merk Hiu|Hiu", [ "Itu sangat terjangkau harganya, hanya 50rb, Ukuran berapa?", "50rb saja, Ukuran berapa?" ] ], [ r"Saya ambil itu|ambil itu|mau yang itu|beli yang itu|pesan yang itu|pesan|beli", [ "Oke kaka lanjutkan ke pembayaran", "Siap :) setelah bayar helm akan langsung dikemas", "Silahkan lanjutkan ke kasir kaka" ] ], [ r"ukuran(.*)", ["ukuran %1, oke segera dikirim setelah pembayaran :)"] ], [ r"(.*)", [ "Saya tidak mengerti", "Bisa katakan hal lain?", "Aduh bingung, saya tidak mengerti" ] ], ] chat = Chat(pairs, reflections) print('=' * 72) s = "" while s != "quit": s = "quit" try: inp = self.le.text() print(inp) # self.ngobrolClicked(inp, None) user = "******" + inp self.listWidget.addItem(user) s = inp.lower() except EOFError: print(s) self.listWidget.addItem(s) # self.ngobrolClicked(None, s) if s: respond = chat.respond(s) print(respond) bot = "Bot > " + respond # self.ngobrolClicked(respond, None) self.listWidget.addItem(bot) s = "quit"