栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

Java开发Telegram机器人

Java 更新时间:发布时间: 百科书网 趣学号

基于springboot在【pom】中添加


    org.telegram
    telegrambots
    5.3.0

初始化自己的机器人类并注册

@Component
public class SystemInit implements ApplicationRunner {

    @Autowired
    private MyTelegramBot myTelegramBot;

    @Override
    @SneakyThrows
    public void run(ApplicationArguments args) throws Exception {
        TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
        telegramBotsApi.registerBot(myTelegramBot);
    }
}

其次实现该类

public class MyTelegramBot extends TelegramLongPollingBot {
SendMessage message = new SendMessage();
@Override
public String getBotUsername() {
    return username;
}

@Override
public String getBotToken() {
    return token;
}

@SneakyThrows
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
Long chatId = msg.getChatId();
String content = msg.getText();
message.setChatId(chatId.toString());
message.setText(content);
sendMessage(message);
        }
}
//发送消息
private void sendMessage(SendMessage message) {
    try {
        execute(message); // Call method to send the message
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

}

其中username和token换上自己申请的,服务运行在可翻q的服务器上,给机器人发消息就会收到回复,前提是你的telegram能收到翻q信息。

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/601685.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号