1

我正在用 pytelegrambotapi 构建一个简单的游戏。根据规则,向用户发送一个定义和四个以文字为文本的按钮,其中一个是正确的。然后用户应该按下右键。然后另一个例程将用户的答案与正确答案进行比较。如何检索用户按下的按钮的值?

import telebot
from telebot import types

TOKEN = 'XXXXXXXXXXXXXXXXX'
bot = telebot.TeleBot(TOKEN)

kb = types.InlineKeyboardMarkup(row_width=2)

words = {
'Meager' : 'Lacking in quantity',
'Asylum' : 'Shelter',
'Irk' : 'To annoy',
'Kudos' : 'Great glory'
}


def compare(message, word, definition):
    if definition == words[word]:
        bot.send_message(message.from_user.id, 'Correct!')
    else:
        bot.send_message(message.from_user.id, 'Wrong!')


for item in words.items():
    kb.add(types.InlineKeyboardButton(item[0], callback_data = item[0]))



@bot.message_handler(commands=['start', 's'])
def post_random_article(message):
    word = 'Meager'
    bot.send_message(message.from_user.id, word, reply_markup = kb)

bot.polling()
4

1 回答 1

2

没关系,我找到了答案。

@bot.callback_query_handler(func=lambda call: True)
def handle_query(call):
    if call.data.split('#')[0] == call.data.split('#')[1]:
        bot.send_message(call.message.chat.id,  '✅ Correct!')
    else:
        bot.send_message(call.message.chat.id,  '❌ Wrong!\n♻️ The answer is: %s' % call.data.split('#')[1])



@bot.message_handler(commands=['game', 'g'])
def game(message):
    list_of_words = load_my_dictionary(message.from_user.id)
    random.shuffle(list_of_words)
    while not len(list_of_words) < 4:
        current = list_of_words.pop()
        word = current[0]
        definition = current[1]
        all_answers = generate_answers(word, list_of_words)
        keyboard = generate_keyboard(all_answers, word)
        bot.send_message(message.from_user.id, definition, reply_markup = keyboard)
        time.sleep(7)
    bot.send_message(message.from_user.id, ' List is empty!')
于 2019-11-22T08:09:16.130 回答