from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes from telegram.ext.filters import MessageFilter class ContextDataFilter(MessageFilter): def __init__(self, key: str, expected_value): super().__init__() self.key = key self.expected_value = expected_value def filter(self, message) -> bool: bot_data = message.get_bot().data return bot_data.get(self.key) == self.expected_value async def set_flag(update: Update, context: ContextTypes.DEFAULT_TYPE): context.bot.data["allow_messages"] = True await update.message.reply_text("Filter flag set. You can now send messages.") async def restricted_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text( Your message passed the filter!") if __name__ == "__main__": TOKEN = "YOUR_BOT_TOKEN_HERE" app = ApplicationBuilder().token(TOKEN).build() app.bot.data = {"allow_messages": False} my_filter = ContextDataFilter("allow_messages", True) app.add_handler(CommandHandler("setflag", set_flag)) app.add_handler(MessageHandler(my_filter, restricted_handler)) app.run_polling() import datetime from telegram.ext import UpdateFilter class ConditionalUserFilter(UpdateFilter): def __init__(self, condition_func): super().__init__() self.condition_func = condition_func def filter(self, update): try: return bool(self.condition_func(update)) except Exception: return False