1

Is there a way to send a message (call a function), without a command from the bot's user? For example when a certain condition is met?

Currently I have only been able to call a function with a command.

I have been trying the following:

from telegram.ext import Updater, CommandHandler, CallbackContext
from telegram import Update
from datetime import datetime
import telebot as tb
import logging

bot = tb.TeleBot(API_KEY)

logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)


def messager(update: Update, context: CallbackContext) -> None:
    """this function messages at a specific time"""
    update.message.reply_text("message back")

if __name__ == "__main__":
    updater = Updater(API_KEY)

    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler("message", messager))

    condition = False #I have been changing this when testing
    if (condition == True):
        messager() # how to call messager here? how to pass update and context arguments?

    updater.start_polling()
    updater.idle()

Any possible way to achieve this would be great.

1
  • How about adding a condition to messager() function? Commented Oct 27, 2021 at 4:23

1 Answer 1

1

You cannot call a function using update and context since there is no update from the telegram servers to act on. In other words there is no event to perform a callback on.

Depending on what you want to do you could use a MessageHandler instead of a CommandHandler to reply to any message with Filters to filter out which ones to reply to

or if you want to send a message every time you start your bot and you know who to send a message to (i.e you have their chat_id) you can do

if condition:
    updater.bot.send_message(chat_id=CHAT_ID, text="message back")

or if you just want to send a message every time some user starts a chat with your bot you could use the start command which is sent by default to start a chat with a bot

Sign up to request clarification or add additional context in comments.

2 Comments

So basically, to send a message unprompted (without a user sending a message), I need to have their chat_id saved from a previous message?
Yes because you need some way to know who to send messages to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.