I am creating a Telegram bot which would reply Hello
in random languages. Is working fine but the problem is it replies even when I send something randomly with no meaning like sfdsfjls
.
What should I do so that it replies only when I say Hi
or Hello
and reply something like I don't get it
when I send something random.
I am using pytelegrambotapi
.
My code:
import telebot
import random
bot_token =''
bot= telebot.TeleBot(token=bot_token)
lang1= ['Hola','Konnichiwa','Bonjour','Namaste']
# Handle normal messages
@bot.message_handler()
def send_welcome(message):
# Detect 'hi'
if message.text == 'hi' or 'hello':
bot.send_message(message.chat.id, (random.choice(lang1)))
You'll need
if message.text == 'hi' or message.text == 'hello':
Instead off
if message.text == 'hi' or 'hello':
Because the or 'hello'
part will always result in TRUE
as you can test here.
Another option, tho check if a string matches any other string could look something like this:
triggers = {'hi', 'hello'}
if message.text in triggers:
Applying those fixes, and adding a additional check based on the comment gives us the following code:
import telebot
import random
bot_token =''
bot= telebot.TeleBot(token=bot_token)
lang1= ['Hola','Konnichiwa','Bonjour','Namaste']
# Handle normal messages
@bot.message_handler()
def send_welcome(message):
# Detect Messages
if message.text == 'hi' or message.text == 'hello':
bot.send_message(message.chat.id, (random.choice(lang1)))
elif message.text == 'Test':
bot.send_message(message.chat.id, 'Test succeeded')
else:
bot.send_message(message.chat.id, 'Sorry I don\'t get it!')