SpringBoot实现Tg机器人,发送消息
使用的是官方提供的依赖telegrambots6.3,发送消息现在遇到了问题,如何设置机器人发送的消息,用户点击消息内容就可以将消息复制到剪贴板。
使用的是官方提供的依赖telegrambots6.3,发送消息现在遇到了问题,如何设置机器人发送的消息,用户点击消息内容就可以将消息复制到剪贴板。
使用 Telegram Bot API 和 TelegramBots 库在 Spring Boot 中实现 Telegram 机器人发送消息非常简单。首先,需要先在 Telegram 上创建一个机器人,然后获取到它的 token。
一种实现方式是使用 TelegramBots 的 AbstractBot 类来创建一个机器人类。然后在这个机器人类中重写 onUpdateReceived 方法来处理消息,在这里你可以使用 SendMessage 方法来发送消息。
举个例子
@Service
public class MyTelegramBot extends TelegramLongPollingBot {
private final String botToken = "YOUR_BOT_TOKEN";
private final String botUsername = "YOUR_BOT_USERNAME";
@Override
public String getBotUsername() {
return botUsername;
}
@Override
public String getBotToken() {
return botToken;
}
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
String messageText = update.getMessage().getText();
long chatId = update.getMessage().getChatId();
SendMessage message = new SendMessage()
.setChatId(chatId)
.setText("You said: " + messageText);
try {
execute(message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
}
如果你想要让用户点击消息内容可以将其复制到剪贴板,那么你需要发送一个 InlineKeyboardButton 类型的消息。这类消息在用户点击时会发送一个 callback_data 到你的机器人,然后你可以在机器人类中重写 onCallbackQuery 方法来处理这个 callback_data 。
举个例子
@Override
public void onUpdateReceived(Update update) {
if (update.hasCallbackQuery()) {
String callbackData = update.getCallbackQuery().getData();
long chatId = update.getCallbackQuery().getMessage().getChatId// if callbackData is the string you set in your InlineKeyboardButton
if ("COPY_MESSAGE".equals(callbackData)) {
String messageText = update.getCallbackQuery().getMessage().getText();
// copy messageText to clipboard
// You can use ClipboardUtils or other libraries to do this
}
具体来讲,你需要在你的 onUpdateReceived 方法中使用 InlineKeyboardButton 来创建一个按钮。按钮的 callback_data 可以是任意的字符串,我选择的是"COPY_MESSAGE"。 你可以在 onCallbackQuery 中通过这个 callback_data 来判断是哪一个按钮被点击。然后你可以使用你喜欢的工具来将消息文本复制到剪贴板上。
SendMessage message = new SendMessage()
.setChatId(chatId)
.setText(messageText);
// create InlineKeyboardButton
InlineKeyboardButton button = new InlineKeyboardButton()
.setText("Copy message")
.setCallbackData("COPY_MESSAGE");
// create InlineKeyboardMarkup
InlineKeyboardMarkup markup = new InlineKeyboardMarkup();
List<List<InlineKeyboardButton>> buttons = new ArrayList<>();
buttons.add(Collections.singletonList(button));
markup.setKeyboard(buttons);
message.setReplyMarkup(markup);
execute(message);
请注意,每个消息都有一个唯一的消息 ID,所以你可以将其存储在按钮的 callback_data 中并在 onCallbackQuery 中检索它。这样你就可以在点击按钮后找到它对应的消息并将其复制到剪贴板中。还有一些需要注意的地方:
在发送消息时使用 execute() 方法,这样 Telegram Bot API 才能正确地处理消息。
如果你想要更多地控制 Telegram Bot API 的行为,你可以直接使用 TelegramBotsApi 类来注册机器人和处理更新。
如果你使用了多线程来处理更新,请确保在 onUpdateReceived 方法中对 execute() 方法使用同步。
如果你发现机器人没有收到消息,请检查你的 bot token 是否正确。