2017-06-17 113 views
0

我试图使用python-电报机器人模块建立在电报菜单,它的样本中有:蟒蛇-电报机器人菜单创建util的库导入问题

button_list = [ 
    InlineKeyboardButton("col 1", ...), 
    InlineKeyboardButton("col 2", ...), 
    InlineKeyboardButton("row 2", ...) 
] 
reply_markup = InlineKeyboardMarkup(util.build_menu(button_list, n_cols=2)) 
bot.send_message(..., "A two-column menu", reply_markup=reply_markup) 

我得到这个错误:

NameError: global name 'util' is not defined

我不能罚款在样品中的进口,它不认可那里。

我该输入什么?

回答

1

该示例来自我们的Code Snippets页面。因此,要使代码正常工作,您需要实际包含片段,因为它实际上并不是库本身的一部分。

def build_menu(buttons, 
       n_cols, 
       header_buttons, 
       footer_buttons): 
    menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] 
    if header_buttons: 
     menu.insert(0, header_buttons) 
    if footer_buttons: 
     menu.append(footer_buttons) 
    return menu 

,然后更改util.build_menu(button_list, n_cols=2)build_menu(button_list, n_cols=2)

请注意,您甚至不必使用build_menu来使用按钮。事实上,将您的按钮定义为二维列表通常比较简单,因此您的代码会变成:

button_list = [ 
    [ 
     InlineKeyboardButton("col 1", ...), 
     InlineKeyboardButton("col 2", ...) 
    ], 
    [ 
     InlineKeyboardButton("row 2", ...) 
    ] 
] 
reply_markup = InlineKeyboardMarkup(button_list) 
bot.send_message(..., "A two-column menu", reply_markup=reply_markup) 
+0

Tnx,有没有这样的工作示例?因为现在我得到不好的请求 – MasOud

+0

你能否加入我们[python-telegram-bot support group](https://t.me/pythontelegrambotgroup)?我们至少需要看到你的代码的副本,找出为什么它不工作:) – bomjacob

+0

谢谢,但我不明白如何将回调添加到每个按钮。我的意思是你在下面的例子中写下'...'的部分,你在回答中写下的单词中。'事实上,把你的按钮定义为二维列表通常比较简单,所以你的代码会变成:' – f126ck