尝试将变量作为命令

2024-03-29 07:52:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我的变量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')

但它不起作用。将变量作为命令放置是否正确?如何修复它?你知道吗


Tags: textreid消息urldefchat机器人
1条回答
网友
1楼 · 发布于 2024-03-29 07:52:05

问题似乎是您将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')

相关问题 更多 >