A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://stackoverflow.com/questions/79579693/python-telegram-bot-endless-background-task below:

Python telegram-bot endless background task

With python-telegram-bot v0.22 some things have been changed and I can't get the code to work. I've tried a a lot of things but keep running into a problem. Here is my simplified code. I want to write a bot that supports command handlers and runs an endless task in the background that pauses at different times and performs a basic check. if something has changed, a message should be sent to a specific chat ID. I keep finding references to this code, but I can't get it to run. Here is my code currently not executable:

https://github.com/python-telegram-bot/python-telegram-bot/wiki/Frequently-requested-design-patterns#running-ptb-alongside-other-asyncio-frameworks

import asyncio
import time

from telegram import Update, Bot
from telegram.ext import (
    Application,
    CommandHandler,
    ContextTypes,
)

chat_id = 1234
token = "token"
bot = Bot(token=token)

test_value = "test"
content = None

def check_file():
    global content
    while True:
        with open("test.txt", "r") as file:
            file_content = file.read()
            if file_content != content:
                content = file_content
                asyncio.run(bot.send_message(chat_id=chat_id, text="file changed"))
        time.sleep(3)


async def test_get(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(test_value)


async def test_set(update: Update, context: ContextTypes.DEFAULT_TYPE):
    global test_value
    test_value = context.args[0]
    await update.message.reply_text(test_value)


async def init_updater():
    # Create the Application and pass it your bot's token.
    application = Application.builder().token(token).build()

    # add handler
    application.add_handler(CommandHandler('test_get', test_get))
    application.add_handler(CommandHandler('test_set', test_set))

    # start application
    await application.initialize()
    await application.start()
    await application.updater.start_polling()

    check_file()

    await application.updater.stop()
    await application.stop()
    await application.shutdown()


if __name__ == "__main__":
    asyncio.run(init_updater())

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4