2d44feddee
- Telegram bot for receiving and analyzing messages, photos, and updates - Photo download support with fileId-based naming - Random photo send feature (text "image" triggers random photo from downloads) - Renamed from itm-telegram-bot to ifm-telegram-bot Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
214 lines
8.7 KiB
Java
214 lines
8.7 KiB
Java
package com.ifm.telegram;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.GsonBuilder;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
|
|
import org.telegram.telegrambots.meta.api.methods.GetFile;
|
|
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
|
|
import org.telegram.telegrambots.meta.api.objects.File;
|
|
import org.telegram.telegrambots.meta.api.objects.InputFile;
|
|
import org.telegram.telegrambots.meta.api.objects.Message;
|
|
import org.telegram.telegrambots.meta.api.objects.PhotoSize;
|
|
import org.telegram.telegrambots.meta.api.objects.Update;
|
|
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.Paths;
|
|
import java.util.Comparator;
|
|
import java.util.List;
|
|
import java.util.Random;
|
|
|
|
/**
|
|
* Simple Telegram bot that prints all received updates to console.
|
|
* Useful for analyzing message structure from Telegram.
|
|
*/
|
|
public class MessagePrinterBot extends TelegramLongPollingBot {
|
|
|
|
private static final Logger logger = LoggerFactory.getLogger(MessagePrinterBot.class);
|
|
private static final Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
|
|
|
|
private static final String DOWNLOAD_DIR = "downloads";
|
|
private static final Random random = new Random();
|
|
|
|
private final String botUsername;
|
|
|
|
public MessagePrinterBot(String botToken, String botUsername) {
|
|
super(botToken);
|
|
this.botUsername = botUsername;
|
|
// Ensure download directory exists
|
|
try {
|
|
Files.createDirectories(Paths.get(DOWNLOAD_DIR));
|
|
} catch (Exception e) {
|
|
logger.warn("Could not create download directory: {}", e.getMessage());
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public String getBotUsername() {
|
|
return botUsername;
|
|
}
|
|
|
|
@Override
|
|
public void onUpdateReceived(Update update) {
|
|
// Print full Update JSON
|
|
System.out.println("========== UPDATE RECEIVED ==========");
|
|
System.out.println(gson.toJson(update));
|
|
System.out.println("======================================");
|
|
|
|
// Print human-readable summary
|
|
if (update.hasMessage()) {
|
|
Message msg = update.getMessage();
|
|
printMessageSummary(msg);
|
|
|
|
// If text is "image", send a random photo from downloads
|
|
if (msg.hasText() && msg.getText().trim().equalsIgnoreCase("image")) {
|
|
sendRandomPhoto(msg.getChatId().toString());
|
|
}
|
|
} else if (update.hasEditedMessage()) {
|
|
System.out.println("[EDITED MESSAGE]");
|
|
printMessageSummary(update.getEditedMessage());
|
|
} else if (update.hasCallbackQuery()) {
|
|
System.out.println("[CALLBACK QUERY] data=" + update.getCallbackQuery().getData()
|
|
+ " from=" + update.getCallbackQuery().getFrom().getUserName());
|
|
} else if (update.hasChannelPost()) {
|
|
System.out.println("[CHANNEL POST]");
|
|
printMessageSummary(update.getChannelPost());
|
|
} else {
|
|
System.out.println("[OTHER UPDATE TYPE] updateId=" + update.getUpdateId());
|
|
}
|
|
|
|
System.out.println();
|
|
}
|
|
|
|
private void printMessageSummary(Message msg) {
|
|
StringBuilder sb = new StringBuilder();
|
|
sb.append("[MESSAGE SUMMARY]\n");
|
|
sb.append(" chatId: ").append(msg.getChatId()).append("\n");
|
|
sb.append(" chatType: ").append(msg.getChat().getType()).append("\n");
|
|
sb.append(" messageId: ").append(msg.getMessageId()).append("\n");
|
|
sb.append(" from: ").append(msg.getFrom() != null ? msg.getFrom().getUserName() : "null").append("\n");
|
|
sb.append(" firstName: ").append(msg.getFrom() != null ? msg.getFrom().getFirstName() : "null").append("\n");
|
|
sb.append(" date: ").append(msg.getDate()).append("\n");
|
|
|
|
// Text
|
|
if (msg.hasText()) {
|
|
sb.append(" text: ").append(msg.getText()).append("\n");
|
|
}
|
|
|
|
// Photo
|
|
if (msg.hasPhoto()) {
|
|
List<PhotoSize> photos = msg.getPhoto();
|
|
sb.append(" photo: ").append(photos.size()).append(" sizes\n");
|
|
PhotoSize largest = photos.stream()
|
|
.max(Comparator.comparingInt(PhotoSize::getFileSize))
|
|
.orElse(null);
|
|
if (largest != null) {
|
|
sb.append(" largest: fileId=").append(largest.getFileId()).append("\n");
|
|
sb.append(" size=").append(largest.getWidth()).append("x").append(largest.getHeight()).append("\n");
|
|
sb.append(" fileSize=").append(largest.getFileSize()).append(" bytes\n");
|
|
}
|
|
if (msg.getCaption() != null) {
|
|
sb.append(" caption: ").append(msg.getCaption()).append("\n");
|
|
}
|
|
// Download the largest photo
|
|
if (largest != null) {
|
|
downloadPhoto(largest);
|
|
}
|
|
}
|
|
|
|
// Document
|
|
if (msg.hasDocument()) {
|
|
sb.append(" document: ").append(msg.getDocument().getFileName()).append("\n");
|
|
sb.append(" mimeType: ").append(msg.getDocument().getMimeType()).append("\n");
|
|
sb.append(" fileId: ").append(msg.getDocument().getFileId()).append("\n");
|
|
sb.append(" fileSize: ").append(msg.getDocument().getFileSize()).append(" bytes\n");
|
|
if (msg.getCaption() != null) {
|
|
sb.append(" caption: ").append(msg.getCaption()).append("\n");
|
|
}
|
|
}
|
|
|
|
// Voice
|
|
if (msg.hasVoice()) {
|
|
sb.append(" voice: duration=").append(msg.getVoice().getDuration()).append("s\n");
|
|
sb.append(" fileId: ").append(msg.getVoice().getFileId()).append("\n");
|
|
}
|
|
|
|
// Video
|
|
if (msg.hasVideo()) {
|
|
sb.append(" video: ").append(msg.getVideo().getDuration()).append("s\n");
|
|
sb.append(" fileId: ").append(msg.getVideo().getFileId()).append("\n");
|
|
}
|
|
|
|
// Sticker
|
|
if (msg.hasSticker()) {
|
|
sb.append(" sticker: ").append(msg.getSticker().getEmoji()).append("\n");
|
|
sb.append(" fileId: ").append(msg.getSticker().getFileId()).append("\n");
|
|
}
|
|
|
|
// Location
|
|
if (msg.hasLocation()) {
|
|
sb.append(" location: ").append(msg.getLocation().getLatitude())
|
|
.append(",").append(msg.getLocation().getLongitude()).append("\n");
|
|
}
|
|
|
|
// Contact
|
|
if (msg.hasContact()) {
|
|
sb.append(" contact: ").append(msg.getContact().getFirstName())
|
|
.append(" ").append(msg.getContact().getPhoneNumber()).append("\n");
|
|
}
|
|
|
|
// Reply
|
|
if (msg.getReplyToMessage() != null) {
|
|
sb.append(" replyTo: messageId=").append(msg.getReplyToMessage().getMessageId()).append("\n");
|
|
}
|
|
|
|
System.out.println(sb);
|
|
}
|
|
|
|
private void sendRandomPhoto(String chatId) {
|
|
try {
|
|
java.io.File dir = new java.io.File(DOWNLOAD_DIR);
|
|
java.io.File[] images = dir.listFiles((d, name) ->
|
|
name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png"));
|
|
|
|
if (images == null || images.length == 0) {
|
|
logger.info("No images in downloads/ to send");
|
|
return;
|
|
}
|
|
|
|
java.io.File picked = images[random.nextInt(images.length)];
|
|
SendPhoto sendPhoto = new SendPhoto();
|
|
sendPhoto.setChatId(chatId);
|
|
sendPhoto.setPhoto(new InputFile(picked));
|
|
sendPhoto.setCaption("Random image: " + picked.getName());
|
|
execute(sendPhoto);
|
|
logger.info("Sent random photo: {} to chatId: {}", picked.getName(), chatId);
|
|
} catch (Exception e) {
|
|
logger.error("Failed to send random photo: {}", e.getMessage());
|
|
}
|
|
}
|
|
|
|
private void downloadPhoto(PhotoSize photo) {
|
|
try {
|
|
GetFile getFile = new GetFile(photo.getFileId());
|
|
File file = execute(getFile);
|
|
String filePath = file.getFilePath();
|
|
|
|
// Use fileId as filename, keep extension from Telegram's file_path
|
|
String extension = "";
|
|
if (filePath != null && filePath.contains(".")) {
|
|
extension = filePath.substring(filePath.lastIndexOf("."));
|
|
}
|
|
String savedName = photo.getFileId() + extension;
|
|
Path savePath = Paths.get(DOWNLOAD_DIR, savedName);
|
|
|
|
java.io.File downloaded = downloadFile(file, savePath.toFile());
|
|
logger.info("Photo saved: {} ({} bytes)", downloaded.getAbsolutePath(), downloaded.length());
|
|
} catch (Exception e) {
|
|
logger.error("Failed to download photo: {}", e.getMessage());
|
|
}
|
|
}
|
|
}
|