Search code examples
python-telegram-bot

Send a spontaneous message from telegram bot to any user


I'm just getting to know python-telegram-bot, and I haven't found a way to send a spontaneous message to any user. I can only find examples where the user is only defined by their ID numbre. I would appreciate anyone who can help me with this. Thanks


from telegram.ext import Application, CommandHandler, MessageHandler, filters
from telegram.ext import ContextTypes, CallbackContext

async def send_message(context: CallbackContext):  
    
    chat_id = 1212121212  (example ID)
    """ 
    here, 1212121212 must be a variable, not just the ID number

    """
    text = "Message... "
    
    await context.bot.send_message(chat_id= chat_id, text=text, )


def main() -> None:

   token = os.getenv('TELEGRAM_BOT_TOKEN')
   app = Application.builder().token(token).build()

   app.add_handler(MessageHandler(filters.TEXT, handle_message))

   app.job_queue.run_repeating(send_message, interval=20, first=0)

   app.add_error_handler(error)

   app.run_polling(poll_interval=2, timeout=5)


if __name__ == '__main__':
    main()

Solution

  • I can only find examples where the user is only defined by their ID numbre

    This is the only way that a Telegram bot can send messages to a user. However, a Bot can ofc send messages to users at any time (if the user have started the bot) and not only to react to incoming messages. All you need for that is an instance of the telegram.Bot class. Please have a look at PTB Introduction for more explanations.


    Disclaimer: I'm currently the maintainer of python-telegram-bot.