skip to Main Content

i want to send a message to user, without waiting for user triggered my bot. using send_message(), i’ve been read the documentation but i’m not really understand. Here’s my code

from dotenv import load_dotenv
from telegram.ext import *
from telegram import InputFile, Bot
import os
import re

command = ['start']

load_dotenv()

tokenize = os.getenv("TELEGRAM_BOT_TOKEN")

async def start_commmand(update, context):
    umsg = update.message
    await umsg.reply_text("Welcome, i'll help u with ur schedule")


if __name__ == "__main__":
    application = Application.builder().token(tokenize).build()

    application.add_handler(CommandHandler(command[0], start_commmand))

    # Run bot
    application.run_polling(1.0)

i tried to send a message to bot user using send_mesage(), i hope it’s send a message without waiting any message from user. because i’m not really understand after read the documentation, i don’t know how to do it

2

Answers


  1. Sending messages usually goes through a handler, you should use those if you can.

    That said, of course you can send messages, the application is sort of your bot.

    As an example, imagine you want to send yourself a message if you start your bot, this can be done by adding a post_init callback, that will run once when you call run_polling:

    async def send_start_message(self):
        await self.bot.sendMessage(CHAT_ID, 'Hello World')
    
    if __name__ == "__main__":
    
        application = Application.builder().token(TOKEN).build()
        application.post_init = send_start_message
    
        application.run_polling(1.0)
    

    So in this example ‘Hello World’ will be send to CHAT_ID once, on start-up.

    Login or Signup to reply.
  2. In addition to Ostone0s answer I’d like to point out that you don’t need the Application class at all to send a message. That class is intended to be used when you actually want to handle updates. For just making plain calls to the Bot API, you can directly use the Bot class. This is also showcased in the PTB wiki.


    Dicslaimer: I’m currently the maintainer of python-telegram-bot.

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