I’m building a Telegram bot that looks up word definitions using an online dictionary API. Everything works fine except I can’t figure out how to capture the word that users want to search for when they use my command.
Here’s my current code:
from dictionary_api import WordLookup
lookup_service = WordLookup()
if message.startswith('/'):
if message == '/lookup':
result = lookup_service.find_definition('') # This is where I'm stuck - how do I get the actual word from user?
activate_chat(user_id, True)
I need help understanding how to extract the word parameter that comes after the command. For example, when someone types /lookup hello, I want to capture “hello” and pass it to my dictionary search function.
just split the message strin like word = message.split()[1], but make sure to check if there’s a second part first with if len(message.split()) > 1: then grab the word. it works in my bot.
Parse the command and grab the parameters from the message text. Once you’ve confirmed it starts with ‘/lookup’, extract everything after the command using message[8:].strip() - the 8 is just the length of '/lookup '. This keeps spaces intact for multi-word searches and won’t break if someone forgets the parameter. I’ve found this works way better than splitting since it handles edge cases like extra spaces or phrase searches. Just make sure the parameter isn’t empty before hitting your API.
Use regex for this - it’s way cleaner. Import re and do match = re.match(r'/lookup\s+(.+)', message) to grab the word parameter. If it matches, match.group(1) gives you the word. If not, handle the missing parameter case. This automatically deals with multiple spaces between the command and parameter, plus you can easily extend it for input validation. I’ve used this pattern for tons of bot commands and it beats manual string manipulation every time, especially when you’re adding more complex stuff later.