You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Telegram Bot(pytelegrambotapi)中获取命令后的参数?

解决pyTelegramBotAPI获取命令后参数的问题

你遇到的问题是因为pyTelegramBotAPI的命令处理函数只会接收message这一个参数,不能直接在函数定义里额外加word参数,框架不会自动帮你拆分参数传递进去。

修正方法很简单,直接从message.text里手动拆分命令和参数:

import telebot

wordlist = {}

bot = telebot.TeleBot('6515388014:AAEQLxcO6ndqHZJyulKPCVjkvnp2Zndqumg')

@bot.message_handler(commands=['start'])
def start(message):
    bot.send_message(message.chat.id, 'Hi, this bot currently does nothing')

@bot.message_handler(commands=['add'])
def add_word(message):
    # 按空格拆分消息文本,得到命令和参数列表
    message_parts = message.text.split()
    # 检查是否有参数传入
    if len(message_parts) < 2:
        bot.send_message(message.chat.id, '请在/add后输入要添加的单词')
        return
    # 取第二个元素作为目标单词(第一个是命令本身"/add")
    word = message_parts[1]
    bot.send_message(message.chat.id, f'Add the word {word} to the word list?')
    # 这里可以添加把单词存入wordlist的逻辑
    wordlist[word] = True

@bot.message_handler()
def meme(message):
    if message.text.lower() == 'мирон':
        bot.send_message(message.chat.id, 'шашки')

bot.infinity_polling()

关键说明:

  • message.text.split()会把用户输入的内容按空格分割成列表,比如输入/add apple会得到["/add", "apple"]
  • 加入参数长度检查,避免用户只输入/add时触发索引越界错误
  • 如果需要支持多参数,直接取message_parts[2:]然后拼接即可

内容的提问来源于stack exchange,提问作者DamAnD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 02:12:48