尝试将变量作为命令

时间:2019-04-11 05:12:58

标签: python variables telegram-bot python-telegram-bot telepot

我的变量urls从消息中查找URL。如果机器人从收到的邮件中找到URL,我希望它发送yes。这是我尝试过的,

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')

但是它不起作用。将变量作为命令放置的正确方法以及如何修复它?

1 个答案:

答案 0 :(得分:1)

问题似乎在于您将command(一个字符串)与urls(一个字符串列表)进行了比较。如果您希望在命令中找到至少一个 URL的情况下发送消息,则可以将其更改为

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')

注意-如果没有匹配项,urls将为空列表。空列表的布尔值在Python中为false,因此if urls仅在urls不是空列表(即至少有一个匹配项)时通过。这相当于说if len(urls) != 0:

如果您只想在整个command是URL时才发送消息,则可以

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')