python - 如何在电报中制作动态命令
问题描述
如何在不为每个 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_)
解决方案
您的 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
其他功能使其更加复杂。
推荐阅读
- java - 以漂亮的文本格式化结构化日志(单行序列化 JSON)的“gcloud app logs tail”输出
- node.js - nodejs计算具有相同值的dynamodb记录-聚合分组
- php - PDO 驱动程序在 Debian 10 中没有价值
- ios - 如何将关联域附加到 CoreNFC 中 NFCNDEFPayload 的 NFC 标签中
- java - Android 应用程序在模拟器中使用 java 代码崩溃
- html - 如何使用 JQUERY 检查所有“th”值?
- java - 如何在放心的拦截器中设置内容类型?
- python - python pandas,删除用于任何 DataFrame 特定列的重复功能,但有一个例外:
- google-cloud-platform - 谷歌云平台如何限制用户使用单个VPC?
- android - 在 Android 10 中,Picasso 能够在没有任何权限的情况下真正显示带有图像的 Uri 的图像,但 openInputStream 需要权限