Memoria for chat bot

Asked

Viewed 302 times

1

I’m making a chatbot, I’ve implemented some functions and I’d like to know if there’s a waylo save what I taught him by typing the phrase and then typing the answer to when I asked the question he knew the answer I did this way but I do not know how to ask to save questions and answer follows the code

# !/usr/bin/env python
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
import os
from datetime import datetime
from googlesearch import search
import speech_recognition as sr
import pyttsx3
import wikipedia
import json

import webbrowser
wikipedia.set_lang('pt') #difinindo wikipedia para portugues

speaker = pyttsx3.init()

bot = ChatBot('Iana', read_only=True)

keywords = ['o que é','fale-me', 'quem é', 'quem foi','definição','defina']

google_keywords = ['pesquisar por', 'pesquise por','pesquise','tocar no']


dict_cmds = {}

def load_cmds():
    lines = open('cmds.txt', 'r').readlines()
    for line in lines:
        line = line.replace('\n', '')
        parts = line.split('\t')
        dict_cmds.update({parts[0]: parts[1]})


# CHATBOT TRAINER..

bot.set_trainer(ListTrainer)
for _file in os.listdir('Chats'):
    lines = open('Chats/' + _file, 'r').readlines()
    bot.train(lines)


def speak(text):
    speaker.say(text)
    speaker.runAndWait()


def evaluate(text): #passar um comando
    result = None
    try:
        result = dict_cmds[text]
    except:
        result = None
    return result
######## comandos externos######
def run_cmd(cmd_type):
    result = None

    if cmd_type == 'asktime':
        now = datetime.now()
        result = 'São' + str(now.hour) + 'horas e' + str(now.minute )+'minutos. '
    if cmd_type == 'askdate':
        now = datetime.now()
        months = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']
        result  = 'Hoje é ' + str(now.day) + ' de ' + months[now.month - 1]
    if cmd_type =='bloco':
        now = os.startfile('notepad.exe')
        result = 'abrindo bloco de notas'
    if cmd_type == 'musica':
        now = os.startfile("C:\Program Files (x86)\PreSonus\Studio One 3\Studio One.exe")
        result = 'um momento'
    if cmd_type == 'aprender':
        chave = input('digite uma frase: ')
        resp = input('digite a resposta: ')


    return result


def get_answer(text):
    result = None
    for key in keywords:
        if text.startswith(key):
            result = text.replace(key, '')


    if result is not None:
        results = wikipedia.search(result)
        result = wikipedia.summary(results[0],sentences=2)

    return  result

def search_web(text):
    result = None
    if text is not None:
        for key in google_keywords:
            if text.startswith(key):
                result = text.replace(key,'')

        if result is not None:
            for url in search(text, stop=3):
                webbrowser.open_new_tab(url)
                break
            return 'pesquisando por' + result.rstrip()
    return result


load_cmds()  # carrega os comandos



r = sr.Recognizer()

with sr.Microphone() as s:
    r.adjust_for_ambient_noise(s)

    while True:
        try:
            audio = r.listen(s)
            speech = r.recognize_google(audio, language='pt').lower()
            response = run_cmd(evaluate(speech))
            if response == None:
                response = get_answer(speech)
                if response == None:
                    response = search_web(speech)
                    if response == None:
                        response = bot.get_response(speech)
            print('Voce disse:{} '.format(speech))
            print('Bot: {} '.format(response))
            speak(response)
        except:
            print('Algum erro ocorreu.')
  • You can use Sqlite, Firebird, or even a remote database such as mysql, postgre, sqlserver (preferably these last via API due to security).

  • I liked the idea but said I’m new in python I’m still learning not know how to implement it on Cod by explaining to me

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.