Search code examples
pythontelegram

pyTelegramBotAPI - how to send the messages


I know how to reply to commands and messages with pyTelegramBotAPI But maybe do you know how to make it send the messages to my chat id without interaction? It doesn't execute lines of code below bot.polling()

import telebot
bot=telebot.TeleBot(API_KEY)

@bot.message_handler(content_types=['text'])

def send_text(message):
    bot.send_message(message.chat.id, 'text')

bot.polling(none_stop=True)

I want it to send the messages with a trigger on server side, not when I send a command to the bot.


Solution

  • The following line in your code:

    @bot.message_handler(content_types=['text'])
    

    Creates a message_handler, that can be used to reply on a message.


    Since you just want to send a regular message, without any reply logic, you can use use the bot.send_message method, without any handlers.

    Example:

    import telebot
    
    # Create bot
    bot = telebot.TeleBot(token='ABCDEFHHIJ:AAG2snRwz8jnFtVf8b0eyCueGJRD3hY9AaQ')
    
    # Send message
    bot.send_message(123456798, 'Hi! I\'m a Bot!')
    

    If I run this script, my Bot will send me the message, and terminates the script afterwards. Of course you could add the bot.polling at the bottom to let the Bot poll for replies or something similar.

    Visual result after running the script:

    enter image description here