python - Python电报机器人(Telebot)
问题描述
我正在使用库https://github.com/eternnoir/pyTelegramBotAPI构建 Telegram 机器人
我试图在按下菜单按钮时向用户发送消息。
我怎么能做到?
import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
TELEGRAM_TOKEN = '<TOKEN>'
bot = telebot.TeleBot(TELEGRAM_TOKEN)
def gen_markup():
markup = InlineKeyboardMarkup()
markup.row_width = 2
markup.add(InlineKeyboardButton("Yes", callback_data="cb_yes"),
InlineKeyboardButton("No", callback_data="cb_no"))
return markup
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
if call.data == "cb_yes":
bot.answer_callback_query(call.id, "Answer is Yes")
elif call.data == "cb_no":
bot.answer_callback_query(call.id, "Answer is No")
@bot.message_handler(func=lambda message: True)
def message_handler(message):
bot.send_message(message.chat.id, "Yes/no?", reply_markup=gen_markup())
bot.polling(none_stop=True)
解决方案
您可以使用call
对象的数据作为发送者的用户 id( call.from_user.id
) 来发送消息:
if call.data == "cb_yes":
bot.answer_callback_query(call.id, "Answer is Yes")
bot.send_message(call.from_user.id,"Your answer was Yes!")
elif call.data == "cb_no":
bot.answer_callback_query(call.id, "Answer is No")
bot.send_message(call.from_user.id,"Your answer was No!")
推荐阅读
- sql - 为什么 ms-access sql Pass Through 在 VBA 中不起作用
- cron - 当我添加日志选项时,Cron 作业不起作用
- android - 尝试在 Windows 上为 Android 构建 Chromium 时,gclient runhooks 抛出错误
- java - 不兼容的类型:javafx.scene.media.Media 无法转换为 javax.print.attribute.standard.Media
- python - 降维(异构数据)
- node.js - Meteor Mongodb 深度搜索
- vue.js - `nuxt.js` 替代 vue3?
- javascript - 如何使用 TypeScript 在 useRef 挂钩中键入函数
- c# - 在 .net 核心的自定义模型绑定器中验证嵌套的 Json 对象
- angular - 在 Liferay 中调整 Angular 应用程序时出错