Exemplo n.º 1
0
class ChatterModel(BaseModel):
    def __init__(self):
        self.bot = ChatBot('tgbot')
        self.text_last = {}

    def _get(self, message, c_last, payload, predict):
        # update the bot

        statement = Statement(payload)

        if message.chat.id in c_last:
            last = c_last[message.chat.id]

            self.bot.learn_response(statement, last)

        c_last[message.chat.id] = statement

        # choose the best reply

        if predict:
            response = self.bot.generate_response(statement)

            return [(response.confidence, response.text)]

    def text(self, message, predict):
        return self._get(message, self.text_last, message.text, predict)
def chatMessages(message):
    logging.debug("Message received = %s", message)
    message = message.strip()

    try:
        parts = message.split(":")
        firstPart = parts[0]
        firstPart = firstPart.strip()
        logging.debug("First part=%s", firstPart)
        bot = ChatBot(
            'Feedback Learning Bot',
            storage_adapter='chatterbot.storage.SQLStorageAdapter',
            logic_adapters=[{
                'import_path': 'chatterbot.logic.BestMatch'
            }, {
                'import_path': 'chatterbot.logic.LowConfidenceAdapter',
                'threshold': 0.65,
                'default_response': 'I am sorry, I am new to it.'
            }],
            input_adapter='chatterbot.input.VariableInputTypeAdapter',
            output_adapter='chatterbot.output.TerminalAdapter')
        logging.debug("Inside Bot processing")
        CONVERSATION_ID = bot.storage.create_conversation()
        input_statement = bot.input.process_input_statement(firstPart)
        statement, response = bot.generate_response(input_statement,
                                                    CONVERSATION_ID)
        if firstPart.lower() == "tquestion":
            logging.debug("Saving answer")
            question = parts[1]
            logging.debug("question=%s", question)
            question_statement = bot.input.process_input_statement(question)
            try:
                AnsTag = parts[2]
                if AnsTag.lower() == "tanswer":
                    AnsTag = AnsTag.strip()
                    logging.debug("AnsTag=%s", AnsTag)
                    Answer = parts[3]
                    Answer = Answer.strip()
                    if Answer:
                        logging.debug("Answer=%s", Answer)
                        answer_statement = bot.input.process_input_statement(
                            Answer)
                        bot.learn_response(answer_statement,
                                           question_statement)
                        bot.storage.add_to_conversation(
                            CONVERSATION_ID, question_statement,
                            answer_statement)
                        bot.output.process_response(answer_statement)
                        emit("Bot_Reply", "Saved your answer.")
                else:
                    emit("Bot_Reply", "Answer tag is incorrect")
            except:
                emit("Bot_Reply", "No Answer found for question")
        else:
            logging.debug("Response=%s", response.text)
            emit("Bot_Reply", response.text)
    except:
        logging.debug("something is not good")
        emit("Bot_Reply", "something is not good")
Exemplo n.º 3
0
def main():
    # Uncomment the following line to enable verbose logging
    logging.basicConfig(level=logging.INFO)

    # Create a new instance of a ChatBot
    bot = ChatBot(
        "Terminal",
        storage_adapter="chatterbot.storage.JsonFileStorageAdapter",
        logic_adapters=[{
            'import_path':
            'chatterbot.logic.MathematicalEvaluation'
        }, {
            'import_path': 'chatterbot.logic.TimeLogicAdapter'
        }, {
            '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/en/latest/quickstart.html'
        }],
        trainer='chatterbot.trainers.ListTrainer',
        input_adapter="chatterbot.input.TerminalAdapter",
        output_adapter="chatterbot.output.TerminalAdapter",
        database="../database.json")

    DEFAULT_SESSION_ID = bot.default_session.id

    print('Type something to begin...')

    # The following loop will execute each time the user enters input
    while True:
        try:
            input_statement = bot.input.process_input_statement()
            statement, response = bot.generate_response(
                input_statement, DEFAULT_SESSION_ID)

            print('\n Is "{}" this a coherent response to "{}"? \n'.format(
                response, input_statement))

            if get_feedback():
                bot.learn_response(response, input_statement)

            bot.output.process_response(response)

            # Update the conversation history for the bot
            # It is important that this happens last, after the learning step
            bot.conversation_sessions.update(bot.default_session.id_string, (
                statement,
                response,
            ))

        # Press ctrl-c or ctrl-d on the keyboard to exit
        except (KeyboardInterrupt, EOFError, SystemExit):
            break
Exemplo n.º 4
0
def chatbot():

    conn = rpyc.classic.connect(
        'ev3dev.local')  # host name or IP address of the EV3
    ev3 = conn.modules['ev3dev.ev3']  # import ev3dev.ev3 remotely

    bot = ChatBot('Luigi',
                  storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
                  logic_adapters=["chatterbot.logic.BestMatch"],
                  input_adapter='chatterbot.input.TerminalAdapter',
                  output_adapter='chatterbot.output.TerminalAdapter',
                  trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
                  database='chatterbot-database')

    bot.train("chatterbot.corpus.english")

    CONVERSATION_ID = bot.storage.create_conversation()
    ev3.Sound.volume = 200
    ev3.Sound.speak('Hello ! Say something to begin').wait

    m = ev3.MediumMotor('outA')
    m.run_to_rel_pos(position_sp=30, speed_sp=900, stop_action="hold")
    m.run_to_rel_pos(position_sp=-30, speed_sp=900, stop_action="hold")

    print('Hello ! Say something to begin')

    # The following loop will execute each time the user enters input
    while True:
        try:
            input_statement = bot.input.process_input_statement()
            statement, response = bot.generate_response(
                input_statement, CONVERSATION_ID)
            ev3.Sound.speak('%s' %
                            bot.output.process_response(response)).wait()
            reaction_tete = 'no'
            if reaction_tete in bot.output.process_response(response):
                m.run_to_rel_pos(position_sp=45,
                                 speed_sp=900,
                                 stop_action="hold")
                m.run_to_rel_pos(position_sp=-45,
                                 speed_sp=900,
                                 stop_action="hold")
            #print('\n Is "{}" a coherent response to "{}"? \n'.format(response, input_statement))
            # if get_feedback():
            #print("please input the correct one")
            #response1 = bot.input.process_input_statement()
            #bot.learn_response(response1, input_statement)
            #bot.storage.add_to_conversation(CONVERSATION_ID, statement, response1)
            #print("Responses added to bot!")
        # Press ctrl-c or ctrl-d on the keyboard to exit
        except (KeyboardInterrupt, EOFError, SystemExit):
            break
Exemplo n.º 5
0
def get_message(message):
    chatbot = ChatBot('Ron Obvious', read_only=True, logic_adapters=['chatterbot.logic.BestMatch',
                                                                     {'import_path': 'chatterbot.logic.BestMatch',
                                                                      'threshold': 0.65,
                                                                      'default_response': 'I am sorry, but I can only answer questions related to ACM.'
                                                                      }
                                                                     ],
                      input_adapter='chatterbot.input.VariableInputTypeAdapter',
                      output_adapter='chatterbot.output.OutputAdapter',
                      filter='chatterbot.filters.RepetitiveResponseFilter')

    # Create a new trainer for the chatbot
    trainer = ChatterBotCorpusTrainer(chatbot)

    # Train the chatbot based on the english corpus
    trainer.train("chatterbot.corpus.english.greetings",
                  "chatterbot.corpus.english.conversations",
                  "chatterbot.corpus.english.emotion",
                  "chatterbot.corpus.english.psychology")
    return chatbot.generate_response(message)
Exemplo n.º 6
0
    def process(self, input_statement,
                additional_response_selection_parameters):

        import time
        import sys
        import os

        while True:
            try:
                input_statement = Statement(text=input())
                response = ChatBot.generate_response(input_statement)

                print('\n Is "{}" a coherent response to "{}"? \n'.format(
                    response.text, input_statement.text))
                if get_feedback() is False:
                    print('please input the correct one')
                    correct_response = Statement(text=input())
                    ChatBot.learn_response(correct_response, input_statement)
                    print('Responses added to bot!')
            except (KeyboardInterrupt, EOFError, SystemExit):
                break
Exemplo n.º 7
0
class AIChatBot:
    def __init__(self,
                 bot_name,
                 self_training,
                 low_confidence_threshold,
                 low_confidence_responses,
                 random_response=True,
                 premoderation_callback=None,
                 db_file=None,
                 db_uri=None):
        """Create new AIChatBot instance.

        Args:
            bot_name (str): Bot name.
            db_uri (str): Database URI.
            db_file (str): Database file (should not be used, left for backward compatibility)
            self_training (bool): Will bot train itself.
            low_confidence_threshold (float): Confidence threshold, if lower - low_confidence_responses will be used.
            low_confidence_responses (list): Responses that will be used if confidence is lower than threshold.
            random_response (bool): If true, choose random response instead of the most frequent.
            premoderation_callback (function): Premoderation function, set None to disable.
        """
        # Backward compatibility
        if db_uri is None and db_file is not None:
            db_uri = 'sqlite:///{}'.format(db_file)
            warnings.warn(
                'use db_uri instead of deprecated db_file, it will be removed in the future',
                DeprecationWarning)
        self.__chatbot = ChatBot(
            bot_name,
            logic_adapters=['chatterbot.logic.BestMatch'],
            response_selection_method=get_random_response
            if random_response else get_most_frequent_response,
            filters=['chatterbot.filters.RepetitiveResponseFilter'],
            database_uri=db_uri)
        self.__conversation_id = self.__chatbot.storage.create_conversation()
        self.previous_response = None

        self.__self_training = self_training
        self.__low_confidence_threshold = low_confidence_threshold
        self.__low_confidence_responses = low_confidence_responses
        self.__premoderation_callback = premoderation_callback

    def get_response(self, question, premoderation_payload=None):
        """Get response to the message.

        Args:
            question (str): Message.
            premoderation_payload: Data to pass to premoderation_callback.

        Returns:
            str: Response.

        """
        # Get supposed response
        question = Statement(question)
        response = self.__chatbot.generate_response(question,
                                                    self.__conversation_id)[1]
        """:type : Response"""

        # Choose random response if confidence is lower than threshold
        if response.confidence < self.__low_confidence_threshold and self.__low_confidence_responses:
            response = Statement(choice(self.__low_confidence_responses))

        if self.__premoderation_callback:
            response = self.__premoderation_callback(question.text,
                                                     response.text,
                                                     premoderation_payload)
            if not response:
                return
            response = Statement(response)
            response.confidence = 1
            self.__chatbot.learn_response(response, question)
            self.__chatbot.storage.add_to_conversation(self.__conversation_id,
                                                       question, response)

        if self.__self_training and self.previous_response and '?' in self.previous_response.text and \
                self.previous_response.confidence >= self.__low_confidence_threshold:
            self.__chatbot.learn_response(question, self.previous_response)
            self.__chatbot.storage.add_to_conversation(self.__conversation_id,
                                                       self.previous_response,
                                                       question)
        self.previous_response = response

        return response.text

    def learn(self, question, response):
        """Learn a response.

        Args:
            question (str): Question.
            response (str): Response

        """
        question = Statement(question)
        response = Statement(response)
        self.__chatbot.learn_response(response, question)
        self.__chatbot.storage.add_to_conversation(self.__conversation_id,
                                                   question, response)

    def statement_exists(self, statement_text):
        """Check if statement exists.

        Args:
            statement_text (str): Statement text.

        Returns:
            bool

        """
        return True if self.__chatbot.storage.find(statement_text) else False

    def remove_statement(self, statement_text):
        """Remove statement from database.

        Args:
            statement_text (str): Statement text.

        """
        self.__chatbot.storage.remove(statement_text)
Exemplo n.º 8
0
            "import_path": "chatterbot.logic.BestMatch",
            "statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
            "response_selection_method": "chatterbot.response_selection.get_most_frequent_response"
        },
        {
            'import_path': 'chatterbot.logic.LowConfidenceAdapter',
            'threshold': 0.65,
            'default_response': 'Disculpa, estoy aprendiendo a entenderte. ¿Puedes ser mas especifico?'
        },
        {
            'import_path': 'chatterbot.logic.SpecificResponseAdapter',
            'input_text': 'Desarrollador',
            'output_text': 'Ok, Facebook: https://www.facebook.com/pdts31'
        }
    ],

   preprocessors=[
        'chatterbot.preprocessors.clean_whitespace'
    ], 
    #Autoentrenamiento
    read_only=False,
)
#DEFAULT_SESSION_ID =chatbot.default_session.id

chatbot.set_trainer(ChatterBotCorpusTrainer)
chatbot.train("./train.yml")

while True:
    input_statement = chatbot.input.process_input_statement()
    statement, response = chatbot.generate_response(input_statement, 1)
    print("\n%s\n\n"%response)
Exemplo n.º 9
0
    if 'yes' in text.lower():
        return True
    elif 'no' in text.lower():
        return False
    else:
        print('Please type either "Yes" or "No"')
        return get_feedback()


print('Type something to begin...')

# The following loop will execute each time the user enters input
while True:
    try:
        input_statement = chatbot.input.process_input_statement()
        # conversation_id = chatbot.storage.create_conversation()
        statement, response = chatbot.generate_response(input_statement,
                                                        conversation_id=None)
        print('Is "{}" an appropriate response to "{}"?'.format(
            response.text, input_statement))
        if get_feedback():
            chatbot.learn_response(response, input_statement)
        else:
            print('Say what??')
            better = chatbot.input.process_input_statement()
            chatbot.learn_response(better, input_statement)

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break
Exemplo n.º 10
0
    if 'Yes' in text:
        return True
    elif 'No' in text:
        return False
    else:
        print('Please type either "Yes" or "No"')
        return get_feedback()


print('Type something to begin...')

# The following loop will execute each time the user enters input
while True:
    try:
        input_statement = bot.input.process_input_statement()
        statement, response, confidence = bot.generate_response(
            input_statement)

        print('\n Is "{}" this a coherent response to "{}"? \n'.format(
            response, input_statement))

        if get_feedback():
            bot.learn_response(response)

        bot.output.process_response(response, confidence)

        # Update the conversation history for the bot
        # It is important that this happens last, after the learning step
        bot.recent_statements.append((
            statement,
            response,
        ))
    if 'Yes' in text:
        return True
    elif 'No' in text:
        return False
    else:
        print('Please type either "Yes" or "No"')
        return get_feedback()

print('Type something to begin...')

# The following loop will execute each time the user enters input
while True:
    try:
        input_statement = bot.input.process_input_statement()
        statement, response, confidence = bot.generate_response(input_statement)

        print('\n Is "{}" this a coherent response to "{}"? \n'.format(response, input_statement))

        if get_feedback():
            bot.learn_response(response,input_statement)

        bot.output.process_response(response, confidence)

        # Update the conversation history for the bot
        # It is important that this happens last, after the learning step
        bot.conversation_sessions.update(
            bot.default_session.id_string,
            (statement, response, )
        )
Exemplo n.º 12
0
            'Puedes reservarlo ahora en: https://www.royalcaribbean-espanol.com/'
        },
    ],
    preprocessors=['chatterbot.preprocessors.clean_whitespace'],
    read_only=True,
)

DEFAULT_SESSION_ID = chatbot.default_session

from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot.set_trainer(ChatterBotCorpusTrainer)
chatbot.train("./cruises_ES.yml")

print(
    "---------------------------------------------------------------------------"
)
print(
    "--------------------BIENVENIDO AL CHAT CON CARIBBEANBOT---------------------"
)
print(
    "---------------------------------------------------------------------------"
)
print("Has tu pregunta:")

while True:
    input_statement = chatbot.input.process_input_statement()
    statement, response = chatbot.generate_response(input_statement,
                                                    DEFAULT_SESSION_ID)
    print("\n%s\n\n" % response)
Exemplo n.º 13
0
class Edgar:
    def __init__(self):

        if not ValidacaoHelper.rodando('mongo'):
            system('echo "x89FiaNB" | sudo -S systemctl start mongodb')

        self.__bot = ChatBot(
            name='Edgar',
            preprocessors=['chatterbot.preprocessors.clean_whitespace'],
            logic_adapters=[{
                'import_path': 'chatterbot.logic.BestMatch',
            }],
            storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
            database_uri='mongodb://localhost:27017/chatterbot-database')
        self.__resposta = None
        self.idade = 0
        self.treinado = False
        self.sentenca_usuario = ''

    @property
    def bot(self):
        return self.__bot

    @property
    def resposta(self):
        return self.__resposta

    @property
    def resposta_str(self):
        return f'{self.__resposta}'

    def responda(self):
        if self.__resposta:
            return f"{self.__resposta}."
        else:
            return "Não há afirmações a serem respondidas."

    def escute(self, sentenca):
        self.__resposta = self.__bot.generate_response(Statement(sentenca))
        self.sentenca_usuario = sentenca

    def aprenda(self, resposta_valida, sentenca):
        self.__resposta = resposta_valida
        treinador_resposta_correta = ListTrainer(self.__bot)
        treinador_resposta_correta.train([sentenca, resposta_valida])

    def cantar(self):
        iniciar_canto()
        mixer.music.load("./Sounds/music.mp3")
        mixer.music.play()
        mixer.music.set_volume(1)

        clock = time.Clock()
        clock.tick(10)

        while mixer.music.get_busy():
            event.poll()
            clock.tick(10)

    @property
    def apresentacao(self):
        return f'\t\t {"*" * 15} Programa de testes com o robô Edgar {"*" * 15} ' \
            '\nVocê terá uma conversa com o Edgar, para sair digite "Edgar, por hoje é só"'
        return True
    elif 'no' in text.lower():
        return False
    else:
        print('Please type either "Yes" or "No"')
        return get_feedback()


print('Type something to begin...')

# The following loop will execute each time the user enters input
while True:
    try:
        input_statement = Statement(text=input())
        response = bot.generate_response(
            input_statement
        )

        print('\n Is "{}" a coherent response to "{}"? \n'.format(
            response.text,
            input_statement.text
        ))
        if get_feedback():
            print('please input the correct one')
            correct_response = Statement(text=input())
            bot.learn_response(correct_response, input_statement)
            print('Responses added to bot!')

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break
Exemplo n.º 15
0
class Wheatley:
    def __init__(self, bot):
        logging.basicConfig(level=logging.INFO)

        self.bot = bot
        self.ping_replace = re.compile(r"<@[0-9]{2,}>", re.IGNORECASE)

        with open('./config/wheatley.json') as data_file:
            self.wheatley_config = json.load(data_file)

        self.chatbot = ChatBot(
            'akhrot',
            logic_adapters=["chatterbot.logic.BestMatch"],
            trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
            storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
            database=self.wheatley_config['database'],
            database_uri=self.wheatley_config['database_uri'])
        self.admin_roles = self.wheatley_config['admin-roles']

    def write_to_yaml(self, messages):
        file_handle = open(self.wheatley_config['corpus-folder'] +
                           str(time.time()) + '.yml',
                           'w+',
                           encoding='utf-8')
        file_handle.write('categories:\n- discord-chat\nconversations:\n')
        alt = True
        for message in messages:
            msg = self.ping_replace.sub('', message.content).replace(
                '"', "'").replace('\\', '\\\\')
            if alt:
                file_handle.write('- - "' + msg + '"\n')
            else:
                file_handle.write('  - "' + msg + '"\n')
            alt = not alt
        file_handle.close()

    async def download_messages(self, channel, limit, is_all, current_count,
                                last_msg, msg_handle):
        before = None
        dwnld_limit = 100

        if last_msg is not None:
            before = last_msg

        if (not is_all and current_count >= limit):
            await self.bot.edit_message(msg_handle,
                                        'Finished downloading messages.')
            return current_count

        batch_size = 0
        msg_set = []
        async for message in self.bot.logs_from(channel,
                                                limit=dwnld_limit,
                                                before=before):
            batch_size += 1
            last_msg = message
            msg_set.append(message)

        self.write_to_yaml(msg_set)

        await self.bot.edit_message(
            msg_handle, 'Downloaded ' + str(current_count) + ' messages.')
        current_count += batch_size
        if batch_size < 100:
            await self.bot.edit_message(msg_handle,
                                        'Finished downloading messages.')
            return current_count
        else:
            return current_count + await self.download_messages(
                channel, limit, is_all, current_count, last_msg, msg_handle)

    @commands.command(pass_context=True, no_pm=True)
    async def dwnld(self, ctx, limit: str, channel: discord.Channel):
        if (len(
                set([role.name.lower() for role in ctx.message.author.roles
                     ]).intersection(set(self.admin_roles))) == 0):
            await self.bot.send_message(ctx.message.channel,
                                        'Unauthorized to issue this command.')
            return
        logging.info('issued download with: ' + limit + ', in :' +
                     channel.name + '.')
        resp = await self.bot.send_message(ctx.message.channel,
                                           'Downloading messages.')
        is_all = False
        if (limit == 'all'):
            is_all = True
            limit = None
        else:
            limit = int(limit)
        await self.download_messages(channel, limit, is_all, 0, None, resp)

    @commands.command(pass_context=True, no_pm=True)
    async def train(self, ctx):
        if (len(
                set([role.name.lower() for role in ctx.message.author.roles
                     ]).intersection(set(self.admin_roles))) == 0):
            await self.bot.send_message(ctx.message.channel,
                                        'Unauthorized to issue this command.')
            return
        logging.info('issued train command.')
        msg_handle = await self.bot.say('Issued the train command.')
        self.chatbot.train(self.wheatley_config['corpus-folder'])
        await self.bot.edit_message(msg_handle, 'Finished training.')

    async def talk(self, message):
        logging.info('MSG: ' + message.content + ' in ' + message.channel.name)

        luck = random()
        if ('hey wheatley' in message.content.lower()):
            if (luck < 0.33):
                await self.bot.send_message(message.channel, 'yes bby')
            elif (luck >= 0.33 and luck < 0.66):
                await self.bot.send_message(message.channel, 'idk man')
            else:
                await self.bot.send_message(message.channel, 'f**k no my dewd')
        elif ('magnet' in message.content.lower()):
            await self.bot.send_message(
                message.channel,
                ''.join(choice(ascii_letters) for x in range(15)))
        else:
            if (luck > 0.33):
                logging.info('trigerred')
                start_time = time.time()
                try:
                    await self.bot.send_typing(message.channel)
                except:
                    pass  #f**k it
                if (message.channel.name != 'general'):
                    _, response = self.chatbot.generate_response(
                        self.chatbot.input.process_input_statement(
                            message.content),
                        self.chatbot.default_session.uuid)
                else:
                    response = self.chatbot.get_response(message.content)

                end_time = time.time()
                logging.info('Time taken for response:' +
                             str(end_time - start_time))

                await self.bot.send_message(message.channel, response.text)
Exemplo n.º 16
0
class Wheatley:
    def __init__(self, bot):
        logging.basicConfig(level=logging.INFO)

        self.bot = bot
        self.ping_replace = re.compile(r"<@!{0,1}@&{0,1}[0-9]{2,}>",
                                       re.IGNORECASE)

        with open('./config/wheatley.json') as data_file:
            self.wheatley_config = json.load(data_file)

        logging.info('CSTRING:' +
                     self.wheatley_config[self.wheatley_config['database_type']
                                          + '_database_uri'])

        if (self.wheatley_config['database_type'] == "mongo"):
            self.chatbot = ChatBot(
                'wheatley',
                logic_adapters=["chatterbot.logic.BestMatch"],
                trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
                storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
                database=self.wheatley_config['database'],
                database_uri=self.wheatley_config[
                    self.wheatley_config['database_type'] + '_database_uri'])
        elif (self.wheatley_config['database_type'] == "mysql"):
            self.chatbot = ChatBot(
                'wheatley',
                logic_adapters=["chatterbot.logic.BestMatch"],
                trainer='chatterbot.trainers.ChatterBotCorpusTrainer',
                storage_adapter='chatterbot.storage.SQLStorageAdapter',
                database_uri=self.wheatley_config[
                    self.wheatley_config['database_type'] + '_database_uri'])

        self.admin_roles = self.wheatley_config['admin-roles']

    def write_to_yaml(self, messages):
        file_handle = open(self.wheatley_config['corpus-folder'] +
                           str(time.time()) + '.yml',
                           'w+',
                           encoding='utf-8')
        corpus_dict = {'categories': ['discord-chat'], 'conversations': []}

        for stim, resp in zip(messages[0::2], messages[1::2]):
            stim = self.ping_replace.sub('',
                                         stim.content).replace('\\', '\\\\')
            resp = self.ping_replace.sub('',
                                         resp.content).replace('\\', '\\\\')

            if (self.wheatley_config['max_dialog_length'] is not -1):
                stim = stim[:self.wheatley_config['max_dialog_length']]
                resp = resp[:self.wheatley_config['max_dialog_length']]

            corpus_dict['conversations'].append([stim, resp])

        file_handle.write(yaml.dump(corpus_dict, default_flow_style=False))
        file_handle.close()

    async def download_messages(self, channel, limit, is_all, current_count,
                                last_msg, msg_handle):
        before = None
        dwnld_limit = 100

        if last_msg is not None:
            before = last_msg

        if (not is_all and current_count >= limit):
            await self.bot.edit_message(msg_handle,
                                        'Finished downloading messages.')
            return current_count

        batch_size = 0
        msg_set = []
        async for message in self.bot.logs_from(channel,
                                                limit=dwnld_limit,
                                                before=before):
            batch_size += 1
            last_msg = message
            msg_set.append(message)

        self.write_to_yaml(msg_set)

        if (current_count % 1000 == 0):
            await self.bot.edit_message(
                msg_handle, 'Downloaded ' + str(current_count) + ' messages.')

        current_count += batch_size
        if batch_size < 100:
            await self.bot.edit_message(msg_handle,
                                        'Finished downloading messages.')
            return current_count
        else:
            return current_count + await self.download_messages(
                channel, limit, is_all, current_count, last_msg, msg_handle)

    @commands.command(pass_context=True, no_pm=True)
    async def dwnld(self, ctx, limit: str, channel: discord.Channel):
        if (len(
                set([role.name.lower() for role in ctx.message.author.roles
                     ]).intersection(set(self.admin_roles))) == 0):
            await self.bot.send_message(ctx.message.channel,
                                        'Unauthorized to issue this command.')
            return
        logging.info('issued download with: ' + limit + ', in :' +
                     channel.name + '.')
        resp = await self.bot.send_message(ctx.message.channel,
                                           'Downloading messages.')
        is_all = False
        if (limit == 'all'):
            is_all = True
            limit = None
        else:
            limit = int(limit)
        await self.download_messages(channel, limit, is_all, 0, None, resp)

    @commands.command(pass_context=True, no_pm=True)
    async def train(self, ctx):
        if (len(
                set([role.name.lower() for role in ctx.message.author.roles
                     ]).intersection(set(self.admin_roles))) == 0):
            await self.bot.send_message(ctx.message.channel,
                                        'Unauthorized to issue this command.')
            return
        logging.info('issued train command.')
        msg_handle = await self.bot.say('Issued the train command.')
        self.chatbot.train(self.wheatley_config['corpus-folder'])
        await self.bot.edit_message(msg_handle, 'Finished training.')

    async def talk(self, message):
        logging.info('MSG: ' + message.content)

        luck = random()
        if ('hey wheatley' in message.content.lower()):
            if (luck < 0.33):
                await self.bot.send_message(message.channel, 'yes bby')
            elif (luck >= 0.33 and luck < 0.66):
                await self.bot.send_message(message.channel, 'idk man')
            else:
                await self.bot.send_message(message.channel, 'f**k no my dewd')
        elif ('magnet' in message.content.lower()):
            await self.bot.send_message(
                message.channel,
                ''.join(choice(ascii_letters) for x in range(15)))
        else:
            if (luck > 0.33):
                logging.info('trigerred')
                start_time = time.time()

                conv_id = self.chatbot.default_conversation_id
                if not conv_id:
                    conv_id = self.chatbot.storage.create_conversation()

                if (message.channel.is_private
                        and message.author.id == '<your_id>'):
                    logging.info('IN DMS')
                elif (not message.channel.is_private):
                    logging.info('IN CHANNEL:' + message.channel.name)
                else:
                    logging.info('UNAUTHORIZED DMS FROM:' +
                                 message.author.name + ' #' +
                                 message.author.id)
                    return

                try:
                    await self.bot.send_typing(message.channel)
                except:
                    pass  #f**k it

                if (message.channel.name != 'general'):
                    _, response = self.chatbot.generate_response(
                        self.chatbot.input.process_input_statement(
                            message.content), conv_id)
                else:
                    response = self.chatbot.get_response(message.content)

                end_time = time.time()
                logging.info('Time taken for response:' +
                             str(end_time - start_time))

                clean_msg = self.ping_replace.sub('', response.text)
                try:
                    await self.bot.send_message(message.channel, clean_msg)
                except discord.errors.Forbidden as ex:
                    logging.info(str(ex))
    if 'yes' in text.lower():
        return False
    elif 'no' in text.lower():
        return True
    else:
        print('Please type either "Yes" or "No"')
        return get_feedback()


print("Type something to begin...")

# The following loop will execute each time the user enters input
while True:
    try:
        input_statement = bot.input.process_input_statement()
        statement, response = bot.generate_response(input_statement, CONVERSATION_ID)

        bot.output.process_response(response)
        print('\n Is "{}" a coherent response to "{}"? \n'.format(response, input_statement))
        if get_feedback():
            print("please input the correct one")
            response1 = bot.input.process_input_statement()
            bot.learn_response(response1, input_statement)
            bot.storage.add_to_conversation(CONVERSATION_ID, statement, response1)
            print("Responses added to bot!")

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break
    if 'Yes' in text:
        return True
    elif 'No' in text:
        return False
    else:
        print('Please type either "Yes" or "No"')
        return get_feedback()


print('Type something to begin...')

# The following loop will execute each time the user enters input
while True:
    try:
        input_statement = bot.input.process_input_statement()
        statement, response = bot.generate_response(input_statement, DEFAULT_SESSION_ID)

        print('\n Is "{}" this a coherent response to "{}"? \n'.format(response, input_statement))

        if get_feedback():
            bot.learn_response(response,input_statement)

        bot.output.process_response(response)

        # Update the conversation history for the bot
        # It is important that this happens last, after the learning step
        bot.conversation_sessions.update(
            bot.default_session.id_string,
            (statement, response, )
        )
Exemplo n.º 19
0
class NLG_unit(object):

	""" This object contains tools to answer in natural language any message non-Fib related

	Attributes:
		chatterbot_bot(:class:`chatterbot.ChatBot`): chatterbot bot to process the non-fib-Related questions
		train_queue(:obj:`dict`): dictionary that act as a queue of training concepts
		conversation_id(:obj:`int` or None): Identifier that keeps track of the diferent amounts of conversations learnt
	"""
	def __init__(self):
		self.chatterbot_bot = ChatBot(
			"Fibot",
			storage_adapter="chatterbot.storage.SQLStorageAdapter",
		)
		self.train_queue = {}
		self.conversation_id = None

	"""
		This function load the learnt model for chatterbot
	"""
	def load(self):
		self.conversation_id = self.chatterbot_bot.storage.create_conversation()

	"""
		Parameters:
			chat_id (:obj:`str`): chat_id of the person to get feedback from
			correct (:obj:`bool`): tells whether the prediction was correct_statement
			correct_statement (:obj:`str` or None): Correction if there is

		This function enables the chatterbot bot to learn if he predicted good and allows
		him to learn new responses.
	"""
	def give_feedback(self, chat_id, correct = True, correct_statement = None):
		if not correct:
			message = self.train_queue[chat_id]['message']
			correct_statement = Statement(correct_statement)
			self.chatterbot_bot.learn_response(correct_statement, message)
			self.chatterbot_bot.storage.add_to_conversation(self.conversation_id, message, correct_statement)
			self.send_message(chat_id, "Aprendido!. Mándame más si quieres, o desactívame usando /train_off")
		else:
			self.send_message(chat_id, "Bien. Mándame más si quieres, o desactívame usando /train_off")

	"""
		Parameters:
			chat_id (:obj:`str`): chat_id of the person to process the answer for
			message (:obj:`str`): message the user introduced to be processed

		This function makes the bot predict the following message, and
		asks for checks.
	"""
	def process_answer_training(self, chat_id, message):
		print("Query de %s con mensaje %s"%(chat_id, message))
		self.send_chat_action(chat_id)
		input_statement = Statement(message)
		statement, response = self.chatterbot_bot.generate_response(input_statement, self.conversation_id)
		self.send_message(chat_id,'Es "{}" una respuesta coherente a "{}"? (Sí/No)'.format(response, message))
		self.train_queue[chat_id] = {
			'message': input_statement,
			'response': response
		}

	"""
		Parameters:
			message (:obj:`str`): message the user introduced to be processed
			debug (:obj:`bool`): indicates the level of verbosity

		This function returns the predicted responses for message
	"""
	def get_response(self, message, debug = False):
		input_statement = Statement(message)
		_, response = self.chatterbot_bot.generate_response(input_statement, self.conversation_id)
		if debug:
			return "%s, confidence = %d"%(response['text'], response['confidence'])
		else:
			return str(response)

	"""
		Parameters:
			chat_id (:obj:`str`): chat_id of the person to process the answer for
			message (:obj:`str`): content of the messages

		This function allows nlg class to send messages for the training duties
	"""
	def send_message(self, chat_id, message):
		params = {
			'chat_id': chat_id,
			'text': message
		}
		bot_token = os.getenv('FibotTOKEN')
		base_url = 'https://api.telegram.org/bot%s/sendMessage'%bot_token
		response = requests.get(base_url, params = params)

	"""
		Parameters:
			chat_id (:obj:`str`): chat_id of the person to process the answer for
			action (:obj:`str`): action to send of the messages

		This function allows nlg class to send chat_action for the training duties
	"""
	def send_chat_action(self, chat_id, action = ChatAction.TYPING):
		params = {
			'chat_id': chat_id,
			'action': action
		}
		bot_token = os.getenv('FibotTOKEN')
		base_url = 'https://api.telegram.org/bot%s/sendChatAction'%bot_token
		response = requests.get(base_url, params = params)
    ],
    preprocessors=['chatterbot.preprocessors.clean_whitespace'],
)
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('./soporte.yml')
levenshtein_distance = LevenshteinDistance()
#synset_distance = SynsetDistance()
#sentiment_comparison = SentimentComparison()
#jaccard_similarity = JaccardSimilarity()

disparate = Statement(
    'Te has equivocado')  #convertimos una frase en un tipo statement
entradaDelUsuario = ""  #variable que contendrá lo que haya escrito el usuario

while entradaDelUsuario != "adios":
    entradaDelUsuario = Statement(text=input())  #leemos la entrada del usuario
    respuesta = chatbot.generate_response(entradaDelUsuario)
    try:
        fecha = datetime_parsing(entradaDelUsuario.text)
        fecha = fecha[0]
        print(fecha[0])
    except:
        pass
    if levenshtein_distance.compare(entradaDelUsuario, disparate) > 0.51:
        print('¿Qué debería haber dicho?')
        entradaDelUsuarioCorreccion = Statement(input())
        chatbot.learn_response(entradaDelUsuarioCorreccion, entradaDelUsuario)
        print("He aprendiendo que cuando digas {} debo responder {}".format(
            entradaDelUsuario.text, entradaDelUsuarioCorreccion.text))

    print(respuesta)
Exemplo n.º 21
0
class Chatterbot:
    def __init__(self, bot):
        self.bot = bot
        self.settings = dataIO.load_json('data/chatterbot/settings.json')
        self.chatterbot = ChatBot('Athena',
                                  database='LanLogFour',
                                  storage_adapter='chatterbot.storage.'
                                  'MongoDatabaseAdapter',
                                  input_adapter='chatterbot.input.'
                                  'VariableInputTypeAdapter',
                                  output_adapter='chatterbot.output.'
                                  'OutputAdapter',
                                  output_format='text',
                                  logic_adapters=[
                                      {'import_path': 'chatterbot.logic.'
                                       'BestMatch',
                                       'statement_comparison_function':
                                       'chatterbot.comparisons.'
                                       'levenshtein_distance',
                                       'response_selection_method':
                                       'chatterbot.response_selection.'
                                       'get_most_frequent_response'},
                                      'chatterbot.logic.MathematicalEvaluation'
                                      ]
                                  )
        self.conversations = {}
        self.previous_statement = {}

    @commands.command(pass_context=True)
    async def chat(self, ctx):
        """Reads messages from chat"""
        message = ctx.message.content[6:]
        conversation_id = self._get_conversation(ctx.message.channel.id)
        response = await self._get_response(message, conversation_id)
        await self.bot.say(response)

    @commands.command()
    @checks.serverowner_or_permissions(manage_server=True)
    async def chattertraindocs(self):
        """Runs training on the docs"""
        self.chatterbot.set_trainer(ListTrainer)
        with open('data/chatterbot/doc1.txt') as f:
            doc1 = f.readlines()
        with open('data/chatterbot/doc2.txt') as f:
            doc2 = f.readlines()
        docData = doc1 + doc2
        docData = [x.strip(',') for x in docData]
        docData = [x.strip('\'') for x in docData]
        docData = [x.strip('\n') for x in docData]
        self.chatterbot.train(docData)
        await self.bot.say("Training complete.")

    @commands.command()
    @checks.serverowner_or_permissions(manage_server=True)
    async def chattertrain(self):
        self.chatterbot.set_trainer(ChatterBotCorpusTrainer)
        self.chatterbot.train("chatterbot.corpus.english")
        await self.bot.say("Training complete")

    @commands.command(no_pm=True, pass_context=True)
    @checks.serverowner_or_permissions(manage_server=True)
    async def chatchannel(self, context, channel: discord.Channel = None):
        """
        Set the channel to which the bot will sent its continues updates.
        Example: [p]chatchannel #talk
        """
        if channel:
            self.settings['CHANNEL_ID'] = str(channel.id)
            dataIO.save_json('data/chatterbot/settings.json', self.settings)
            message = 'Channel set to {}'.format(channel.mention)
        elif not self.settings['CHANNEL_ID']:
            message = 'No Channel set'
        else:
            channel = discord.utils.get(
                self.bot.get_all_channels(), id=self.settings['CHANNEL_ID'])
            if channel:
                message = 'Current channel is {}'.format(channel.mention)
            else:
                self.settings['CHANNEL_ID'] = None
                message = 'No channel set'

        await self.bot.say(message)

    @commands.command(pass_context=True)
    @checks.serverowner_or_permissions(manage_server=True)
    async def chatterignore(self, context, channel: discord.Channel = None):
        if channel:
            self.settings['BLOCKED_CHANNELS'].append(channel.id)
            # TODO: Check if already in list
            dataIO.save_json('data/chatterbot/settings.json', self.settings)
            message = '{} added to blocked channels.'.format(channel.mention)
        elif not self.settings['BLOCKED_CHANNELS']:
            message = 'No channels blocked'
        # else:
        #    channel = discord.utils.get(
        #        self.bot.get_all_channels(),
        #        id=self.settings['BLOCKED_CHANNELS'])
        #    if channel:
        #        message = 'Current channel is {}'.format(channel.mention)
        #    else:
        #        self.settings['CHANNEL_ID'] = None
        #        message = 'No channel set'

        await self.bot.say(message)

    async def listener(self, message):
        if message.author.id == self.bot.user.id:
            pass
        elif message.content == '':
            pass
        elif message.content[0] == '!':  # Kludge
            pass
        elif message.mention_everyone is True:
            pass
        elif message.mentions != []:
            pass
        elif message.role_mentions != []:
            pass
        elif message.channel.id == self.settings['CHANNEL_ID']:
            conversation_id = self._get_conversation(message.channel.id)
            response = await self._get_response(message.content,
                                                conversation_id)
            await self.bot.send_message(message.channel, response)
        elif message.channel.id not in self.settings['BLOCKED_CHANNELS']:
            conversation_id = self._get_conversation(message.channel.id)
            input_statement = self.chatterbot.input.process_input_statement(
                message.content)
            if conversation_id in self.previous_statement:
                self.chatterbot.learn_response(
                    input_statement, self.previous_statement[conversation_id])
                self.previous_statement[conversation_id] = input_statement
            else:
                self.previous_statement[conversation_id] = input_statement
        else:
            pass

    async def _get_response(self, input_item, conversation_id):
        input_statement = self.chatterbot.input.process_input_statement(
            input_item)
        # Preprocess the input statement
        for preprocessor in self.chatterbot.preprocessors:
            input_statement = preprocessor(self.chatterbot, input_statement)
        statement, response = self.chatterbot.generate_response(
            input_statement, conversation_id)
        # Learn that the user's input was a valid response to the chat bot's
        # previous output
        if not self.chatterbot.read_only:
            if conversation_id in self.previous_statement:
                prev = self.previous_statement[conversation_id]
            else:
                prev = None
            self.chatterbot.learn_response(statement, prev)
            self.chatterbot.storage.add_to_conversation(conversation_id,
                                                        statement, response)
            self.previous_statement[conversation_id] = response
        # Process the response output with the output adapter
        return str(response)

    def _get_conversation(self, channel_id):
        try:
            conversation_id = self.conversations[channel_id]
        except KeyError:
            conversation_id = self.chatterbot.storage.create_conversation()
            self.conversations[channel_id] = conversation_id
        return conversation_id
        table = str.maketrans('', '', string.punctuation)
        stripped = [w.translate(table) for w in words]
        for w in stripped:
            if w == "":
                stripped.remove(w)
            elif w == " ":
                stripped.remove(w)
        filtered_sen_pun = ' '.join(stripped)
        print('Punc :', filtered_sen_pun)

        # Lowering the case
        #filtered_sent=filtered_sen_pun.lower()
        input_statement = Statement(filtered_sen_pun)
        print('-' * 100)
        print('input_statement ==>', input_statement)
        response = bot.generate_response(input_statement)
        print('=' * 100)
        print("Chatbot :", response.text)

        print('\n Is "{}" a coherent response to "{}"? \n'.format(
            response.text, input_statement.text))
        if get_feedback():
            print('please input the correct one')
            correct_response = Statement(text=input())
            bot.learn_response(correct_response, input_statement)
            print('Responses added to bot!')

    # Press ctrl-c or ctrl-d on the keyboard to exit
    except (KeyboardInterrupt, EOFError, SystemExit):
        break
Exemplo n.º 23
0
class ChatClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super(ChatClient, self).__init__(*args, **kwargs)

        self.bot = ChatBot(
            'Fred',
            storage_adapter='chatterbot.storage.SQLStorageAdapter',
            database='./db.sqlite3')

        self.commands = {'ping': self.ping, 'train': self.train}

    @asyncio.coroutine
    def ping(self, message):
        yield from self.send_message(message.channel, content="pong")

    @asyncio.coroutine
    def train(self, message):
        if message.channel.is_private:
            yield from self.send_message(
                message.channel,
                content=
                ":stuck_out_tongue: Sorry you have to teach me on a server where I can check your role."
            )
            return

        if not "Bot Trainer" in [role.name for role in message.author.roles]:
            yield from self.send_message(
                message.channel,
                content=
                ":unamused: Only user with the 'Bot Trainer' role can train me."
            )
            return

        if not "(:)" in message.content:
            yield from self.send_message(
                message.channel,
                content=
                ":confused: You have no reply for me to learn. Use (:) to seperate message."
            )
            return

        train_times = 1
        if "(super_train)" in message.clean_content:
            train_times = 100
            yield from self.send_message(
                message.channel,
                content=f":clock: super_train underway please be patient")

        learn_message, learn_reply = message.clean_content.replace(
            "!" + get_command(message.content),
            "").replace("(super_train)", "").split("(:)")

        self.learn(learn_message, learn_reply, train_times=train_times)

        yield from self.send_message(
            message.channel,
            content=
            f"learnt: \n message = {learn_message} \n reply = {learn_reply}")

    def corpus_train():
        self.bot.set_trainer(ChatterBotCorpusTrainer)

        self.bot.train("chatterbot.corpus.english", )

    def learn(self, message, reply, train_times=1):
        logging.info("--- Learning ---")
        message = remove_mentions(message)
        reply = remove_mentions(reply)

        self.bot.set_trainer(ListTrainer)

        self.bot.train([
            message,
            reply,
        ] * train_times)

        logging.info("learning message: " + message)
        logging.info("learning reply: " + reply)

    @asyncio.coroutine
    def on_ready(self):
        logging.info('Connected!')
        logging.info('Username: '******'ID: ' + self.user.id)

    @asyncio.coroutine
    def send_reply(self, message):
        logging.info("--- Sending Reply ---")
        message_without_mentions = remove_mentions(message.clean_content)

        reply = str(
            self.bot.generate_response(Statement(message_without_mentions),
                                       None)[1])
        yield from self.send_message(message.channel, content=reply)

        logging.info("message: " + message_without_mentions)
        logging.info("reply: " + reply)

    @asyncio.coroutine
    def on_message(self, message):
        if message.author == self.user:
            return

        if message.content.startswith("!"):
            command = get_command(message.clean_content)
            try:
                yield from self.commands[command](message)
            except KeyError:
                yield from self.send_message(
                    message.channel,
                    content=(command +
                             ":stuck_out_tongue: is not a registered command"))

            return

        if self.user in message.mentions or message.channel.is_private:
            yield from self.send_reply(message)
        else:
            if message.clean_content.endswith("?") or len(
                    message.mentions) > 0:
                reply = yield from self.wait_for_message()
                if reply.author in [self.user, message.author]:
                    logging.info("forgetting conversation")
                    return

                self.learn(message.clean_content, reply.clean_content)