import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.telegram.telegrambots.meta.api.methods.AnswerPreCheckoutQuery;
import org.telegram.telegrambots.meta.api.methods.invoices.SendInvoice;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.InputFile;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.payments.LabeledPrice;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Component
public class TelegramBot extends TelegramLongPollingBot {
private final BotConfig botConfig;
private final ResourceLoader resourceLoader;
@Value("${provider.token}")
String providerToken;
ArrayList<Product> products = new ArrayList<>();
public TelegramBot(BotConfig botConfig, ResourceLoader resourceLoader) {
this.botConfig = botConfig;
this.resourceLoader = resourceLoader;
products.add(new Product("1", "Iphone 6S Plus", 7000, "Треснуто стекло", "images/Iphone6SPlus.jpg"));
products.add(new Product("2", "Iphone 7 Plus", 9000, "80 процентов батареи", "images/Iphone7.jpg"));
products.add(new Product("3", "Iphone X", 30000, "Нет изъянов", "images/IphoneX.jpg"));
products.add(new Product("4", "Iphone 11 Pro", 40000, "Нет изъянов", "images/Iphone11Pro.jpg"));
}
@Override
public String getBotUsername() {
return botConfig.getBotName();
}
@Override
public String getBotToken() {
return botConfig.getBotToken();
}
@Override
public void onUpdateReceived(Update update) {
if (update == null || (!update.hasMessage() && !update.hasCallbackQuery())) {
return;
}
if (update.hasMessage() && update.getMessage().hasText()) {
long chatId = update.getMessage().getChatId();
String message = update.getMessage().getText();
switch (message) {
case "/start":
try {
startCommand(chatId, update.getMessage().getChat().getFirstName());
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
break;
case "/products":
try {
productCommand(chatId);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
break;
default:
try {
sendMessage(chatId, "Извините, команда не распознана!");
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
}
} else if (update.hasCallbackQuery()) {
CallbackQuery callbackQuery = update.getCallbackQuery();
String callbackData = callbackQuery.getData();
String[] dataParts = callbackData.split(":");
String productId = dataParts[0];
String photoPath = dataParts[1];
Product product = products.stream()
.filter(p -> p.getId().equals(productId))
.findFirst()
.orElse(null);
if (product != null) {
try {
Resource resource = resourceLoader.getResource("classpath:" + product.getPhotoPath());
InputStream inputStream = resource.getInputStream();
InputFile inputFile = new InputFile(inputStream, resource.getFilename());
execute(new SendPhoto(callbackQuery.getMessage().getChatId().toString(), inputFile));
String messageText = "";
switch (product.getId()) {
case "1":
SendInvoice sendInvoice = new SendInvoice();
sendInvoice.setNeedPhoneNumber(true);
sendInvoice.setNeedName(true);
sendInvoice.setNeedShippingAddress(true);
sendInvoice.setChatId(callbackQuery.getMessage().getChatId().toString());
sendInvoice.setTitle(product.getName());
sendInvoice.setDescription(product.getDescription());
sendInvoice.setPayload(product.getId());
sendInvoice.setProviderToken(providerToken);
sendInvoice.setCurrency("RUB");
sendInvoice.setPrices(List.of(new LabeledPrice("Цена", product.getPrice() * 100)));
sendInvoice.setStartParameter("invoice_" + product.getId() + "_" + product.getPrice());
execute(sendInvoice);
break;
case "2":
SendInvoice sendInvoice2 = new SendInvoice();
sendInvoice2.setChatId(callbackQuery.getMessage().getChatId().toString());
sendInvoice2.setTitle(product.getName());
sendInvoice2.setDescription(product.getDescription());
sendInvoice2.setPayload(product.getId());
sendInvoice2.setProviderToken(providerToken);
sendInvoice2.setCurrency("RUB");
sendInvoice2.setPrices(List.of(new LabeledPrice("Цена", product.getPrice() * 100)));
sendInvoice2.setStartParameter("invoice_" + product.getId() + "_" + product.getPrice());
execute(sendInvoice2);
break;
case "3":
SendInvoice sendInvoice3 = new SendInvoice();
sendInvoice3.setChatId(callbackQuery.getMessage().getChatId().toString());
sendInvoice3.setTitle(product.getName());
sendInvoice3.setDescription(product.getDescription());
sendInvoice3.setPayload(product.getId());
sendInvoice3.setProviderToken(providerToken);
sendInvoice3.setCurrency("RUB");
sendInvoice3.setPrices(List.of(new LabeledPrice("Цена", product.getPrice() * 100)));
sendInvoice3.setStartParameter("invoice_" + product.getId() + "_" + product.getPrice());
execute(sendInvoice3);
break;
case "4":
SendInvoice sendInvoice4 = new SendInvoice();
sendInvoice4.setChatId(callbackQuery.getMessage().getChatId().toString());
sendInvoice4.setTitle(product.getName());
sendInvoice4.setDescription(product.getDescription());
sendInvoice4.setPayload(product.getId());
sendInvoice4.setProviderToken(providerToken);
sendInvoice4.setCurrency("RUB");
sendInvoice4.setPrices(List.of(new LabeledPrice("Цена", product.getPrice() * 100)));
sendInvoice4.setStartParameter("invoice_" + product.getId() + "_" + product.getPrice());
execute(sendInvoice4);
break;
default:
messageText = "Неизвестный товар";
break;
}
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(callbackQuery.getMessage().getChatId().toString());
sendMessage.setText(messageText);
execute(sendMessage);
} catch (IOException | TelegramApiException e) {
throw new RuntimeException(e);
}
}
}
}
// Функции команд:
private void startCommand(long chatId, String name) throws TelegramApiException {
String answer = "Привет!, " + name + "\nСписок команд: /start";
sendMessage(chatId, answer);
}
private void productCommand(long chatId) throws TelegramApiException {
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
ArrayList<ArrayList<InlineKeyboardButton>> rowsInlineKeyboard = new ArrayList<>();
ArrayList<InlineKeyboardButton> rowInlineKeyboard = new ArrayList<>();
for (Product product : products) {
String callbackData = product.getId() + ":" + product.getPhotoPath(); // Сохраняем id и путь к файлу
rowInlineKeyboard.add(InlineKeyboardButton.builder()
.text(product.getName() + ", " + product.getPrice())
.callbackData(callbackData)
.build());
if (rowInlineKeyboard.size() == 2) { // добавляем кнопки в ряд по 2
rowsInlineKeyboard.add(rowInlineKeyboard);
rowInlineKeyboard = new ArrayList<>();
}
}
if (!rowInlineKeyboard.isEmpty()) { // добавляем оставшиеся кнопки
rowsInlineKeyboard.add(rowInlineKeyboard);
}
inlineKeyboardMarkup.setKeyboard(List.of(rowsInlineKeyboard.toArray(new ArrayList[0])));
SendMessage message = new SendMessage();
message.setChatId(chatId);
message.setText("Выберите товар:");
message.setReplyMarkup(inlineKeyboardMarkup);
execute(message);
}
// Функция для отправки сообщений:
private void sendMessage(long chatId, String text) throws TelegramApiException {
SendMessage message = new SendMessage();
message.setChatId(chatId);
message.setText(text);
try {
execute(message);
} catch (TelegramApiException e){
System.out.println(e);
}
}
}