首页 > 解决方案 > 如何在电报中制作动态命令

问题描述

如何在不为每个 id 创建方法的情况下为数据库中的项目发送 id

我的目标是输入所需的 ID /13,然后机器人返回我需要的关于该项目的信息

选择的仓库是pyTelegramBotAPI

对于数据库访问和操作,我正在使用 flask-sqlalchemy

import telebot

from config import telegram_token       

bot = telebot.TeleBot(telegram_token)

@bot.message_handler(commands=['summary'])
def send_welcome(message):
    summary = """ return general info about bot performance """
    bot.reply_to(message, summary )


@bot.message_handler(commands=['<id>'])
def send_welcome(message):
    id_ = """ return info about this id"""
    bot.reply_to(message, id_)

标签: pythontelegram

解决方案


您的 API 链接显示了regex识别命令的方法

@bot.message_handler(regexp="SOME_REGEXP") 

您可以使用 withregexp="/\d+"来获取任何/number.

稍后您应该使用message.text[1:]将其number作为字符串(不带/)。

@bot.message_handler(regexp="/\d+")
def get_id(message):  
    id_ = message.text[1:]        # as string without `/`
    #id_ = int(message.text[1:])  # as integer
    bot.reply_to(message, id_)

编辑:

只为/number它运行功能还需要^ $

regexp="^/\d+$"

没有^ $它也将运行功能hello /13 world


最少的工作代码

import os
import telebot

TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')

bot = telebot.TeleBot(TELEGRAM_TOKEN)

@bot.message_handler(regexp="^\d+$")
def get_id(message):  
    id_ = message.text[1:]        # as string without `/`
    #id_ = int(message.text[1:])  # as integer
    bot.reply_to(message, id_)

bot.polling()

编辑:

你也可以使用

@bot.message_handler(func=lambda message: ...)

@bot.message_handler(func=lambda msg: msg.text[0] == '/' and msg.text[1:].isdecimal())
def get_id(message):  
    id_ = message.text[1:]        # as string without `/`
    #id_ = int(message.text[1:])  # as integer
    bot.reply_to(message, id_)

或更具可读性

def is_number_command(message):
    text = message.text
    return text[0] == '/' and text[1:].isdecimal()
    
@bot.message_handler(func=is_number_command)
def get_id(message):  
    id_ = message.text[1:]        # as string without `/`
    #id_ = int(message.text[1:])  # as integer
    bot.reply_to(message, id_)

您可以使用text[1:].isdecimal()text[1:].isdigit()text[1:].isnumeric()或或str.isdecimal(text[1:])str.isdigit(text[1:])str.isnumeric(text[1:])

您可以使用func其他功能使其更加复杂。


推荐阅读