skip to Main Content

I am having difficulty fully defining the class in my Python code. I have played around with it, but have had no luck.

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, 
    ConversationHandler, MessageHandler, BaseFilter, run_async, Filters
     

class TelegramBot:
    class PrivateUserFilter(BaseFilter):
        def __init__(self, user_id):
            self.user_id = int(user_id)

        def filter(self, message):
            return message.from_user.id == self.user_id

    def __init__(self, token: str, allowed_user_id): 
        self.updater = Updater(token=token)
        self.dispatcher = self.updater.dispatcher
        self.private_filter = PrivateUserFilter(allowed_user_id)
        self._prepare()

It’s throwing the following exception:

~OneDrive - yyy..coretelegrambot.py in __init__(self, token, allowed_user_id)
---> 44         self.private_filter = PrivateUserFilter(allowed_user_id)
     45         self._prepare()
     46 

NameError: name 'PrivateUserFilter' is not defined

2

Answers


  1. You’re putting a class inside an other class. This means the "inside" class is only available as an attribute on the first.

    And while some some systems make use of such nested classes e.g. Django somewhat famously uses nested classes for some types of meta-information of models and forms, here it seems completely useless.

    Just move PrivateUserFilter to the toplevel, next to the other class.

    Login or Signup to reply.
  2. Change self.private_filter = PrivateUserFilter(allowed_user_id) to self.private_filter = self.PrivateUserFilter(allowed_user_id).

    Edit: can also use TelegramBot instead of self.

    Think of it like namespaces, you’ll only be able to call the inner class if you reference the outer one.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search