Python Forum
How to make a telegram bot respond to the specific word in a sentence? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to make a telegram bot respond to the specific word in a sentence? (/thread-22905.html)



How to make a telegram bot respond to the specific word in a sentence? - Metodolog - Dec-02-2019

So, I'm trying to make my bot respond whenever a certain word is said in a sentence (the language is Serbian), so I made this code:

if (message.text.lower().find('lav') != -1):
        bot.send_message(message.chat.id,  "Najgore pivo...")
Now, the bot is doing what I would like, when some somebody says:

"Popio sam lav"

it responds as it should.
But, the problem is that the word "lav" is also part in other words, for example:

"Nebo je plavo"

so the bot responds here as well and I want to block that.

I am just starting to play with python, so I would really appreciate help, tnx :)


RE: How to make a telegram bot respond to the specific word in a sentence? - stullis - Dec-02-2019

It's looking for any sequence of "lav" in the string. Here are two solutions.

1. Split the sentence up by white space. This will change the sentence to a list which you can iterate over, checking for the word.

sentence = message.text.lower()
if "lav" in sentence.split():
        bot.send_message(message.chat.id,  "Najgore pivo...")
2. Use a regular expression instead. "\blav\b" will do the trick.

import re

match_lav = re.compile("\blav\b")
matches = match_lav.findall(message.text.lower())

if len(matches) > 0:
        bot.send_message(message.chat.id,  "Najgore pivo...")



RE: How to make a telegram bot respond to the specific word in a sentence? - martabassof - Dec-22-2020

Hello,

I am super new with python and been having the same problem.

I currently have a bot running on Telegram which only responds to specific messages.

I want it to answer to specific words as well, contained in a sentence, but the code I found here seems not to work.

What can I do?

Thanks