1

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.

enter image description here

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)))
0stone0
  • 34,288
  • 4
  • 39
  • 64
Yash Dwivedi
  • 47
  • 1
  • 5
  • 2
    Hi. Please remove the tags for `python-telegram-bot` and `php-telegram-bot`. The former is a different python library and the latter clearly is inappropriate because you're using python. Instead use the tag `py-telegram-bot-api` which is for the library that you use ;) – CallMeStag Jun 29 '21 at 11:35

1 Answers1

1

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!')
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Great I got it! But one thing is still not cleared that what should I do to make the bot reply ' Sorry I don't get it!' when typing anything random. – Yash Dwivedi Jun 29 '21 at 12:59
  • 1
    Please see my edit. Using a `if`, `elif` and `else` should be enough. – 0stone0 Jun 29 '21 at 14:02