'Python telegram bot - reply when user says specific words
Context: I am starting to learn how to code a telegram bot in python. I have successfully made a fun bot for my group with friends to use. However, i only want it to respond when specific words are mentioned apart from the commands that trigger it. Example: Whenever a user says the word "wen" plus any other word(s), i want the bot to reply with: SOON! I want the bot to only pick up some trigger words and reply and for the remainder of the chat to stay idle
Part of my code:
user_message = str(input_text).lower()
wenResponse = str("wen ").join(input_text)
if user_message + wenResponse:
return ("SOON!")
def handle_message(update,context):
text=str(update.message.text).lower()
response=sample_responses(text)
update.message.reply_text(response)
Actual result: The bot is working but only when the user says specifically "wen". If the user adds more words after "wen" the bot doesnt pick it up.
Solution 1:[1]
if "wen" in str(input_text).lower():
return "soon"
This should work even if the key word isn’t the first word.
Solution 2:[2]
You can just use .startswith('text')
to check is a string starts with 'text'
.
The .startswith('text')
return True
if the string starts with text
, or else it will retur False
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | BrainFl |