skip to Main Content

I have this code..

import telebot

#telegram API 
api_key = os.environ['Tele_API_key']
bot = telebot.TeleBot(api_key)

@bot.message_handler(commands=['start'])
def help_command(message):
    bot.send_message(chat.id,"send a message")

@bot.message_handler(func = lambda msg: msg.text is not None and '/' not in msg.text)
    if message.text == "Hi":
        bot.send_message(chat.id,"Hello!")

It sends me "Hello" Everytime I send "Hi"

I want it to be like,
after I do /start
it should ask "send a message"
and when I send "Hello"
it should send "Hi"

But the problem is, it sends "Hi" everytime I send "Hello"

But I only want it to say "Hello" after I send /start and then the "Hi" message

I am beginner, Thanks for the help

2

Answers


  1. You was created object msg inside @message_handler , But haven’t used it.

    These are silly mistakes

    • message.text
    • chat.id

    Correct ✅

    • msg.text
    • msg.chat.id

    Final code

    @bot.message_handler(func = lambda msg: msg.text is not None and '/' not in msg.text)
    if msg.text == "Hi":
        bot.send_message(msg.chat.id,"Hello!")
    
    Login or Signup to reply.
  2. You can do like this

    @bot.message_handler(commands=[all_commands['start']])
    def say(message):
        bot.send_message(message.chat.id, "send a message")
    
    @bot.message_handler(func=lambda msg: msg.text is not None and '/' not in msg.text)
    def sayHi(message):
        if message.text == "Hi":
             bot.reply_to(message, "Hello!")
    

    You can reply a message with reply_to(message, "your reply text")

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search