当前位置: 首页 > backend >正文

[TG开发]简单的回声机器人

你好! 如果你想了解如何在Java上编写Telegram机器人,你来对地方了!

准备启动

机器人API基于HTTP请求,但在本书中我将使用Rubenlagus的Java库

安装库

你可以使用不同的方法安装TelegramBots库, 我这里使用Maven

<dependency><groupId>org.telegram</groupId><artifactId>telegrambots</artifactId><version>Latest</version>
</dependency>

让我们开始编码吧

在本节课中,我们将编写一个简单的机器人,它会回显我们发送给它的所有内容。现在,打开inteliidea,创建一个新项目。你可以随意给它起个名字。

  1. 现在,当你在该项目中后,在src目录下创建文件MyAmazingBot.java和Main,java。打开MyAmazingBot.java,并开始编写我们的实际机器人!
  2. 记住! 类必须继承TelegramLongPollingBot并实现必要的方法。
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException;public class MyAmazingBot extends TelegramLongPollingBot {@Overridepublic void onUpdateReceived(Update update) {// TODO}@Overridepublic String getBotUsername() {// TODOreturn null;}@Overridepublic String getBotToken() {// TODOreturn null;}
}
  1. 正如您所理解的,

`getBotUsername()'和`getBotToken ()`必须返回从 @BotFather获取的机器人的用户名和令牌。

import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException;public class MyAmazingBot extends TelegramLongPollingBot {@Overridepublic void onUpdateReceived(Update update) {// TODO}@Overridepublic String getBotUsername() {// Return bot username// If bot username is @MyAmazingBot, it must return 'MyAmazingBot'return "MyAmazingBot";}@Overridepublic String getBotToken() {// Return bot token from BotFatherreturn "12345:qwertyuiopASDGFHKMK";}
}
  1. 现在,让我们转到我们机器人的逻辑部分。

如前所述,我们希望它能够回复我们发送给它的每条文本。`onUpdateReceived(Updateupdate)`方法就是为此而设的。当接收到一条更新时,该方法会被调用。

@Override
public void onUpdateReceived(Update update) {// We check if the update has a message and the message has textif (update.hasMessage() && update.getMessage().hasText()) {// Set variablesString message_text = update.getMessage().getText();long chat_id = update.getMessage().getChatId();SendMessage message = new SendMessage() // Create a message object object.setChatId(chat_id).setText(message_text);try {execute(message); // Sending our message object to user} catch (TelegramApiException e) {e.printStackTrace();}}
}
  1. 该如何运行这个机器人呢? 保存该文件并打开Mainjava。这个文件将实例化TelegramBotsApi并注册我们的新机器人。
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException;
public class Main {public static void main(String[] args) {// TODO Initialize Api Context// TODO Instantiate Telegram Bots API// TODO Register our bot}
}
  1. 现在,让我们初始化API上下文
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException;
public class Main {public static void main(String[] args) {// Initialize Api ContextApiContextInitializer.init();// TODO Instantiate Telegram Bots API// TODO Register our bot}
}
  1. 实例化Telegram机器人API:
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException;
public class Main {public static void main(String[] args) {// Initialize Api ContextApiContextInitializer.init();// Instantiate Telegram Bots APITelegramBotsApi botsApi = new TelegramBotsApi();// TODO Register our bot}
}
  1. 并注册我们的机器人:
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException;
public class Main {public static void main(String[] args) {// Initialize Api ContextApiContextInitializer.init();// Instantiate Telegram Bots APITelegramBotsApi botsApi = new TelegramBotsApi();// Register our bottry {botsApi.registerBot(new MyAmazingBot());} catch (TelegramApiException e) {e.printStackTrace();}}
}
  1. 这是我们的所有文件:
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException;
public class Main {public static void main(String[] args) {// Initialize Api ContextApiContextInitializer.init();// Instantiate Telegram Bots APITelegramBotsApi botsApi = new TelegramBotsApi();// Register our bottry {botsApi.registerBot(new MyAmazingBot());} catch (TelegramApiException e) {e.printStackTrace();}}
}
import org.telegram.telegrambots.api.methods.send.SendMessage;import org.telegram.telegrambots.api.objects.Update;import org.telegram.telegrambots.bots.TelegramLongPollingBot;import org.telegram.telegrambots.exceptions.TelegramApiException;public class MyAmazingBot extends TelegramLongPollingBot {@Overridepublic void onUpdateReceived(Update update) {// We check if the update has a message and the message has textif (update.hasMessage() && update.getMessage().hasText()) {// Set variablesString message_text = update.getMessage().getText();long chat_id = update.getMessage().getChatId();SendMessage message = new SendMessage() // Create a message object object.setChatId(chat_id).setText(message_text);try {execute(message); // Sending our message object to user} catch (TelegramApiException e) {e.printStackTrace();}}}@Overridepublic String getBotUsername() {// Return bot username// If bot username is @MyAmazingBot, it must return 'MyAmazingBot'return "MyAmazingBot";}@Overridepublic String getBotToken() {// Return bot token from BotFatherreturn "12345:qwertyuiopASDGFHKMK";}
}
  1. 现在我们可以将项目打包成可运行的jar文件,并在我们的计算机/服务器上运行它!
java -jar MyAmazingBot.jar

http://www.xdnf.cn/news/17720.html

相关文章:

  • hadoop 前端yarn 8088端口查看任务执行情况
  • 人工智能——CNN基础:卷积和池化
  • 利用生成式AI与大语言模型(LLM)革新自动化软件测试 —— 测试工程师必读深度解析
  • 数据分析可视化学习总结(美妆2)
  • 飞算AI:企业智能化转型的新引擎——零代码重塑生产力
  • CSS动态视口单位:彻底解决移动端适配顽疾,告别布局跳动
  • 高可用实战之Nginx + Apache篇
  • Java面试宝典:ZGC
  • PyTorch基础(Numpy与Tensor)
  • Vue3+AntDesign实现带搜索功能的下拉单选组件
  • 如何生成.patch?
  • 2025年AI大模型应用架构设计十大核心问题深度解析
  • Java pdf工具
  • Java 导出word 实现表格内插入图表(柱状图、折线图、饼状图)--可编辑数据
  • 飞算JavaAI的中间件风暴:Redis + Kafka 全链路实战
  • Android 在 2020-2025 都做哪些更新?
  • 浏览器面试题及详细答案 88道(23-33)
  • Pytorch FSDP权重分片保存与合并
  • CW32L011电机开发板控制教程
  • MVCC底层实现原理
  • Java Web开发:Session与Cookie详细入门指南
  • 深入理解 C++ 中的虚函数:原理、特点与使用场景
  • mac下载maven并配置,以及idea配置
  • 智慧城市数字孪生:城市管理的“平行宇宙”
  • nginx匹配规则
  • 计算机网络体系结构
  • framebuffer
  • 当GitHub宕机时,我们如何保持高效协作?分布式策略与应急方案详解
  • 建设有人文温度的智能社会:规划与实施路径
  • 2小时构建生产级AI项目:基于ViT的图像分类流水线(含数据清洗→模型解释→云API)(第十七章)