You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以InputStream形式发送JAR包内图片至Telegram?

解决方案:从JAR包中通过InputStream发送图片给Telegram用户

可以实现,InputFile类支持通过InputStream构建实例,只需指定带后缀的文件名即可让Telegram识别文件格式。

核心修改代码

将原本地文件发送的逻辑替换为从JAR资源读取输入流发送:

@Override
public void onUpdateReceived(Update update) {
    var message = update.getMessage();
    if (message == null || message.getFrom() == null) {
        return;
    }
    var userId = message.getFrom().getId();
    
    // 从JAR包内读取图片资源
    try (InputStream imgStream = this.getClass().getResourceAsStream("/img/hello.png")) {
        if (imgStream == null) {
            // 资源不存在时反馈用户
            execute(SendMessage.builder()
                    .chatId(userId)
                    .text("图片资源不存在")
                    .build());
            return;
        }
        
        // 用InputStream构建InputFile,第二个参数指定文件名(需带后缀)
        InputFile photo = new InputFile(imgStream, "hello.png");
        
        execute(SendPhoto.builder()
                .chatId(userId)
                .photo(photo)
                .build());
    } catch (IOException | TelegramApiException e) {
        e.printStackTrace();
    }
}

原基础代码与依赖

本地文件发送的原始代码

public class TelegramBot extends TelegramLongPollingBot {

    public TelegramBot(...) {
        super(botToken);
        this.botName = botName();
    }

    @Override
    public String getBotUsername() {
        return botName;
    }

    @Override
    public void onUpdateReceived(Update update) {
        var message = update.getMessage();
        var incomingMessage = Objects.isNull(message.getText()) ? "" : message.getText().toLowerCase();
        var user = message.getFrom();
        var userId = user.getId();

        execute(SendPhoto.builder()
                .chatId(userId)
                .photo(new InputFile(new java.io.File("/home/xxx/img/hello.png")))
                .build());
    }
}

Maven依赖

<dependency>
    <groupId>org.telegram</groupId>
    <artifactId>telegrambots</artifactId>
    <version>${telegrambots.version}</version>
</dependency>

Spring Boot集成实现

以下是适配Spring Boot环境的完整实现:

1. Bot配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;

@Configuration
public class TelegramBotConfig {

    @Bean
    public TelegramBotsApi telegramBotsApi(TelegramBot telegramBot) throws TelegramApiException {
        TelegramBotsApi api = new TelegramBotsApi(DefaultBotSession.class);
        api.registerBot(telegramBot);
        return api;
    }
}

2. 带资源读取的Bot实现类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.objects.InputFile;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import java.io.IOException;
import java.io.InputStream;

@Component
public class TelegramBot extends TelegramLongPollingBot {

    private final String botUsername;

    public TelegramBot(@Value("${telegram.bot.token}") String botToken,
                       @Value("${telegram.bot.username}") String botUsername) {
        super(botToken);
        this.botUsername = botUsername;
    }

    @Override
    public String getBotUsername() {
        return botUsername;
    }

    @Override
    public void onUpdateReceived(Update update) {
        if (update.getMessage() == null || update.getMessage().getFrom() == null) {
            return;
        }
        Long userId = update.getMessage().getFrom().getId();
        
        try (InputStream imgStream = this.getClass().getResourceAsStream("/img/hello.png")) {
            if (imgStream == null) {
                sendMessage(userId, "图片资源未找到");
                return;
            }
            InputFile photo = new InputFile(imgStream, "hello.png");
            SendPhoto sendPhoto = SendPhoto.builder()
                    .chatId(userId)
                    .photo(photo)
                    .caption("这是来自JAR包内的图片")
                    .build();
            execute(sendPhoto);
        } catch (IOException | TelegramApiException e) {
            try {
                sendMessage(userId, "发送图片失败:" + e.getMessage());
            } catch (TelegramApiException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    private void sendMessage(Long chatId, String text) throws TelegramApiException {
        execute(org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder()
                .chatId(chatId)
                .text(text)
                .build());
    }
}

3. 配置文件(application.yml)

telegram:
  bot:
    token: 你的Telegram Bot Token
    username: 你的Bot用户名

内容的提问来源于stack exchange,提问作者zappee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:42:16