def baseTest(): deepThought = ChatBot("deepThought") deepThought.set_trainer(ChatterBotCorpusTrainer) # 使用中文语料库训练它 deepThought.train("chatterbot.corpus.chinese") # 语料库 print(deepThought.get_response(u"很高兴认识你")) print(deepThought.get_response(u"嗨,最近如何?")) print(deepThought.get_response(u"复杂优于晦涩")) #语出 The Zen of Python print(deepThought.get_response(u"面对模棱两可,拒绝猜测的诱惑.")) print(deepThought.get_response(u"你叫什么名字?"))
def testAddTraining(): from chatterbot.trainers import ListTrainer deepThought = ChatBot("Training demo") deepThought.set_trainer(ListTrainer) deepThought.train([ u"嗳,渡边君,真喜欢我?", u"那还用说?", u"那么,可依得我两件事?", u"三件也依得", ]) print(deepThought.get_response(u"真喜欢我?")) #不必完全匹配 print(deepThought.get_response(u"那用说?"))
async def talk(self, ctx): """Command that implements the talk to the bot function. It uses ChatterBot, is a machine-learning based conversational dialog engine build in Python which makes it possible to generate responses based on collections of known conversations **Dependencies**: pip install chatterbot **Keyword arguments**: chatbot -- stores chatbot object ctx -- Context reference to get message tts -- Set to true for text to speed implementation """ chatbot = ChatBot("Ron Obvious") chatbot.train("chatterbot.corpus.english") msg = ctx.message.content print(msg) if msg.startswith('$talk'): msg = msg[6:] print(msg) reply = chatbot.get_response(msg) await self.bot.send_message(ctx.message.channel, reply, tts=True)
def test_training_with_unicode_characters(self): """ Ensure that the training method adds unicode statements to the database. """ import os bot = ChatBot("Test Bot2", database="unicode-database.db") conversation = [ u"¶ ∑ ∞ ∫ π ∈ ℝ² ∖ ⩆ ⩇ ⩈ ⩉ ⩊ ⩋ ⪽ ⪾ ⪿ ⫀ ⫁ ⫂ ⋒ ⋓", u"⊂ ⊃ ⊆ ⊇ ⊈ ⊉ ⊊ ⊋ ⊄ ⊅ ⫅ ⫆ ⫋ ⫌ ⫃ ⫄ ⫇ ⫈ ⫉ ⫊ ⟃ ⟄", u"∠ ∡ ⦛ ⦞ ⦟ ⦢ ⦣ ⦤ ⦥ ⦦ ⦧ ⦨ ⦩ ⦪ ⦫ ⦬ ⦭ ⦮ ⦯ ⦓ ⦔ ⦕ ⦖ ⟀", u"∫ ∬ ∭ ∮ ∯ ∰ ∱ ∲ ∳ ⨋ ⨌ ⨍ ⨎ ⨏ ⨐ ⨑ ⨒ ⨓ ⨔ ⨕ ⨖ ⨗ ⨘ ⨙ ⨚ ⨛ ⨜", u"≁ ≂ ≃ ≄ ⋍ ≅ ≆ ≇ ≈ ≉ ≊ ≋ ≌ ⩯ ⩰ ⫏ ⫐ ⫑ ⫒ ⫓ ⫔ ⫕ ⫖", u"¬ ⫬ ⫭ ⊨ ⊭ ∀ ∁ ∃ ∄ ∴ ∵ ⊦ ⊬ ⊧ ⊩ ⊮ ⊫ ⊯ ⊪ ⊰ ⊱ ⫗ ⫘", u"∧ ∨ ⊻ ⊼ ⊽ ⋎ ⋏ ⟑ ⟇ ⩑ ⩒ ⩓ ⩔ ⩕ ⩖ ⩗ ⩘ ⩙ ⩚ ⩛ ⩜ ⩝ ⩞ ⩟ ⩠ ⩢", ] bot.train(conversation) response = bot.get_response(conversation[1]) os.remove("unicode-database.db") self.assertEqual(response, conversation[2])
def test_training_adds_statements(self): """ Test that the training method adds statements to the database. """ import os bot = ChatBot("Test Bot2", database="test-database-2") conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm great.", "That is good to hear", "Thank you.", "You are welcome.", "Sure, any time.", "Yeah", "Can I help you with anything?" ] bot.train(conversation) response = bot.get_response("Thank you.") os.remove("test-database-2") self.assertEqual(response, "You are welcome.")
class Bot: def __init__(self, session): self.session = session self.chatbot = ChatBot(session) self.training() print session, " Initialized!" def training(self): # Train based on the english corpus print "Training . . ." self.chatbot.train("chatterbot.corpus.english") self.chatbot.train("chatterbot.corpus.italian") def getSession(self): print self.session return self.session # def getCreateDate(): # return self.createDate def getResponse(self, msg): response = self.chatbot.get_response(msg) return response
def gente_reply(request): if request.is_ajax(): a = "sa" chatbot = ChatBot("Robbo") message = request.POST["message"] if message[0:6]=="#info ": ulter_message = message[6:len(message)] if ulter_message != "" and ulter_message != " ": url = "https://en.wikipedia.org/wiki/" + ulter_message data = requests.get(url) soup = BeautifulSoup(data.content) send_data = soup.find("p") reply = send_data.text else: reply = "#info message" else: reply = chatbot.get_response(message) print reply response_data = {} response_data["message"] = reply print response_data return HttpResponse(json.dumps(response_data)) else: return HttpResponse("Error")
class TkinterGUIExample(tk.Tk): def __init__(self, *args, **kwargs): ''' Create & set window variables. ''' tk.Tk.__init__(self, *args, **kwargs) self.chatbot = ChatBot("No Output", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapters=[ "chatterbot.adapters.logic.ClosestMatchAdapter" ], input_adapter="chatterbot.adapters.input.VariableInputTypeAdapter", output_adapter="chatterbot.adapters.output.OutputFormatAdapter", database="../database.db" ) self.title("Chatterbot") self.initialize() def initialize(self): ''' Set window layout. ''' self.grid() self.respond = ttk.Button(self, text='Get Response', command=self.get_response) self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3) self.usr_input = ttk.Entry(self, state='normal') self.usr_input.grid(column=1, row=0, sticky='nesw', padx=3, pady=3) self.conversation_lbl = ttk.Label(self, anchor=tk.E, text='Conversation:') self.conversation_lbl.grid(column=0, row=1, sticky='nesw', padx=3, pady=3) self.conversation = ScrolledText.ScrolledText(self, state='disabled') self.conversation.grid(column=0, row=2, columnspan=2, sticky='nesw', padx=3, pady=3) def get_response(self): ''' Get a response from the chatbot & display it. ''' user_input = self.usr_input.get() self.usr_input.delete(0, tk.END) response = self.chatbot.get_response(user_input) self.conversation['state'] = 'normal' self.conversation.insert( tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(response.text) + "\n" ) self.conversation['state'] = 'disabled' time.sleep(0.5)
class TkinterGUIExample(tk.Tk): def __init__(self, *args, **kwargs): """ Create & set window variables. """ tk.Tk.__init__(self, *args, **kwargs) self.chatbot = ChatBot( "GUI Bot", storage_adapter="chatterbot.storage.SQLStorageAdapter", logic_adapters=[ "chatterbot.logic.BestMatch" ], database_uri="sqlite:///database.db" ) self.title("Chatterbot") self.initialize() def initialize(self): """ Set window layout. """ self.grid() self.respond = ttk.Button(self, text='Get Response', command=self.get_response) self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3) self.usr_input = ttk.Entry(self, state='normal') self.usr_input.grid(column=1, row=0, sticky='nesw', padx=3, pady=3) self.conversation_lbl = ttk.Label(self, anchor=tk.E, text='Conversation:') self.conversation_lbl.grid(column=0, row=1, sticky='nesw', padx=3, pady=3) self.conversation = ScrolledText.ScrolledText(self, state='disabled') self.conversation.grid(column=0, row=2, columnspan=2, sticky='nesw', padx=3, pady=3) def get_response(self): """ Get a response from the chatbot and display it. """ user_input = self.usr_input.get() self.usr_input.delete(0, tk.END) response = self.chatbot.get_response(user_input) self.conversation['state'] = 'normal' self.conversation.insert( tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(response.text) + "\n" ) self.conversation['state'] = 'disabled' time.sleep(0.5)
def response(a): chatbot = ChatBot("Ron Obvious") chatbot.set_trainer(ChatterBotCorpusTrainer) chatbot.train("chatterbot.corpus.english") b = str(chatbot.get_response(a)) return b
class TuringTests(TestCase): def setUp(self): from chatterbot import ChatBot self.chatbot = ChatBot('Agent Jr.') @expectedFailure def test_ask_name(self): response = self.chatbot.get_response( 'What is your name?' ) self.assertIn('Agent', response.text) @expectedFailure def test_repeat_information(self): """ Test if we can detect any repeat responses from the agent. """ self.fail('Condition not met.') @expectedFailure def test_repeat_input(self): """ Test what the responses are like if we keep giving the same input. """ self.fail('Condition not met.') @expectedFailure def test_contradicting_responses(self): """ Test if we can get the agent to contradict themselves. """ self.fail('Condition not met.') @expectedFailure def test_mathematical_ability(self): """ The math questions inherently suggest that the agent should get some math problems wrong in order to seem more human. My view on this is that it is more useful to have a bot that is good at math, which could just as easily be a human. """ self.fail('Condition not met.') @expectedFailure def test_response_time(self): """ Does the agent respond in a realistic amount of time? """ self.fail('Condition not met.')
class Bot(object): def __init__(self, config_file): config = json.load(open(config_file)) self.chatbot = ChatBot( 'Robot Overload', io_adapter='chatterbot.adapters.io.NoOutputAdapter', database=config['database']) self.chatbot.train('chatterbot.corpus.english') self.chatbot.train('chatterbot.corpus.english.greetings') self.chatbot.train('chatterbot.corpus.english.conversations') self.token = config['token'] self.bot_id = config['bot_id'] self.slack_client = None def connect(self): self.slack_client = SlackClient(self.token) self.slack_client.rtm_connect() self.last_ping = 0 def start(self): self.connect() while True: for reply in self.slack_client.rtm_read(): self.input(reply) self.autoping() time.sleep(.1) def input(self, data): text = data.get('text', '') if data.get('type') == 'message' and self.bot_id in text: channel = data['channel'] text = text.replace(self.bot_id, '') response = self.chatbot.get_response(text) self.output([channel, response]) def output(self, output): limiter = False channel = self.slack_client.server.channels.find(output[0]) if channel != None and output[1] != None: if limiter == True: time.sleep(.1) limiter = False message = output[1].encode('ascii','ignore') channel.send_message("{}".format(message)) limiter = True def autoping(self): now = int(time.time()) if now > self.last_ping + 3: self.slack_client.server.ping() self.last_ping = now
class reply_engine: bot = None def init(self): self.bot = ChatBot( "Lisa", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter", io_adapter="chatterbot.adapters.io.NoOutputAdapter", database="../database.db", ) self.bot.train("chatterbot.corpus.english") def get_reply(self, data): return self.bot.get_response(data)
class Chatbrain (): def __init__(self): self.brain = ChatBot("Adolfo", storage_adapter = "chatterbot.adapters.storage.MongoDatabaseAdapter", logic_adapters=["chatterbot.adapters.logic.EvaluateMathematically", #"chatterbot.adapters.logic.TimeLogicAdapter"]) "chatterbot.adapters.logic.ClosestMatchAdapter"], io_adapter="chatterbot.adapters.io.SelectiveAdapter") self.brain.train("chatterbot.corpus.Portuguese.conversations_pt-BR") def respond(self, textin): return self.brain.get_response(textin) def read(self, inputc): self.brain.io.process_input(statement=inputc)
class GoodFoodBot: def __init__(self): self.bot = ChatBot('Good Food Bot') print 'start training' # Train based on the english conversations corpus print 'finished training' def train_bot(self): chunks = self.get_chunks(self.clean_dataset, 100) print 'start chunk training' for chunk, i in chunks: self.bot.train(chunk) print 'finished chunk %s' % i print 'finished training with movie_lines' def clean_dataset(self): n = path.join(path.dirname(__file__), 'data/movie_lines.txt') file = open(n, 'r') array = file.read().split('\n') mapped_arr = map(lambda txt: txt.split(' +++$+++ ')[-1:][0], array[0:1000]) return mapped_arr def format_data(self, arr): return map(lambda txt: txt.split(' +++$+++ ')[-1:][0], arr) def get_response(self, text): return self.bot.get_response(text) def get_chunks(self, arr, n): # Declare some empty lists chunk = [] chunks = [] # Step through the data n elements # at a time for x in range(0, len(arr), n): # Extract n elements chunk = arr[x:x+n] # Add them to list chunks.append(chunk) # Return the new list return chunks
class TalkManager: """ Class Managing the discussions held by Ariia and her training. """ def __init__(self): """ Constructor """ self.ariiaTalker = ChatBot("Ariia") self.talk = None self.ariiaTalker.set_trainer(ListTrainer) self.ariiaTalker.train([ "comment vas-tu", "ça va bien merci, et toi ?", "très bien !", "moi ça va.", "je suis en pleine forme !", ]) self.ariiaTalker.train([ "comment tu t'appelles", "Ariia", ]) self.ariiaTalker.train([ "qui est ton Créateur", "un programmeur du dimanche.", ]) def getTalk(self, dialog): """ Specify the speech answering the user's dialog Parameters : dialog - The dialog held by the user """ self.talk = unicode(self.ariiaTalker.get_response(dialog)) self.talk = self.talk.encode('utf-8') print type(self.talk) return self.talk
def post(self, request, *args, **kwargs): """ Return a response to the statement in the posted data. """ input_data = json.loads(request.read().decode('utf-8')) #self.validate(input_data) #print "******* input_data : " + json.dumps(input_data) print "******* input_data : " + input_data.get("text") chatbot = ChatBot( 'tony bot 01', logic_adapters=[ { 'import_path': 'chatterbot.logic.BestMatch' }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.33, 'default_response': u'그 질문에 대해서는 내가 대답해 줄 수 있는 게 없어. || 해당 질문에 대답하기를 원한다면 다음 링크를 통해서 너의 의견을 제안해 주면 고맙겠어. || <a href="http://35.189.163.55:8080/anemo/trainingUI/chatterbot_UI.html">임시 학습 페이지 링크</a>' } ], trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) # Train based on the english corpus chatbot.train("/Users/kimtony/workspace/anemonlp/AnemoNLP/App/MLBot/chatterbot/corpus") #conversation = self.get_conversation(request) #response = self.chatterbot.get_response(input_data, conversation.id) #response_data = response.serialize() response = unicode(chatbot.get_response(input_data)).encode("utf8") print "******* response : " + response response_data = { 'text': response } return JsonResponse(response_data, status=200)
class Conversation(Adaptor): def __init__(self, options): super(Conversation, self).__init__(options) if 'logic_adapters' not in options: options["logic_adapters"] = [ "chatterbot.adapters.logic.ClosestMatchAdapter", "chatterbot.adapters.logic.EvaluateMathematically", "chatterbot.adapters.logic.TimeLogicAdapter" ] self.chatbot = ChatBot("Salvius", **options) self.chatbot.train( "chatterbot.corpus.english" ) def respond(self, text): return self.chatbot.get_response(text)
class Chatter: """ Chatter is the core class involved with the integration with ChatterBot. It handles abstracting all interactions with ChatterBot. """ def __init__(self): self.chat_bot = ChatBot( 'JenkiesBot', storage_adapter='chatterbot.adapters.storage.JsonDatabaseAdapter', logic_adapters=[ 'chatterbot.adapters.logic.ClosestMeaningAdapter', 'chatterbot.adapters.logic.ClosestMatchAdapter' ], database='./chat-storage.json') # Training self.chat_bot.set_trainer(ChatterBotCorpusTrainer) self.train_from_corpa() def train_from_corpa(self): """ Trains the ChatterBot instance.""" self.chat_bot.train('chatterbot.corpus.english') self.chat_bot.train('.corpa') def add_axiom(self, statement: str, responses: str): """ Adds the user's supplied axiom to the axiom file.""" def update_axiom_json(json_file_contents: dict) -> dict: """ Used as the call back for add_axiom()'s call to update_json_file. Describes how we should add a new axiom to our training corpa json file. """ json_file_contents['axioms'].append([ statement ] + responses) return json_file_contents update_json_file('../corpa/training-corpa.json', update_axiom_json) # Retraining is required now! self.train_from_corpa() def get_reply(self, message): """ Abstracts away the to our bots method for retrieving a repsonse.""" return self.chat_bot.get_response(message)
def wake_hope(name="Hope", human_name="", loglevel=logging.INFO, database=DB_PATH): name = name or 'Hope' human_name = human_name or getpass.getuser().title() loglevel = loglevel or logging.INFO database = database or DB_PATH logging.basicConfig(level=loglevel, stream=sys.stdout) bot = ChatBot( "Terminal", storage_adapter="chatterbot.adapters.storage.django_storage.DjangoStorageAdapter", logic_adapters=[ "chatterbot.adapters.logic.MathematicalEvaluation", "chatterbot.adapters.logic.TimeLogicAdapter", "chatterbot.adapters.logic.ClosestMatchAdapter" ], input_adapter="chatterbot.adapters.input.TerminalAdapter", output_adapter="chatterbot.adapters.output.TerminalAdapter", database=database, ) now = datetime.datetime.now() today = datetime.datetime(*now.timetuple()[:3]) noon = datetime.datetime(*now.timetuple()[:3]) + datetime.timedelta(.5) # midnight = noon + datetime.timedelta(.5) # noqa early_morn = today + datetime.timedelta(3. / 24.) evening = today + datetime.timedelta(18. / 24.) tod = 'morning' if early_morn < now < noon else ('afternoon' if noon <= now < evening else 'evening') print("Good {}{}.".format(tod, '' if not human_name else ' ' + human_name)) while True: try: # TerminalAdapter doesn't require any args bot_input = bot.get_response(None) print(colored(str(bot_input) + '\r', 'yellow')) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
class reply_engine: bot = None def init(self): self.bot = ChatBot( "Lisa", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter", io_adapter="chatterbot.adapters.io.NoOutputAdapter", database="database/database.db", ) def get_reply(self, data): return self.bot.get_response(data) def train(self): trainingData = [] print "Input Converstion" while True: data = raw_input() if data == "#": break trainingData.append(data) self.bot.train(trainingData)
bot1 = ChatBot("Chicken") bot2 = ChatBot("Duck") bot1.gg() bot1 = ChatBot("Chicken") bot1.train("chatterbot.corpus.english") bot2.train("chatterbot.corpus.test") #bot1.train("chatterbot.corpus.test") response2="What's slappin'?" count = 0 count2 = 0 chicken = 1 if chicken==1: while True: count = count + 1 time.sleep(2) response1=bot1.get_response(response2) if len(response1)<50: response1=response1+" "+bot1.get_response(response1) response2=bot2.get_response(response1) print "Bot1:"+response1 time.sleep(2) print "Bot2:"+response2 elif chicken==2: while True: response1=bot1.get_response(raw_input(" ")) print response1 elif chicken==3: i = 0 while i < 50: response1=bot1.get_response("absolutely I agree with the") print response1
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot( 'Charlie', trainer='chatterbot.trainers.ListTrainer' ) chatbot.train([ "Hi, can I help you?", "Sure, I'd to book a flight to Iceland.", "Your flight has been booked." ]) # Get a response to the input text 'How are you?' response = chatbot.get_response('I would like to book a flight.') print(response)
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new chat bot named Charlie chatbot = ChatBot('Charlie', trainer='chatterbot.trainers.ListTrainer') chatbot.train([ "Hi, can I help you?", "Sure, I'd like to book a flight to Iceland.", "Your flight has been booked." ]) # Get a response to the input text 'I would like to book a flight.' response = chatbot.get_response('I would like to book a flight.') print(response)
# -*- coding: utf-8 -*- # chatterBot from chatterbot.trainers import ListTrainer from chatterbot import ChatBot # operacional system biblioteca import os bot = ChatBot('Bot') # bot bot.set_trainer(ListTrainer) # definindo metodo de treinamento for arq in os.listdir('chat'): serie = open('chat/' + arq, 'r').readlines() # lendo arquivos de conversas bot.train(serie) # treinando while True: # loop de conversação entrada = input('Você: ') # entrada do usuário saida = bot.get_response(entrada) # resposta do bot if (float(saida.confidence) > 0.5): # nível de confiança para responder: 5% print('Bot: ', saida) else: print('Bot: Não sei responder, por favor, me explique ...')
"Do u know stephen Hawkins?", "Dr.Hawkins is a famous physicist, who doesn't know him?", "Hmm", "Hmm" ] trainer = ListTrainer(chatbot) trainer.train(Conversation) from chatterbot.trainers import ChatterBotCorpusTrainer trainer = ChatterBotCorpusTrainer(chatbot) trainer.train("chatterbot.corpus.english") while True: try: message = input('You : ') if message.strip() == 'Bye' or message.strip( ) == 'bye' or message.strip() == 'exit' or message.strip == 'stop': print('Xavier : Have a good day.') break else: reply = chatbot.get_response(message) print('Xavier :', reply) output = gTTS(text=reply, lang=language) output.save("speech.mp3") os.system('start speech.mp3') except (KeyboardInterrupt, EOFError, SystemExit): print('Some Error occured') break
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chat = ChatBot('cctmx') trainer = ChatterBotCorpusTrainer(chat) trainer.train("chatterbot.corpus.spanish.greetings") while True: peticion = input('Tu: ') respuesta = chat.get_response(peticion) print('Bot: ', respuesta)
from chatterbot import ChatBot # Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) # Create a new instance of a ChatBot bot = ChatBot('SQLMemoryTerminal', storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', 'chatterbot.logic.TimeLogicAdapter', 'chatterbot.logic.BestMatch' ]) print('Type something to begin...') # The following loop will execute each time the user enters input while True: try: user_input = input() bot_response = bot.get_response(user_input) print(bot_response) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer chatbot = ChatBot("Bach Van Ngoc", silence_performance_warning=True, trainer="chatterbot.trainers.ChatterBotCorpusTrainer") chatbot.train("chatterbot.corpus.english") response = chatbot.get_response("Hello, how old are you?") print chatbot.get_response("I have a question.") conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you", "You're welcome." ] chatbot.set_trainer(ListTrainer) chatbot.train(conversation) print chatbot.get_response("Good morning") print chatbot.get_response("What's your name?")
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer try: bot = ChatBot("Chatterbot", storage_adapter="chatterbot.storage.SQLStorageAdapter", logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', 'chatterbot.logic.LowConfidenceAdapter', 'chatterbot.logic.BestMatch', 'metro_logic.MyLogicAdapter', 'wiki_logic.MyWikiLogic' ]) # bot.set_trainer(ChatterBotCorpusTrainer) # bot.train("chatterbot.corpus.spanish") except Exception as e: print(e) while True: try: userText = input('-->') print(bot.get_response(userText)) except Exception as e: print(e)
def voz(text): v.say(text) v.runAndWait() r = sr.Recognizer() with sr.Microphone() as s: r.adjust_for_ambient_noise(s) print('Diga Alguma Coisa!') try: while True: audio = r.listen(s) speech = recognize_pt(audio) response = bot.get_response(speech) print('Você Disse: ', speech) print('Bob: ', response) voz(response) except: trace = traceback.format_exc() voz('Erro.') finally: print(trace) # bot.set_trainer(ListTrainer) # for _file in os.listdir('chats'): # lines = open('chats/' + _file, 'r').readlines() # bot.train(lines)
from chatterbot import ChatBot bot = ChatBot("Math & Time Bot", logic_adapters=[ "chatterbot.logic.MathematicalEvaluation", "chatterbot.logic.TimeLogicAdapter" ], input_adapter="chatterbot.input.VariableInputTypeAdapter", output_adapter="chatterbot.output.OutputAdapter") response = bot.get_response("what is 4+9?") print(response) reponse = bot.get_response("time is ") print(response)
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome.", "Hi, can I help you?", "Sure, I'd like to book a flight to Iceland.", "Your flight has been booked." ] # Create a new chat bot named Charlie chatbot = ChatBot('Charlie') # Create a new Trainer trainer = ListTrainer(chatbot) trainer.train(conversation) # Get a response to the input text 'Good morning.' response = chatbot.get_response("Good morning!") print(response) # Get a response to the input text 'I would like to book a flight.' response = chatbot.get_response('I would like to book a flight.') print(response)
from chatterbot.storage import SQLStorageAdapter from chatterbot import ChatBot chatbot = ChatBot("Ron Obvious") from chatterbot.trainers import ListTrainer conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome." ] trainer = ListTrainer(chatbot) trainer.train(conversation) response = chatbot.get_response("Good morning!") print(response)
# Pyggy responds (pandorabot) result = API.talk(user_key, app_id, host, botname, text1, session_id=True, recent=True) text2 = result['response'] # time.sleep(0.1) speak_response(text2, 'Rosie') # Save the back and forth to the CSV log writer.writerow([time.time(),text1,text2]) csvfile.flush() # Fiona updates what to say next (random choice of bot seed) coin = random.random() highLim = 0.99 lowLim = 0.01 if coin > highLim: result = API.talk(user_key, app_id, host, botname, text1, session_id=True, recent=True) text1 = result['response'] elif coin < highLim and coin > lowLim: text1 = bot.get_response(text2) else: text1 = ngram.generate_text(lm, 8, nletters=100) # time.sleep(0.1)
from chatterbot import ChatBot import sys bot = ChatBot("Terminal", storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter", logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter", io_adapter="chatterbot.adapters.io.TerminalAdapter", database="../database.db") user_input = "Type something to begin..." print(user_input) while True: try: # 'raw_input' is just 'input' in python3 if sys.version_info[0] < 3: user_input = str(raw_input()) else: user_input = input() bot_input = bot.get_response(user_input) except (KeyboardInterrupt, EOFError, SystemExit): break
unit2 = command.lower().split(" ")[4] conversion = float(conversionDict[unit2]) / float(conversionDict[unit1]) response = str(val) + " " + unit1 + " equals " + str(round(val*conversion,3)) + " " + unit2 except: response = "Sorry, I didn't understand that." elif _abusive == True: response = "Don't speak to me like that" elif conflict == False: if _bring == True: response = "Okay, I'll bring you the " + _tool elif _return == True: response = "Okay, I'll put the " + _tool + " away" else: response = "Error in the code, this should never happen" else: response = str(chatbot.get_response(command)) #response = "Sorry, I didn't understand that." #Print and say the response print("response: " + response) if response != "": tts = gTTS(text=response, lang='en') tts.save("good.mp3") os.system("afplay good.mp3")
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot("EjemploBot") trainer = ChatterBotCorpusTrainer(chatbot) trainer.train("chatterbot.corpus.spanish.conversations") while True: mensaje = input("->") if mensaje == "salir": break respuesta = chatbot.get_response(mensaje) print("BOT: " + str(respuesta))
trainer = ListTrainer(bot) trainer.train([ 'Hi', 'Hello, How can I assist you ?', 'how does the investment work?', 'Investing is a way to potentially increase the amount of money you have.The goal is to buy financial products, also called investments, and hopefully sell them at a higher price than what you initially paid.', 'Should i invest in stocks', 'Investing in stocks is an excellent way to grow wealth. For long-term investors, stocks are a good investment even during periods of market volatility — a stock market downturn simply means that many stocks are on sale.', 'how long do you plan to invest ?', 'near about 3 years..' 'what you have invested already?' 'Okay Thanks', 'No Problem! Have a Good Day!' 'Good Luck with all your future investments.' 'Hmmm!! I dont understand yourquestion quiet well' ]) # ##### Create a loop for chatbot to repod to any investment related request until user says "bye" # In[6]: name = input("Enter Your Name: ") print("Welcome to the Bot Service! Let me know how can I help you?") while True: request = input(name + ':') if request == 'Bye' or request == 'bye': print('Bot: Bye') break else: response = bot.get_response(request) print('Bot:', response) # In[ ]:
from chatterbot import ChatBot from chatterbot.filters import RepetitiveResponseFilter import logging # Uncomment the following line to enable verbose logging # logging.basicConfig(level=logging.INFO) # Create a new ChatBot instance bot = ChatBot( "Terminal", storage_adapter="chatterbot.adapters.storage.MongoDatabaseAdapter", logic_adapters=["chatterbot.adapters.logic.ClosestMatchAdapter"], filters=(RepetitiveResponseFilter), input_adapter="chatterbot.adapters.input.TerminalAdapter", output_adapter="chatterbot.adapters.output.TerminalAdapter", database="chatterbot-database") print("Type something to begin...") while True: try: bot_input = bot.get_response(None) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
class answer(): def __init__(self): # Create a new chat bot named Blue self.chatbot = ChatBot( 'Blue', filters=[filters.get_recent_repeated_responses], storage_adapter='chatterbot.storage.SQLStorageAdapter', database='sqlite:///db.sqlite3') #get default system language self.lang = str(getdefaultlocale()[0]) #init tts offline engine self.engine = pyttsx3.init() self.engine.setProperty('rate', 110) voices = self.engine.getProperty('voices') self.engine.setProperty("voice", voices[26].id) #init translator to support others languages self.gtl = Translator(service_urls=['translate.googleapis.com']) #set wikipedia language wikipedia.set_lang( str(getdefaultlocale()[0][0] + getdefaultlocale()[0][1])) def speak(self, text): try: tts = gTTS(text, lang=self.lang[0] + self.lang[1]) sn = str(randint(1, 100000)) + ".mp3" tts.save(sn) playsound.playsound(sn) os.remove(sn) except: self.engine.say(text) self.engine.runAndWait() #to send custom message to a server def interact_with_server(self, ip, port, message): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, int(port))) s.send(bytes(message)) s.close() return True, response except: return False #to interact with a irobot cleaner def interact_with_cleaner(self, ip, password): robot = Robot(ip, password) ms = robot.GetMission() if not "cleaning" in str(ms): robot.StartCleaning() else: robot.StopCleaning() robot.ReturnHome() #to basically call the module and display a website by his url def display_website(self, ws): subprocess.run(["python3", "websearch.py", ws]) def end_video(self, time): time = time.split(":") time = int(time[0]) * 60 + int(time[1]) sleep(time) p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): print(line) if 'midori' in str(line).lower(): pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) sleep(1) def check_commands_files(self, message): response = "" #checking custom files with open("irobot_cleaners.blue", "r") as f: while (True): try: if f.readline() in message: password = f.readline() ip = f.readline() self.interact_with_cleaner(ip, password) f.close() break except: f.close() break with open("skills.blue", "r") as f: for line in f: line = line.split(":") if (message in line[0]): subprocess.run(["python3", "/skills/" + line[1], message], shell=True) with open("custom_rss_feed.blue", "r") as f: while (True): try: l = f.readline().lower() if message.lower() in l: url = f.readline() feed = feedparser.parse(url) self.speak( "Voici les deux derniers articles publiés :") for entry in feed.entries[:2]: self.speak(entry.title) sleep(1) self.speak("voici donc le contenu de l'article :") sleep(0.5) self.speak(entry.summary) f.close() return True, response break elif l.strip("\n").strip("\r") == "": return False, response except: print(e) f.close() return False, response break with open("custom_servers.blue", "r") as f: while (True): try: l = f.readline() if message in l: ip = f.readline() port = f.readline() command = f.readline().replace("[NL]", "\n") res = self.interact_with_server(ip, port, command) if not res: self.speak( "Erreur lors de l'envoi du message au serveur") response = ( "Erreur lors de l'envoi du message au serveur") else: self.speak("Message bien envoyé au serveur") response = ("Message bien envoyé au serveur") f.close() return True, response break elif l.strip("\n").strip("\r") == "": return False, response except: f.close() return False, response break with open("custom_websites.blue", "r") as f: while (True): try: if message in f.readline(): url = f.readline() print(url) self.display_website(url) f.close() return True, response break elif l.strip("\n").strip("\r") == "": return False, response except: f.close() break def check_commands(self, message): response = "" checked, response = self.check_commands_files(message=message) if checked: return checked, response else: print(2) if "va sur" in message: #check if the domain name is complete if "." in message: self.display_website("http://www." + message.strip( "va sur").replace(' ', '').replace('blue', "").lower()) response = ( f"j'ai affiché {message.strip('va sur').replace(' ','').lower()} sur la base BLUE" ) self.speak( f"j'ai affiché {message.strip('va sur').replace(' ','').lower()} sur la base BLUE" ) else: #if not, get the first result on a google search self.display_website( str( list( search(message.strip('va sur').replace( ' ', '').lower(), num=1, start=0, stop=1))[0])) response = ( f"j'ai affiché {message.strip('va sur').replace(' ','').lower()} sur la base BLUE" ) self.speak( f"j'ai affiché {message.strip('va sur').replace(' ','').lower()} sur la base BLUE" ) return True, response elif "cherche" in message: response = GoogleSearch().search( message.replace("cherche", "", 1)) result1 = response.results[0] self.speak(f"selon {result1.title}, {result1.getText()}") return True, response elif ("mets la" in message or "mets le clip" in message) and not message.startswith("mets de"): message = message.replace("mets la", "", 1).replace( "mets le clip", "", 1).replace("la video de", "", 1).replace("la chanson de", "", 1).replace( "la musique de", "", 1).replace("une video de", "", 1).replace( "une chanson de", "", 1).replace("une musique de", "", 1) results = YoutubeSearch(message, max_results=10).to_dict() url = "https://youtube.com" + results[0]['url_suffix'] vid = pafy.new(url) best = vid.getbest() self.speak(f"j'ai affiché {message.lower()} sur la base BLUE") self.display_website(best.url) print(f"j'ai affiché {message.lower()} sur la base BLUE") if results[0]['duration'] != 0: proc = multiprocessing.Process( target=self.end_video, args=(results[i]['duration'], )) proc.start() proc.join() else: proc = multiprocessing.Process(target=self.end_video, args=("20:0", )) proc.start() proc.join() return True, response elif (message in "quelle heure est-il") or ( message in "quelle heure il est") or ( message in "donne moi l'heure s'il te plais"): date = datetime.datetime.now() response = (str(date.hour) + ':' + str(date.minute) + "et" + str(date.second) + " secondes") self.speak("Il est " + response) return True, response elif message in "quel jour sommes-nous quel jour on est quel jour est-on donne moi le jour": d = datetime.date.today().strftime("%d %B %Y") response = (str(d)) print(response) self.speak("Nous sommes le" + response) return True, response elif message in "adieu goodbye exit aurevoir au revoir tais toi shut-up au-revoir ta gueule ferme-la chut": response = ("bonne journée !") self.run_cmd("xset dpms force off") return True, response elif message.startswith("dis"): response = (message[3:]) self.speak(message[3:]) return True, response elif message in "ouvre youtube": self.display_website("https://www.youtube.com") response = ("j'ai ouvert youtube dans votre navigateur") return True, response elif message in "ouvre google": self.display_website("https://www.google.com") response = ("j'ai ouvert google dans votre navigateur") return True, response elif message in "ouvre drive ouvre le drive ouvre google drive ouvre mon drive": self.display_website("https://drive.google.com/drive/my-drive") response = ("j'ai ouvert google drive dans votre navigateur") return True, response elif message in "ouvre classroom ouvre google classroom": self.display_website("https://classroom.google.com/u/0/h") response = ( "j'ai ouvert google classroom dans votre navigateur") return True, response elif message in "ouvre Gmail ouvre gmail ouvre mes mails ouvre mail ouvre ma boite mail ouvre ma boite gmail": self.display_website("https://mail.google.com/mail/u/0/#inbox") response = ( "j'ai ouvert votre boite mail dans votre navigateur") return True, response elif message in "effectue un speedtest effectue un test de vitesse fais un speedtest s'il te plaît fais un test de vitesse s'il te plaît c'est un speedtest s'il te plaît": response = ("Mise en route d'un speedtest..") s = speedtest.Speedtest() s.get_servers() s.get_best_server() s.download() s.upload() res = s.results.dict() d = (float(res["download"]) / 1024) / 1000 u = (float(res["upload"]) / 1024) / 1000 p = float(res["ping"]) d = round(d, 3) u = round(u, 3) p = round(p, 3) d = str(d) u = str(u) p = str(p) d = d.replace(".", ",") u = u.replace(".", ",") p = p.replace(".", ",") response = ( "Vous êtes actuellement à {} Mb/s download et {} Mb/s upload, avec un ping de {} millisecondes" .format(d, u, p)) return True, response elif message in "éteins toi éteins-toi extinction shutdown": try: self.run_cmd("shutdown now") except: response = ("Désolé, l'exécution de la commande a foirée") return True, response elif message in "redémarre toi redémarre-toi redémarrage reboot": try: self.run_cmd("reboot") except: response = ("Désolé, l'exécution de la commande a foirée") return True, response elif message in "joue de la musique" or "mets de la musique" in message or "top 50" in message or "top 100" in message: results = YoutubeSearch('top trending world music', max_results=10).to_dict() print( "[+] Searching \"top trending world music\" on Youtube and getting you the best stream url... " ) url = "https://youtube.com" + results[0]['url_suffix'] vid = pafy.new(url) best = vid.getbest() self.display_website(best.url) return True, response elif message in "ifconfig ipconfig quelle est mon adresse IP locale mon IP locale": print(self.run_cmd("ifconfig")) self.speak("Voici votre configuration IP") response = ("Voici votre configuration IP") return True, response if ("ferme Google" in message) or ("ferme Internet" in message) or ( "ferme la fenêtre" in message) or (message == "stop") or ("arrête" in message): #get default browser name sDefault_Browser = self.run_cmd("sensible-browser -V").split( '\n')[0].split(' ')[0] #kill it by name self.run_cmd("killall " + sDefault_Browser) self.speak("j'ai fermé ton navigateur internet") response = "j'ai fermé ton navigateur internet" return True, response elif "ferme" in message: message = message.split(sep=" ") process_name = " ".join(message[1:]) self.run_cmd(f"killall {process_name}") self.speak("j'ai fermé {}".format(process_name)) response = ("j'ai fermé {}".format(process_name)) return True, response elif message in "quelle est mon adresse IP routeur mon IP routeur": self.speak("voici votre IP routeur " + socket.gethostbyname(socket.gethostname())) response = ("Voici votre IP routeur" + socket.gethostbyname(socket.gethostname())) return True, response elif message in "quel temps fait-il dehors donnes moi la météo": self.display_website("https://www.google.com/search?q=meteo") client.send("j'ai ouvert la météo dans votre navigateur") return True, response elif "wikipédia" in message: message = message.split() message = message[-1] self.display_website( "https://fr.wikipedia.org/wiki/{}".format(message)) response = ("voici la page wikipédia de {}".format(message)) return True, response elif "comment" in message and "faire" in message or "how to" in message: message = message.split() if len(message[-2]) <= 2: message = message[-2] + message[-1] else: message = message[-1] self.display_website( "https://fr.wikipedia.org/wiki/{}".format(message)) response = ("voici la page wikipédia de {}".format(message)) return True, response elif ("définition" in message) or ("qui est" in message) or ( "qui était" in message) or ("c'est quoi" in message) or ("qu'est-ce qu" in message): message = message.split() message = message[-1] try: print("[+] Searching on wikipedia...") res = wikipedia.summary(message, sentences=1) response = str(res) print(response) self.speak(res) return True, response except: response = "Auncun article sur wikipedia correspond à ce nom." self.speak( "Auncun article sur wikipedia correspond à ce nom.") return True, response elif message in "fait un compte à rebours": #pas finis return True, response elif message == "test": self.display_website("www.google.com") print("in test") elif "informations" in message or "info" in message or "nouvelles" in message: self.speak("d'après le journal Le monde, ") else: return False, response def run_cmd(self, sCommand): """ run command line :sCommand: String parameter containing the command to run :returns: A string containing the stdout """ return subprocess.run([sCommand], shell=True, capture_output=True).stdout.decode("utf-8") def get_answer(self, message, client): print("[+] Translating...") message = self.gtl.translate(message, dest="fr") if not client == None: if message.lower() == "merci": self.speak("Avec plaisir !") checked, response = self.check_commands(message) response = self.gtl.translate(response, dest=self.lang[0] + self.lang[1]) if not checked: response = str(self.chatbot.get_response(message)) response = self.gtl.translate(response, dest=self.lang[0] + self.lang[1]) print(f"BLUE:{response}") client.send(bytes(response, 'utf-8')) else: print(f"BLUE:{response}") client.send(bytes(response, 'utf-8')) else: print(3) checked, response = self.check_commands(message) response = self.gtl.translate(response, dest=self.lang[0] + self.lang[1]) print(response) if not checked: print(message) response = str(self.chatbot.get_response(message)) response = self.gtl.translate(response, dest=self.lang[0] + self.lang[1]) print(f"BLUE:{response}") self.speak(response) else: print(response)
while True: try: __input = input() with open("../data/keywords.csv", 'r') as f: reader = csv.DictReader(f) dont_use_chatter = False for row in reader: if row["QUESTION"] in __input: logging.debug("the words in my db") print(row["ANSWER"]) dont_use_chatter = True break if dont_use_chatter == False: bot_input = bot.get_response(__input) logging.debug("confidence" + str(bot_input.confidence)) if bot_input.confidence > 0.5: print(bot_input) dont_use_chatter = True else: logging.debug("confidence too low, try to search") segs = jieba.cut(__input) dont_use_chatter = True segged = list(segs) without_sw = remove_stopwords(segged) logging.debug("without stopword: " + "".join(without_sw)) new_bot_input = random.choice(can_words).replace( "%p", __input) print(new_bot_input) except (KeyboardInterrupt, EOFError, SystemExit):
"What time does the Bookshop open?", "The Bookshop opens at 9AM.", ] close_timings_conversation = [ "What time does the Bookshop close?", "The Bookshop closes at 8PM.", ] spec_conversation = [ "How much type of books you have?", "Two thousands type of books I have .", "who is book is good?", "Holly Quran pak is a good book I have. " ] # Initializing Trainer Object trainer = ListTrainer(Bookshop) # Training Bookshopbot # training from corpus corpus_tranier = ChatterBotCorpusTrainer(Bookshop) corpus_tranier.train("chatterbot.corpus.english") trainer.train(greet_conversation) trainer.train(open_timings_conversation) trainer.train(close_timings_conversation) trainer.train(spec_conversation) while True: user_input = input('You') if user_input == 'bye': break response = Bookshop.get_response(user_input) print(response)
class wppbot: #setando o caminho do app dir_path = os.getcwd() #construtor da classe def __init__(self, nome_bot): #Setando o bot self.bot = ChatBot(nome_bot) #ListTrainer(self.bot) #setando a pasta onde ta o chrome driver self.chrome = self.dir_path + '\chromedriver.exe' #configurando um profile pra não logar no whats toda hora self.options = webdriver.ChromeOptions() self.options.add_argument(r"user-data-dir=" + self.dir_path + "\profile\wpp") #iniciando o driver self.driver = webdriver.Chrome(self.chrome, chrome_options=self.options) # Method start def inicia(self, nome_contato): #Selenium vai entrar no whats e esperar 15s pra carregar tudo self.driver.get('https://web.whatsapp.com/') self.driver.implicitly_wait(15) #elemento da barra de pesquisa pela classe self.caixa_de_pesquisa = self.driver.find_element_by_class_name( 'jN-F5') #escrevemos o nome do contato na caixa e esperamos 2s self.caixa_de_pesquisa.send_keys(nome_contato) time.sleep(2) #buscar o contato/grupo e clicar no mesmo self.contato = self.driver.find_element_by_xpath( '//span[@title = "{}"]'.format(nome_contato)) self.contato.click() time.sleep(2) # Method speak start def saudacao(self, frase_inicial): #setando a caixa de mansagem como elemento _2S1VP self.caixa_de_mensagem = self.driver.find_element_by_class_name( '_2S1VP') #validando se a mensagem inicial é uma lista if type(frase_inicial) == list: #fazendo um for para mandar cada mensagem for frase in frase_inicial: #Escrevemos a frase na caixa de mensagem. self.caixa_de_mensagem.send_keys(frase) time.sleep(1) #Setamos o botão de enviar e clicamos para enviar. self.botao_enviar = self.driver.find_element_by_class_name( '_35EW6') self.botao_enviar.click() time.sleep(1) else: return False # Method hear start def escuta(self): #setando todas as mensagens no grupo post = self.driver.find_elements_by_class_name('_3_7SH') #pegando o indice da ultima mensagem ultima = len(post) - 1 #texto da ultima conversa texto = post[ultima].find_element_by_css_selector( 'span.selectable-text').text return texto # Method Responder def responde(self, texto): #setando a resposta do bot na variavel response response = self.bot.get_response(texto) #transforma em string a resposta response = str(response) #coloca o prefixo bot no inicio response = '*bot :* _' + response + '_' #setando a caixa de mensagem e atribuindo a resposta e enviando-a self.caixa_de_mensagem = self.driver.find_element_by_class_name( '_2S1VP') self.caixa_de_mensagem.send_keys(response) time.sleep(1) self.botao_enviar = self.driver.find_element_by_class_name('_35EW6') self.botao_enviar.click() # Method trainer def treina(self, nome_pasta): #Listamos todos os arquivos dentro da pasta e para cada linha treinamos nosso bot. for treino in os.listdir(nome_pasta): conversas = open(nome_pasta + '/' + treino, 'r').readlines() trainer = ListTrainer(self.bot) trainer.train(conversas)
storage_adapter='chatterbot.storage.JsonFileStorageAdapter', logic_adapters=[{ 'import_path': 'chatterbot.logic.BestMatch' }, { 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 'threshold': 0.65, 'default_response': 'I am sorry, but I do not understand.' }], trainer='chatterbot.trainers.ListTrainer') # 手动给定一点语料用于训练 bot.train([ 'How can I help you?', 'I want to create a chat bot', 'Have you read the documentation?', 'No, I have not', 'This should help get you started: http://chatterbot.rtfd.org/en/latest/quickstart.html' ]) # 给定问题并取回结果 question = 'How do I make an omelette?' print(question) response = bot.get_response(question) print(response) print("\n") question = 'how to make a chat bot?' print(question) response = bot.get_response(question) print(response)
speak("Hi, Welcome! How are you doing?") while True: print("Say something!") #speak("say something") with m as source: audio = r.listen(source) print("Got it! Now to recognize it...") try: # recognize speech using Google Speech Recognition value = r.recognize_google(audio) # we need some special handling here to correctly print unicode characters to standard output if str is bytes: result = format(value).encode("utf-8") print(result) if(result in "Take make me a picture pictures"): img_capture() statement=chatbot.get_response(result) speak(statement) print(statement) #if(result in word): # print(result) # speak("how are you buddy") #else: # print(result) # speak("sorry. didn't hear you") else: # this version of Python uses unicode for strings (Python 3+) print("You said {}".format(value)) except sr.UnknownValueError: print("Oops! Didn't catch that") except sr.RequestError as e: print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e)) except KeyboardInterrupt:
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer # https://chatbotslife.com/how-to-create-an-intelligent-chatbot-in-python-c655eb39d6b1 my_bot = ChatBot(name='DetectAndDeter', read_only=True, logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', 'chatterbot.logic.BestMatch' ]) def train(): corpus_trainer = ChatterBotCorpusTrainer(my_bot) corpus_trainer.train('chatterbot.corpus.english') def get_response(text: str): text.replace(" %HESITATION", "") return my_bot.get_response(text) if __name__ == '__main__': while True: print(my_bot.get_response(input("> ")))
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os bot = ChatBot('Bot') bot.set_trainer(ListTrainer) while True: message = input('\nYou: ') if message.strip != 'Bye': reply = bot.get_response(message) print('Chatbot: ', reply) if message.strip() == 'Bye': print('Chatbot: Bye') break
#!/usr/bin/python # -*- coding: utf-8 -*- from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot("myBot") chatbot.set_trainer(ChatterBotCorpusTrainer) # 使用英文语料库训练它 chatbot.train("chatterbot.corpus.english") # 开始对话 while True: print chatbot.get_response(raw_input(">"))
from chatterbot import ChatBot import logging ''' This is an example showing how to train a chat bot using the Ubuntu Corpus of conversation dialog. ''' # Enable info level logging logging.basicConfig(level=logging.INFO) chatbot = ChatBot( 'Example Bot', trainer='chatterbot.trainers.UbuntuCorpusTrainer' ) # Start by training our bot with the Ubuntu corpus data chatbot.train() # Now let's get a response to a greeting response = chatbot.get_response('How are you doing today?') print(response)
from chatterbot.trainers import ListTrainer from chatterbot import ChatBot bot = ChatBot('Test') conv = ['Oi', 'olá'] bot.set_trainer(ListTrainer) bot.train(conv) while (True): quest = input('Você: ') response = bot.get_response(quest) print('Bot: ', response)
# Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) # Create a new instance of a ChatBot bot = ChatBot( "Terminal", storage_adapter="chatterbot.storage.SQLStorageAdapter", logic_adapters=[ "chatterbot.logic.MathematicalEvaluation", "chatterbot.logic.TimeLogicAdapter", "chatterbot.logic.BestMatch" ], input_adapter="chatterbot.input.TerminalAdapter", output_adapter="chatterbot.output.TerminalAdapter", database="../database.db" ) print("Type something to begin...") # The following loop will execute each time the user enters input while True: try: # We pass None to this method because the parameter # is not used by the TerminalAdapter bot_input = bot.get_response(None) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome." ] chatbot.set_trainer(ListTrainer) chatbot.train(conversation) ######################################## ### END of TRAINING ######################################## print("USER: How are you doing?") response = chatbot.get_response("How are you doing?") print("BOT:" + str(response)) print("USER: Hello") response = chatbot.get_response("Hello") print("BOT:" + str(response)) print("USER: Good morning!") response = chatbot.get_response("Good morning!") print("BOT:" + str(response)) print("USER: Do you like machine learning?") response = chatbot.get_response("Do you like machine learning?") print("BOT:" + str(response)) print("USER: How do I make a neural network?")
# -*- coding: utf-8 -*- from chatterbot import ChatBot # Create a new instance of a ChatBot bot = ChatBot('Exact Response Example Bot', storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[{ 'import_path': 'chatterbot.logic.BestMatch' }, { 'import_path': 'chatterbot.logic.SpecificResponseAdapter', 'input_text': 'Help me!', 'output_text': 'Ok, here is a link: http://chatterbot.rtfd.org' }], trainer='chatterbot.trainers.ListTrainer') # Get a response given the specific input response = bot.get_response('Help me!') print(response)
class DialogueManager(object): """ Class for the dialogue manager """ def __init__(self, paths): """ Constructor for the DialogueManager - Loads the intent recognizer (is this about programming, or just chit-chatting?) - Loads the tf-idf vectorizer (the vectorizer trained on the dialogue and StackOverflow thread questions) Parameters ---------- paths : dict Where the keys are names, and the values are lists of paths relative to this directory """ print("Loading resources...") # Create the chatbot self.create_chitchat_bot() # Intent recognition: self.intent_recognizer = \ unpickle_file(Path(*paths['INTENT_RECOGNIZER'])) self.tfidf_vectorizer = \ unpickle_file(Path(*paths['TFIDF_VECTORIZER'])) self.ANSWER_TEMPLATE = ('I think its about {}\n' 'This thread might help you: ' 'https://stackoverflow.com/questions/{}') # Goal-oriented part: self.tag_classifier = unpickle_file(Path(*paths['TAG_CLASSIFIER'])) self.thread_ranker = ThreadRanker(paths) def create_chitchat_bot(self): """ Initializes self.chitchat_bot with some conversational model. """ self.chatbot = \ ChatBot('MrStack2000Bot', trainer='chatterbot.trainers.ChatterBotCorpusTrainer') # Train on the english corpus self.chatbot.train("chatterbot.corpus.english") # Train for own conversation self.chatbot.set_trainer(ListTrainer) self.chatbot.train([ 'What is PEP20?', 'The zen of python', 'Where can I learn about it?', 'On the interwebz', 'Where on the interwebz?' 'https://www.python.org/dev/peps/pep-0020/' ]) self.chatbot.train([ 'What is AI?', ('I like the definition: AI is what we think is intelligent, but' 'which has not yet been achieved') ]) def generate_answer(self, question): """ Combines StackOverflow and chitchat parts using intent recognition. Parameters ---------- question : str The question asked Returns ------- str The answer """ # Recognize intent of the question using `intent_recognizer`. # Don't forget to prepare question and calculate features for the # question. prepared_question = text_prepare(question) if prepared_question == '': # Text preparation is an empty string, tf_idf won't work return self.chatbot.get_response(question) features = self.tfidf_vectorizer.transform(prepared_question.split()) intent = self.intent_recognizer.predict(features)[0] # Chit-chat part: if intent == 'dialogue': # Pass question to chitchat_bot to generate a response. response = self.chatbot.get_response(question) return response # Goal-oriented part: else: # Pass features to tag_classifier to get predictions. # NOTE: [0] as we are just after the first tag tag = self.tag_classifier.predict(features)[0] # Pass prepared_question to thread_ranker to get predictions. thread_id = self.thread_ranker.get_best_thread(question, tag) return self.ANSWER_TEMPLATE.format(tag, thread_id)
# -*- coding: utf-8 -*- from chatterbot import ChatBot bot = ChatBot('Test', trainer='chatterbot.trainers.ChatterBotCorpusTrainer') bot.train('chatterbot.corpus.portuguese') while True: res = input('Você: ') resp = bot.get_response(res) print('Bot: ', resp)
trainer.train(['What is your name?', 'My name is CBIT']) trainer.train(['Who are you?', 'I am a bot' ]) # In[23]: from chatterbot.trainers import ChatterBotCorpusTrainer # Create a new trainer for the chatbot trainer = ChatterBotCorpusTrainer(bot) # Train the chatbot based on the english corpus trainer.train("chatterbot.corpus.english") # Get a response to an input statement bot.get_response("who is obama?") # In[ ]: @app.route("/") def home(): return render_template("home.html") @app.route("/get") def get_bot_response(): userText = request.args.get('msg') return str(bot.get_response(userText)) if __name__ == "__main__": app.run()
from chatterbot import ChatBot bot = ChatBot( "Math & Time Bot", logic_adapters=[ "chatterbot.adapters.logic.EvaluateMathematically", "chatterbot.adapters.logic.TimeLogicAdapter" ], io_adapter="chatterbot.adapters.io.NoOutputAdapter" ) # Print an example of getting one math based response response = bot.get_response("What is 4 + 9?") print(response) # Print an example of getting one time based response response = bot.get_response("What time is it?") print(response)
from chatterbot.trainers import ChatterBotCorpusTrainer from settings import GITTER # Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) chatbot = ChatBot( 'GitterBot', gitter_room=GITTER['ROOM'], gitter_api_token=GITTER['API_TOKEN'], gitter_only_respond_to_mentions=False, input_adapter='chatterbot.input.Gitter', output_adapter='chatterbot.output.Gitter' ) trainer = ChatterBotCorpusTrainer(chatbot) trainer.train('chatterbot.corpus.english') # The following loop will execute each time the user enters input while True: try: response = chatbot.get_response(None) # Press ctrl-c or ctrl-d on the keyboard to exit except (KeyboardInterrupt, EOFError, SystemExit): break
class DataCachingTests(TestCase): def setUp(self): self.test_data_directory = 'test_data' self.test_database_name = self.random_string() + ".db" if not os.path.exists(self.test_data_directory): os.makedirs(self.test_data_directory) database_path = os.path.join( self.test_data_directory, self.test_database_name ) self.chatbot = ChatBot( "Test Bot", io_adapter="chatterbot.adapters.io.NoOutputAdapter", logic_adapter="tests.logic_adapter_tests.test_data_cache.DummyMutatorLogicAdapter", database=database_path ) self.chatbot.train([ "Hello", "How are you?" ]) def random_string(self, start=0, end=9000): """ Generate a string based on a random number. """ from random import randint return str(randint(start, end)) def remove_data(self): import shutil if os.path.exists(self.test_data_directory): shutil.rmtree(self.test_data_directory) def tearDown(self): """ Remove the test database. """ self.chatbot.storage.drop() self.remove_data() def test_additional_attributes_saved(self): """ Test that an additional data attribute can be added to the statement and that this attribute is saved. """ response = self.chatbot.get_response("Hello") found_statement = self.chatbot.storage.find("Hello") self.assertIsNotNone(found_statement) self.assertIn("pos_tags", found_statement.serialize()) self.assertEqual( "NN", found_statement.serialize()["pos_tags"] )