你好! 如果你想了解如何在Java上編寫Telegram機器人,你來對地方了!
準備啟動
機器人API基于HTTP請求,但在本書中我將使用Rubenlagus的Java庫
安裝庫
你可以使用不同的方法安裝TelegramBots庫, 我這里使用Maven
<dependency><groupId>org.telegram</groupId><artifactId>telegrambots</artifactId><version>Latest</version>
</dependency>
讓我們開始編碼吧
在本節課中,我們將編寫一個簡單的機器人,它會回顯我們發送給它的所有內容。現在,打開inteliidea,創建一個新項目。你可以隨意給它起個名字。
- 現在,當你在該項目中后,在src目錄下創建文件MyAmazingBot.java和Main,java。打開MyAmazingBot.java,并開始編寫我們的實際機器人!
- 記住! 類必須繼承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;}
}
- 正如您所理解的,
`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";}
}
- 現在,讓我們轉到我們機器人的邏輯部分。
如前所述,我們希望它能夠回復我們發送給它的每條文本。`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();}}
}
- 該如何運行這個機器人呢? 保存該文件并打開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}
}
- 現在,讓我們初始化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}
}
- 實例化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}
}
- 并注冊我們的機器人:
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.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";}
}
- 現在我們可以將項目打包成可運行的jar文件,并在我們的計算機/服務器上運行它!
java -jar MyAmazingBot.jar