是否可以通过 Telegram python 机器人中的 Inlinekeybuttons 使用带有参数的代码?
Is it possible to use code with argument through Inlinekeybuttons in Telegram python bot?
我在命令处理程序中编写了代码,参数为 if 1 then task1,if 2 then task2。我可以让它工作,只需输入“/command 1”或“/command 2”来激活它。
是否可以在 inlinekeyboardbutton 中立即添加“1”或“2”参数?
我的内联键盘代码现在看起来像那样。
我知道我的按钮现在会触发完全相同的代码,但不知道如何为第一个按钮设置参数“1”,为第二个按钮设置参数“2”。
options.append(InlineKeyboardButton("command with argument 1", callback_data="1"))
options.append(InlineKeyboardButton("command with argument 2", callback_data="2"))
#######
def callback_query_handler(update, context):
input = update.callback_query.data
if input == '1':
self._command(update, context)
if input == '2':
self._command(update,context)
请注意 input
是内置函数,您不应覆盖它。
现在我假设 self._command
是您用于处理 command
的 CommandHandler
的回调。
首先(至少从您的代码片段看来) self
在 callback_query_handler
函数中未定义。
此外,update
是 update.callback_query
的更新,而 self._command
可能假设 update.message is not None
- 所以这必然会产生问题。
我建议
- 从
self._command
中提取依赖于参数的逻辑到不同的函数中
- 从
self._command
和 callback_query_handler
调用该函数
这个函数应该以实参作为参数。请注意,在您的 corrent 代码段中, if
基本上没有意义,因为在这两种情况下您都对 self._command
进行了相同的调用
我在命令处理程序中编写了代码,参数为 if 1 then task1,if 2 then task2。我可以让它工作,只需输入“/command 1”或“/command 2”来激活它。
是否可以在 inlinekeyboardbutton 中立即添加“1”或“2”参数?
我的内联键盘代码现在看起来像那样。
我知道我的按钮现在会触发完全相同的代码,但不知道如何为第一个按钮设置参数“1”,为第二个按钮设置参数“2”。
options.append(InlineKeyboardButton("command with argument 1", callback_data="1"))
options.append(InlineKeyboardButton("command with argument 2", callback_data="2"))
#######
def callback_query_handler(update, context):
input = update.callback_query.data
if input == '1':
self._command(update, context)
if input == '2':
self._command(update,context)
请注意 input
是内置函数,您不应覆盖它。
现在我假设 self._command
是您用于处理 command
的 CommandHandler
的回调。
首先(至少从您的代码片段看来) self
在 callback_query_handler
函数中未定义。
此外,update
是 update.callback_query
的更新,而 self._command
可能假设 update.message is not None
- 所以这必然会产生问题。
我建议
- 从
self._command
中提取依赖于参数的逻辑到不同的函数中 - 从
self._command
和callback_query_handler
调用该函数
这个函数应该以实参作为参数。请注意,在您的 corrent 代码段中, if
基本上没有意义,因为在这两种情况下您都对 self._command