Chatbot not understanding registered phrases

Asked

Viewed 201 times

-3

I’m developing a Chatbot called "Joker" for use in a Telegram group. The Bot must respond only if its name (Joker) is quoted in a sentence, otherwise it must remain "silent" without interfering with the group’s conversation. However, he "wakes up" and responds with a null value, "None" to any message sent to the group. With the word Joker contained in the phrase, the Bot is not understanding the predefined questions, registered in your training and answers with one of the standard answers to questions not yet learned.

  • User: Good morning, you guys!
  • Bot: None
  • User: Good morning, Joker
  • Bot: I’m sorry, I didn’t get your message.
def respond(self, message):
    """
    Receive message from user and returns corresponding answer.
    """
    if re.search("joker", message, re.IGNORECASE):
        joker_na_mensagem = True
    else:
        joker_na_mensagem = False

    if joker_na_mensagem and len(message) > 50 and self.watson_usage:
        top_answer = get_analysis(message)
        return f"Hmm, você está falando sobre {top_answer}"
    elif joker_na_mensagem and len(message.strip()) == len("joker"):
        return "Algo de errado não está certo. 
                Digite /info para saber mais."
    elif joker_na_mensagem:
        return self.comm.get_response(self.clean(message))
  • The question cited, is mine and has a different context, not fitting the answer I seek. I elaborated better the question for a better understanding.

  • 1

    You should edit the previous reset by correcting the question and not duplicating

  • 1

    This is not a duplicate. The current question departs from the purpose of the original question. I was advised by a user who was helping me to elaborate a new question. For this reason, I did not edit the previous one and asked this question.

  • 1

    The user steered you right, but if the original question ran away from what you were looking for, it was only necessary to elaborate a new question and edit the previous one and not create duplicate questions just because you didn’t get the answer you expected.

1 answer

0

This code should remove 'Joker' from the message to be parsed.

def respond(self, message):
    """
    Receive message from user and returns corresponding answer.
    """
    if re.search("joker", message, re.IGNORECASE):
        joker_na_mensagem = True
    else:
        joker_na_mensagem = False

    mensagem_sem_joker = re.sub(r'\bjoker\b', '', message, flags=re.IGNORECASE)
    # remove espaços duplicados
    mensagem_sem_joker = re.sub(r'\s{2,}', ' ', mensagem_sem_joker)

    if joker_na_mensagem and len(message) > 50 and self.watson_usage:
        top_answer = get_analysis(mensagem_sem_joker)
        return f"Hmm, você está falando sobre {top_answer}"
    elif joker_na_mensagem and len(message.strip()) == len("joker"):
        return "Algo de errado não está certo." \
               "Digite /info para saber mais."
    elif joker_na_mensagem:
        return self.comm.get_response(self.clean(mensagem_sem_joker))

As for the answer None, you need to edit your code so that if the function respond return None, you do not pass this value to the user, because the None means there is no response to that message, probably because it was not directed to the bot.

Since I don’t have access to the rest of the code, I can’t fix this for you.


Edit

In the code you provided via Dropbox, there is the following snippet in the file bot/application.py:

def text_message(self, bot, update):
    self.send_type_action(bot, update)

    if not self.check_for_emotion(update):
        message = update.effective_message.text
        update.effective_message.reply_text(
            str(self.comm.respond(message))
        )
    return 0

I believe this is the reason why the bot is responding to messages with None. This code snippet is calling update.effective_message.reply_text regardless of what was returned by the function respond.

To fix this, replace the whole above with the following code:

def text_message(self, bot, update):
    self.send_type_action(bot, update)

    if not self.check_for_emotion(update):
        message = update.effective_message.text
        resposta = self.comm.respond(message)
        if resposta:
            update.effective_message.reply_text(resposta)
    return 0

What this code does, is to check if the function respond returned something. If yes, call the function reply_text with the result.
As the function respond only returns string or None, the conversion of types made by str is unnecessary and has been removed.

Note: I realized that you were copying wrong. Therefore, the syntax errors.
The structure of a python function is the way I wrote it. Never align the body of a function to its first line.

  • @Jacob this error says that I referenced message sem_joker before creating it, however, I did not do this. I think you may have changed the formatting of the code. Python is very strict in formatting the code. Copy as I did and try again. When to code in full, you gave me a public link. This link only works for the owner of the file. To share, you must make the folder public and copy the public link.

  • Traceback (Most recent call last): File "bot/application.py", line 19, in <module> from bot.Communication import Communication File "E: 01 - Chatbot project Master bot Communication.py", line 81 Return f"Hmm, you’re talking about {top_answer}" Syntaxerror: 'Return' Outside Function Code: https://www.dropbox.com/sh/nm1otj1xbc1nsp5/AAMKD9srT2nHLVHtNxYnfa?dl=0

  • @Jacob Atualizei.

  • I did everything right as you told me. Without changing the formatting of the code. A part of the error message: File "E: 01 - Chatbot Project Master venv lib site-Packages Telegram ext Dispatcher.py", line 279, in process_update Handler.handle_update(update, self) File "E: 01 - Chatbot Project Master venv lib site-Packages Telegram ext messagehandler.py", line 169, in handle_update Return self.callback(Dispatcher.bot, update, **optional_args) File "bot/application.py", line 166, in text_message update.effective_message.reply_text(reply)

  • Only by analyzing the complete code to better understand what happens. Each moment a different error appears. If you are willing and patient. I don’t want to take up your time, after all, you have helped me too much. The original code in which me aseio, is here: link

  • @Jacob enter complete error

  • telegram.ext.dispatcher - ERROR - An uncaught error was raised while processing the update&#xA;Traceback (most recent call last):&#xA; File "E:\01 - Projeto ChatBot Master\venv\lib\site-packages\telegram\ext\dispatcher.py", line 279, in process_update&#xA; handler.handle_update(update, self) File "E: 01 - Chatbot Project Master venv lib site-Packages Telegram ext messagehandler.py", line 169, in handle_update Return self.callback(Dispatcher.bot, update, **optional_args) File "bot/application.py", line 166, in text_message update.effective_message.reply_text(reply)

  • File "E:\01 - Projeto ChatBot Master\venv\lib\site-packages\telegram\message.py", line 455, in reply_text&#xA; return self.bot.send_message(self.chat_id, *args, **kwargs)&#xA; File "E:\01 - Projeto ChatBot Master\venv\lib\site-packages\telegram\bot.py", line 65, in decorator&#xA; result = func(self, *args, **kwargs) File "E: 01 - Chatbot Project Master venv lib site-Packages Telegram bot.py", line 90, in Decorator result = self. _request.post(url, date, timeout=kwargs.get('timeout'))

  • File "E: 01 - Project Chatbot Master venv lib site-Packages Telegram utils request.py", line 308, in post body=json.dumps(data). Encode('utf-8'), File "C: Users USER Appdata Local Programs Python Python37 lib json_init_.py", line 231, in dumps Return _default_encoder.Encode(obj) File "C: Users USER Appdata Local Programs Python Python37 lib json Encoder.py", line 199, in Encode Chunks = self.iterencode(o, _one_shot=True)

  • File "C: Users USER Appdata Local Programs Python Python37 lib json Encoder.py", line 257, in iterencode Return _iterencode(o, 0) File "C: Users USER Appdata Local Programs Python Python37 lib json Encoder.py", line 179, in default raise Typeerror(f'Object of type {o.class.name} ' Typeerror: Object of type Statement is not JSON serializable

  • @Jacob Did you fix the formatting that was wrong? I fear that you have introduced many errors in your code as this does not seem to be related to my solution to this question.

  • Yes @seu-Druga. All right, as you posted and indicated. I even deleted the venv folder, imagining some file that may have been corrupted, then reinstalled Python again, but it is still the same. I don’t know if it helps, but here’s what happens. Any message that is sent to the group, always appears, Joker is writing. As if he were "listening", but without responding. And he reacts as follows. >User: Hello >User: Hello Joker >User: Joker >Bot: Something’s not right. Type /info to learn more.

  • As I said, this error no longer seems to be related to the question. Nor does it make sense for me to look at the code from which you copied, because you modified it and there are great chances that you introduced these errors. I watched as long as I could, but now you must ascertain the errors that are appearing and formulate new questions. Be very detailed in your questions, if not, I will end up developing everything for you. This is not the purpose of the site. As you can see, there are many negative votes, as information, complete codes and the like are missing.

  • In fact, I did not make any changes to the code itself. I met the developer, who authorized me to use and modify freely. My change was only in Bot training, broadening his vocabulary and now with your help, trying to implement this feature. I really appreciate your help. Your tips were tops. It made all the difference in understanding. Unfortunately, because I am new to the forum, I am not allowed to vote yet. But here is recorded my vote of thanks. I will continue in development. Thanks very much. Thank you very much!

Show 9 more comments

Browser other questions tagged

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