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

[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.lryc.cn/news/619580.html

相关文章:

  • 科技赋能虚拟形象:3D人脸扫描设备的应用与未来
  • vscode+phpstudy+xdebug如何调试php
  • 【R语言】R语言的工作空间映像(workspace image,通常是.RData)详解
  • YOLO v1 输出结构、预测逻辑与局限性详解
  • 教育元宇宙:一场重构教育生态的数字革命
  • 在实验室连接地下车库工控机及其数据采集设备
  • 面向局部遮挡场景的目标检测系统设计与实现
  • 开源WAF新标杆:雷池SafeLine用语义分析重构网站安全边界
  • Go语言实战案例:使用Gin处理路由参数和查询参数
  • .net\c#web、小程序、安卓开发之基于asp.net家用汽车销售管理系统的设计与实现
  • Redis学习——Redis的十大类型String、List、Hash、Set、Zset
  • SQL详细语法教程(一)--数据定义语言(DDL)
  • PCIe Base Specification解析(十)
  • 基于机器学习的自动驾驶汽车新型失效运行方法
  • BGP综合实验_Te. BGP笔记
  • Python实战教程:PDF文档自动化编辑与图表绘制全攻略
  • Blender模拟结构光3D Scanner(一)外参数匹配
  • 解决:nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module
  • PyTorch神经网络工具箱(神经网络核心组件)
  • 第十二节:粒子系统:海量点渲染
  • 5.0.9.1 C# wpf通过WindowsFormsHost嵌入windows media player(AxInterop.WMPLib)
  • Go 1.25正式发布
  • ant-design a-from-model的校验
  • 自然语言处理的实际应用
  • OpenAI官方写的GPT-5 prompt指南
  • [C语言]第二章-从Hello World到头文件
  • 服务器硬件电路设计之 I2C 问答(五):I2C 总线数据传输方向如何确定、信号线上的串联电阻有什么作用?
  • Vue实时刷新,比如我提交审核,审核页面还需要点查询才能看到最新数据
  • 广州健永信息科技有限公司发展历程
  • 【分布式 ID】一文详解美团 Leaf