Python Forum
How to make a telegram bot respond to the specific word in a sentence?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make a telegram bot respond to the specific word in a sentence?
#1
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 :)
Reply
#2
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...")
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python print all files which contain specific word in it mg24 5 1,188 Jan-27-2023, 11:20 AM
Last Post: snippsat
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,455 Aug-12-2021, 04:25 PM
Last Post: palladium
  Use of respond.get ebolisa 2 1,709 Jul-31-2021, 02:11 PM
Last Post: ebolisa
  while sentence kimyyya 3 2,905 Mar-20-2021, 06:00 AM
Last Post: Pedroski55
  List / arrays putting in sentence Kurta 3 2,514 Dec-25-2020, 11:29 AM
Last Post: Larz60+
  Not able to make a specific thing pause in pygame cooImanreebro 4 3,141 Dec-13-2020, 10:34 PM
Last Post: cooImanreebro
  Searching for specific word in text files. JellyCreeper6 1 1,694 Nov-03-2020, 01:52 PM
Last Post: DeaD_EyE
  How to match partial sentence in long sentence Mekala 1 1,486 Jul-22-2020, 02:21 PM
Last Post: perfringo
  Python Speech recognition, word by word AceScottie 6 15,857 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  Remove a sentence if it contains a word. lokhtar 6 5,770 Feb-11-2020, 04:43 PM
Last Post: stullis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020