试图将变量作为命令

Trying to put a variable as command

我的变量 urls 从消息中找到 URLs。如果我的机器人从收到的消息中找到 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')

但它不起作用。将变量作为命令放置是正确的方法吗?如何解决?

问题似乎是您将 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 中为假,因此 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')