2017-06-17 25 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