skip to Main Content

I’ve created a class with an add method. It saves the names of different tokens in a .txt file, only if they aren’t there in the first place. If the .txt file doesn’t exist, it informs the user and creates the file. It looks something like this:

class watchlist:
    def __init__(self, tokens=[]): 
        self.tokens = tokens
    
    def add(self, new_tokens):
        # Check if user has a watchlist, eliminate repeated tokens
        try:
            with open ("watchlist.txt", "r") as registry:
                for line in registry: 
                    existent_token = line.strip('n')
                    if existent_token in new_tokens:
                        new_tokens.remove(existent_token)
                        print(f"{existent_token} was already on your watchlist")
        except FileNotFoundError: print("This user has no watchlist. A new watchlist will be created")
        
        # Add new tokens to watchlist
        with open ("watchlist.txt", "a") as registry:
            for new_token in new_tokens:
                registry.write(f'{new_token.upper()}n')
                print(f'{new_token} added to portfolio')

Thing is, instead of printing the comments to the terminal, I want to send them as messages, without sending them from within the class. I don’t want to replace the line:

print("This user has no watchlist. A new watchlist will be created")

with

context.bot.send_message(chat_id=user.effective_chat.id, text="This user has no...")

because I want to keep the classes in a separate file. What’s the proper way of redirecting that output so that the main function can send the messages while the method is running?

2

Answers


  1. You could initialize your watchlist class with an object having a write function. Setting the object to sys.stdout will print to the terminal, setting it to a custom writer will direct the output somewhere else, for example:

    import sys
    
    class customOutput:
        def write(self, msg : str):
            # TODO: send via telegram
            print("Custom output - Msg: " + msg)
    
        
    class watchlist:
        def __init__(self, writer) -> None:
            self._writer = writer
    
        def add(self):
            self._writer.write("Some message")
    
    my_watchlist = watchlist(customOutput())
    
    my_watchlist.add()
    
    my_watchlist = watchlist(sys.stdout)
    
    my_watchlist.add()
    

    prints:

    Custom output - Msg: Some message
    Some message
    
    Login or Signup to reply.
  2. I guess the main point here is that you don’t necessarily need the context argument of a handler callback to send messages – all you need is an instance of telegram.Bot. In the main this is usually available as updater.bot or dispatcher.bot and you can use it there to initialize your setup. In the solution suggested by Roman Purgstaller, you could create an instance of customOutput in the main and initialize it by passing updater.bot to it.

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