Abstract.
I have two python files. The first one reads some inputs (texts) and the second one stores some functions. The problem here is the method I’m using to look for the function that I need. Now I’m using a If / Elif method to compare the input and the functions but this method needs to compare all the functions stored in the second file with the input and I was thinking if “this is the best way to do it?”.
Full explanation.
I’m trying to build a Telegram chat bot, just to practice some Python. Before anything I drew a mental map to know what I want this scripts will do. Because of that mental map, I came with the idea of spliting the code in different files in order organize everything better and to do the debugging process a little bit easier. So, I did that. I store the credentials (for the api’s) in one file, the mainframe in other file and the functions in other file. I import in the files into the mainframe with From Credentials import *
and From Comands import *
. When any text come to the bot it first checks how it starts, if it starts with “/” then it stores whatever comes after the slash in a variable and send it as a parameter to the functions file. When is there it starts to look for the exact command required and execute it. And it works but I guessing if there is a better way to do it. I hope I explained well the problem and you can help me. Here’s the extract of code that I’m talking.
mainframe.py
from Comands import *
from credentials import *
...
if text.startswith("/"):
comando = text[1:]
print(comando)
Comands.search(comando)
elif text in items:
db.delete_item(text, chat)
items = db.get_items(chat)
keyboard = build_keyboard(items)
send_message("Select an item to delete", chat, keyboard)
else:
db.add_item(text, chat)
items = db.get_items(chat)
message = "n".join(items)
send_message(message, chat)
...
Comands.py
from message_dictionary import *
from mainframe import *
def search(comando):
if comando == "start":
def start():
keyboard = build_keyboard(acuerdo)
send_message(mensaje["start"], chat, keyboard)
elif comando == "done":
def done():
keyboard = build_kerboard(items)
send_message("Select an item to delete", chat, keyboard)
2
Answers
Here it is.
mainframe.py (it is actually called Prubeas.py)
Whats it commented at the end of this code is for an API i'll try to use later, once I done with the telegram api.
Comands.py
I apologies for mixing the languages. I really appreciate your help, thanks.
First, I’ll start with 2 recommendations:
mainframe.py
command.py
some notes about your comand.py:
modified comand.py to return callable function (to address questions in comments):
modified fragment mainframe.py to use returned values: