Search code examples
pythonvariablestelegram-botpython-telegram-bottelepot

Trying to put a variable as command


My variable urls finds URLs from messages. I want my bot to send yes if it finds a URL from the received messages. Here is what I tried,

def action(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', command)

    if command == urls:
        telegram_bot.sendMessage(chat_id, "yes", parse_mode= 'Markdown')

But it is not working. Is it a correct way to put variables as a command and how to fix it?


Solution

  • It seems the issue is that you compare command (a string) against urls (a list of strings). If you want the message to be sent as long as at least one URL was found in the command, you can change this to

    def action(msg):
        chat_id = msg['chat']['id']
        command = msg['text']
    
        urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', command)
    
        if urls:
            telegram_bot.sendMessage(chat_id, "yes", parse_mode= 'Markdown')
    

    Note - if there are no matches, urls will be an empty list. The boolean value of an empty list is false in Python, so if urls only passes if urls is not an empty list (i.e. there was at least one match). This is equivalent to saying if len(urls) != 0:.

    If you instead want a message sent only if the entirety of command is a URL, you can do

    def action(msg):
        chat_id = msg['chat']['id']
        command = msg['text']
    
        pattern = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    
        if re.fullmatch(pattern, command):
            telegram_bot.sendMessage(chat_id, "yes", parse_mode= 'Markdown')