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
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:prints:
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 oftelegram.Bot
. In themain
this is usually available asupdater.bot
ordispatcher.bot
and you can use it there to initialize your setup. In the solution suggested by Roman Purgstaller, you could create an instance ofcustomOutput
in themain
and initialize it by passingupdater.bot
to it.