0

我的变量urls从消息中查找 URL。如果我的机器人yes从收到的消息中找到 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 command == urls:
        telegram_bot.sendMessage(chat_id, "yes", parse_mode= 'Markdown')

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

4

1 回答 1

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')
于 2019-04-11T05:27:15.400 回答