我正在创建一个电报机器人,但遇到了一个问题。
启动机器人后,它会向我发送两个按钮:“是”和“否”。我按其中一个,我希望我的回复保留在我的名字下的聊天中。
所以作为初学者,我没有我需要的那么多信息。
在我的代码中,出现了错误,特别是数据类型和函数参数的问题。当我在回调处理函数中使用
bot.send_message
时,会出现错误,因为该函数不直接接受 from_user
参数。我能实现的最大目标是让机器人以它的名字而不是我的名字发送响应。因此,我需要使用另一种方法来传递用户数据,以便机器人可以像我一样发送消息。但不知道是哪一个。
提前感谢您的任何回复。 |
import telebot
from telebot import types
#from aiogram.types import InlineKeyboardMarkup,InlineKeyboardButton
bot = telebot.TeleBot('mytoken')
@bot.message_handler(commands=['start'])
def start(message):
markup = types.InlineKeyboardMarkup()
btn1 = types.InlineKeyboardButton('да', callback_data='yes')
btn2 = types.InlineKeyboardButton('нет', callback_data='no')
markup.row(btn1, btn2)
bot.send_message(message.chat.id, f'привет, {message.from_user.first_name}! придет ли сегодня Кевин?', reply_markup=markup)
@bot.callback_query_handler(func=lambda callback: True)
def callback_message(callback):
if callback.data == 'yes':
bot.send_message(callback.message.chat.id, 'ок, спасибо, что предупредил')
elif callback.data == 'no':
bot.send_message(callback.message.chat.id, 'ок, спасибо, что предупредил')
bot.polling(non_stop=True)
在 Telegram 中,您无法像直接通过机器人 API 发送来自用户的消息一样发送消息。通过机器人发送的消息始终来自机器人本身。但是,您可以通过编辑原始消息以包含响应来创建机器人正在作为用户进行交互的错觉。
以下是如何实现此目标的示例:
import telebot
from telebot import types
bot = telebot.TeleBot('your_token')
# Dictionary to store the user's messages
user_responses = {}
@bot.message_handler(commands=['start'])
def start(message):
markup = types.InlineKeyboardMarkup()
btn1 = types.InlineKeyboardButton('Yes', callback_data='yes')
btn2 = types.InlineKeyboardButton('No', callback_data='no')
markup.row(btn1, btn2)
bot.send_message(message.chat.id, f'Hello, {message.from_user.first_name}! Will Kevin come today?', reply_markup=markup)
@bot.callback_query_handler(func=lambda callback: True)
def callback_message(callback):
user_id = callback.from_user.id
chat_id = callback.message.chat.id
if callback.data == 'yes':
user_responses[user_id] = 'Yes, Kevin will come today.'
elif callback.data == 'no':
user_responses[user_id] = 'No, Kevin will not come today.'
# Edit the original message to include the user's response
if user_id in user_responses:
bot.edit_message_text(user_responses[user_id], chat_id, callback.message.message_id)
bot.polling(non_stop=True)
此代码将用户的响应存储在按用户 ID 索引的字典 user_responses 中。当用户单击“是”或“否”时,它会更新字典中的用户响应并编辑原始消息以包含用户的响应。这会给用户留下直接响应的印象。然而,它实际上是机器人编辑其原始消息以包含用户的回复。