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

基于Spring Boot的Telegram Bot用户专属群聊自动化实现问询

在Spring Boot中用Telegram Bot实现用户专属群聊自动化

这些功能完全可以实现,以下是具体的实现思路和关键步骤:

核心准备

首先确保你的Telegram Bot已通过BotFather获取有效token,并开启创建群聊、邀请用户的权限(Bot需成为群聊管理员才能执行相关操作)。同时需要维护一个用户-群聊ID映射表(可存储在MySQL、Redis等数据库中),这是实现群聊复用的核心依据。

功能实现细节

1. 检查用户是否已有对应群聊

每次需要给用户发送消息前,先查询映射表:

  • 若存在对应群聊ID,直接复用该群聊
  • 若不存在,执行创建群聊逻辑

Spring Boot中可封装服务类实现查询:

@Service
public class TelegramChatService {
    @Autowired
    private UserChatMappingRepository repository; // 自定义JPA仓库,操作用户-群聊映射表

    public Long getChatIdBySystemUserId(Long systemUserId) {
        UserChatMapping mapping = repository.findBySystemUserId(systemUserId);
        return mapping != null ? mapping.getTelegramChatId() : null;
    }
}

2. 为用户自动创建群聊

使用Telegram Bot API的createSupergroup方法创建群聊(超级群比普通群更适合长期通知场景),创建时需至少邀请一个用户,因此可直接将目标用户加入新群:

@Service
public class TelegramBotService {
    private final TelegramBotsApi botsApi;
    private final YourBot bot; // 自定义Bot类,继承TelegramLongPollingBot

    public TelegramBotService() throws TelegramApiException {
        botsApi = new TelegramBotsApi(DefaultBotSession.class);
        bot = new YourBot();
        botsApi.registerBot(bot);
    }

    public Long createExclusiveChat(Long targetUserId, String chatTitle) throws TelegramApiException {
        // 创建超级群
        CreateSupergroupRequest createRequest = new CreateSupergroupRequest(chatTitle);
        Chat newChat = bot.execute(createRequest);
        
        // 邀请目标用户进群
        bot.execute(new AddChatMemberRequest(newChat.getId(), targetUserId));
        
        return newChat.getId();
    }
}

3. 将用户加入群聊

复用已有群聊时,先检查用户是否在群内,若不在则执行邀请操作:

public void addUserToChat(Long chatId, Long userId) throws TelegramApiException {
    ChatMember member = bot.execute(new GetChatMemberRequest(chatId, userId));
    if (member.getStatus() == ChatMemberStatus.LEFT || member.getStatus() == ChatMemberStatus.KICKED) {
        bot.execute(new AddChatMemberRequest(chatId, userId));
    }
}

4. 向群聊发送消息

直接调用sendMessage方法发送内容:

public void sendMessageToChat(Long chatId, String message) throws TelegramApiException {
    SendMessage sendRequest = new SendMessage();
    sendRequest.setChatId(chatId.toString());
    sendRequest.setText(message);
    bot.execute(sendRequest);
}

完整流程整合

在业务服务中串联所有步骤:

@Service
public class NotificationService {
    @Autowired
    private TelegramChatService chatService;
    @Autowired
    private TelegramBotService botService;
    @Autowired
    private UserChatMappingRepository repository;

    public void sendNotificationToUser(Long systemUserId, String message, String userTelegramId) throws TelegramApiException {
        // 检查是否已有群聊
        Long chatId = chatService.getChatIdBySystemUserId(systemUserId);
        
        if (chatId == null) {
            // 创建新群聊并加入用户
            String chatTitle = "专属通知群 - 用户" + systemUserId;
            chatId = botService.createExclusiveChat(Long.parseLong(userTelegramId), chatTitle);
            // 保存映射关系到数据库
            repository.save(new UserChatMapping(systemUserId, chatId));
        } else {
            // 确保用户在群内
            botService.addUserToChat(chatId, Long.parseLong(userTelegramId));
        }
        
        // 发送消息
        botService.sendMessageToChat(chatId, message);
    }
}

注意事项

  • Bot权限:必须确保Bot是群聊管理员,拥有邀请用户、发送消息的权限
  • 用户隐私:若用户设置了拒绝陌生人邀请,Bot无法直接拉人进群,可改为发送群聊邀请链接让用户主动加入
  • API限流:Telegram API有请求频率限制,需避免触发限流,必要时添加重试机制
  • 映射表维护:若用户退出群聊或群聊被删除,需及时更新映射表,避免后续发送失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 10:22:17