I was creating a Telegram Bot that takes care of scraping on Amazon after receiving a URL via chat. Although it performs this task very well, I cannot handle the case in which the bot received a text that does not fall within the “allowed commands”; in fact, what I wanted it to accept are /start, /stop and a properly formatted URL. I had tried to insert an additional Handler that filtered the messages, but without success. Ultimately I would like any text outside of start, stop, and a URL to be responded to with an error message, such as “SEND ME A URL PLEASE”.
A further problem is that having declared the global variable bot_is_running, the bot appears to be active even before clicking on /start. How can I solve it?
Finally, would it be possible to know how to actually shut down the bot (apart from CTRL+C) and then whether it is possible to restart it from the chat itself, taking into account that it is running on the console of a virtual machine running Ubuntu?
I leave the code I have written so far to understand the structure used.
load_dotenv()
bot_is_running = True
authorized_users = []
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
global bot_is_running
user_id = update.effective_user.id
if user_id not in authorized_users:
await update.message.reply_text("ACCESS DENIED")
return
bot_is_running = True
await context.bot.send_message(chat_id=update.effective_chat.id, text="WELCOME!")
async def stop(update: Update, context: ContextTypes.DEFAULT_TYPE):
global bot_is_running
user_id = update.effective_user.id
if user_id not in authorized_users:
await update.message.reply_text("ACCESS DENIED")
return
bot_is_running = False
await update.message.reply_text("THE BOT HAS BEEN TURNED OFF..")
await context.application.stop()
async def stopped_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
global bot_is_running
if not bot_is_running:
await update.message.reply_text("THE BOT IS OFF.")
def main():
app = ApplicationBuilder()
.read_timeout(100)
.write_timeout(100)
.token(os.environ["TG_BOT_TOKEN"])
.build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("stop", stop))
app.add_handler(MessageHandler(filters.TEXT & (filters.Entity("url") | filters.Entity("text_link")), url_received))
app.add_handler(MessageHandler(filters.TEXT, stopped_message))
app.run_polling()
if __name__ == '__main__':
main()