What I’m trying to do:
I need to run a Telegram (TG) bot, for notifying my users of different events happening. I am using the python-telegram-bot (PTB) library, which is already included in the
As PTB works by registering different command-handlers, and the starting a polling task, I was hoping to have the bot run as a Background Task, which I can control from an admin interface I have already built.
What I am trying to figure out, is this a reasonable use of the Background Tasks of Anvil?
I understand that a dedicated server connected through Uplink, would work, but I’m trying to do this all inside Anvil if possible.
I am running into issues, when trying to query the database, from inside the background task, that is handling PTB:
What I’ve tried and what’s not working:
I have defined my background task, and can start and stop it as I want.
This task is running the PTB, using the following principle:
tg_service_task:
from telegram.ext import Updater
from telegram.ext.commandhandler import CommandHandler
from .tg_bot_api import start_auth
updater = Updater(anvil.secrets.get_secret("VERY_SECRET_TOKEN"))
dispatcher = updater.dispatcher
@anvil.server.background_task('telegram_service')
def service_handler():
anvil.server.task_state = 'Starting service'
# Register commands
start_auth_handler = CommandHandler("start", start_auth)
dispatcher.add_handler(start_auth_handler)
# Start telegram-bot
updater.start_polling()
print(f"Telegram bot started")
The callback function start_auth looks something like this:
tg_bot_api:
token = context.args[0]
print(f"User { update.effective_chat.id } is requesting authorization with token { token }")
operator = app_tables.operators.get(tg_auth_token=token)
if operator is not None:
# Save TG ID in DB
operator.update(telegram_id=int(update.effextive_chat.id))
# Let user know everything went well
context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"Welcome { operator['title'] }\nYou have been authorized successfully!",
)
else:
# Authorization request denied
context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"Failed to authorize.",
)
The issue:
When I initiate the command from Telegram, the start_auth function hangs on the operator = app_tables.operators.get(tg_auth_token=token)
, without throwing an error or anything else.
In the logs, I can see that the bot registers the event, with the correct auth_token that matched the one in the data table, however the get() command does not return.
Am I missing something obvious?
I have tried implemented a simple greeting command, which responds to commands from a Telegram client, so the bot works.
I am, however, suspecting that the PTB maybe blocks the process that is trying to call the data table?
Any insights, suggestions or follow-up questions would be greatly appreciated.
I am working on creating a demo-app, to show the behaviour, but to use it, one would need to provide their own Telegram API key