I’m trying to integrate a Telegram bot into my Python script. The bot is not the primary part of the script, but I need it to send automatic updates to a user based on certain conditions. Most examples I found online involve bots that react to user messages, but I need my bot to send messages automatically without any user interaction.
Here is a simplified version of my script, where I want to periodically update the user (let’s say every 20 sec) through the Telegram bot. However, I’m clueless about whether a function like this already exists and how to integrate it into my script. Does anyone have suggestions?
import logging
from time import sleep
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
TOKEN = "MY_TELEGRAM_TOKEN"
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
application = Application.builder().token(TOKEN).build()
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text(f"You are now monitoring updates.")
run_counter = 0
sleeptime = 20
def main():
global run_counter
while True:
message = "This is an automatic update."
print(message)
# Add here the function to send updates
run_counter += 1
sleep(sleeptime)
# Add command handler for /start command
application.add_handler(CommandHandler("start", start))
def start_bot():
application.run_polling()
def start_main():
main()
if __name__ == "__main__":
# Start the main monitoring script in a separate thread or process
import threading
# Start the main function in a separate thread
main_thread = threading.Thread(target=start_main)
main_thread.start()
# Start the Telegram bot
start_bot()
magic4815162352 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.