Java Telegram 机器人 newbot

01 Telegram 电报机器人

注册 bot

1. 搜索 @BotFather 并对话

@BotFather

2. 发送/start 开始会话

start

3. 发送/newbot 创建机器人

newbot

输入机器人的 nameusername,创建完成返回 token,之后发送消息需要用到它。

4. 搜索 @GetIDsBot 获取 chat ID

Telegram 中每个用户、频道、群组都会有一个 chat ID,机器人发送消息需要指定 chat ID 来将消息发送到指定用户。

@GetIDsBot

chatID

这里的关键点在于,如何获取 channel/group 的 chat id,这里咱确实踩了下 🕳,找了蛮久也没有找到正确的方法,最后发现其实是咱一开始姿势不对,后来找到 stackoverflow 有个回答 Telegram Bot - how to get a group chat id? 成功解决问题。

In order to get the group chat id, do as follows:

  • 1.

    Add the Telegram BOT to the group.

  • 2.

    Get the list of updates for your BOT.

  • 3.

    Use the "id" of the "chat" object to send your messages.

即先将机器人加入频道或群组,然后通过下面的接口获取频道或群组的 chat id。

https://api.telegram.org/bot${token}/getUpdates

2020/08/21 時雨 直接 @GetIDs Bot,将其拉入群组即可获得群组 ID

发送消息

机器人注册成功,咱就可以发送消息了,参考官方接口文档参考 Telegram Bot API,访问接口发送消息:

https://api.telegram.org/bot${token}/sendMessage?chat_id=${chat_id}&text=hello

通过浏览器或者 curl 请求这个地址即可发送消息。

{

"ok": true,

"result": {

"message_id": 6,

"from": {

"id": 1010000036,

"is_bot": true,

"first_name": "chanshiyubot",

"username": "chanshiyu_bot"

},

"chat": {

"id": 98000006,

"first_name": "蝉",

"last_name": "时雨",

"type": "private"

},

"date": 1578035550,

"text": "text"

}

}

SpringBoot 集成

正片开始,已经有了收发消息的电报机器人,通过 github 开源库 java-telegram-bot-api,可以轻松集成到 SpringBoot 项目中,实时监控服务状态。

Java library for interacting with Telegram Bot API

  • Full support of all Bot API 4.6 methods

  • Telegram Passport and Decryption API

  • Bot Payments

  • Gaming Platform

添加依赖并配置 token

<dependency>

<groupId>com.github.pengrad</groupId>

<artifactId>java-telegram-bot-api</artifactId>

<version>4.6.0</version>

</dependency>

机器人 token:

telegram-bot:

token: ${your_bot_token}

注册服务

@Slf4j

@Service

@RequiredArgsConstructor(onConstructor = @__(@Autowired))

public class TelegramBotService implements UpdatesListener {

/**

* token

*/

@Value("${telegram-bot.token}")

private String telegramBotToken;

/**

* bot

*/

private TelegramBot bot;

@Override

public int process(List<Update> updates) {

updates.forEach(update -> {

log.info("机器人收到消息 -> {}", update);

});

return UpdatesListener.CONFIRMED_UPDATES_ALL;

}

public void run() {

// Create your bot passing the token received from @BotFather

this.bot = new TelegramBot(this.telegramBotToken);

// Register for updates

this.bot.setUpdatesListener(this);

}

/**

* 发送消息

*

* @param type 消息类型

* @param chatId 会话ID

* @param text 消息内容

*/

public void sendMessage(Byte type, long chatId, String text) {

SendResponse response;

if (type == 1) {

// 图片

response = bot.execute(new SendPhoto(chatId, text));

} else {

// 文本

response = bot.execute(new SendMessage(chatId, text));

}

log.info("发送消息 -> {}", response);

}

public void close() {

this.bot.removeGetUpdatesListener();

}

}

启动机器人

@Component

@RequiredArgsConstructor(onConstructor = @__(@Autowired))

public class TelegramStartedBootstrap implements ApplicationListener<ContextRefreshedEvent> {

private final TelegramBotService telegramBotService;

@Override

public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

telegramBotService.run();

}

}

最终成果,完美收发消息:

https://chanshiyu.gitbook.io/blog/shi-yu/2020/01telegram-dian-bao-ji-qi-ren

要在Java中实现Telegram机器人回复点击复制文本的功能,您需要使用Telegram Bot API和Java编程语言。以下是一些示例代码,可以帮助您开始: 1. 首先,您需要创建一个Telegram Bot,并获取其API密钥。 2. 接下来,您需要使用Telegram Bot API的Java库,例如TelegramBots。 3. 使用TelegramBots库,您可以编写Java代码来实现机器人回复点击复制文本的功能。以下是一些示例代码: ```java import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; public class MyBot extends TelegramLongPollingBot { @Override public void onUpdateReceived(Update update) { Message message = update.getMessage(); if (message != null && message.hasText()) { SendMessage sendMessage = new SendMessage() .setChatId(message.getChatId()) .setText("点击这里复制文本") .setReplyMarkup(new InlineKeyboardMarkup() .setKeyboard(Arrays.asList( Arrays.asList(new InlineKeyboardButton() .setText("复制") .setCallbackData(message.getText())) ))); try { execute(sendMessage); } catch (TelegramApiException e) { e.printStackTrace(); } } } @Override public String getBotUsername() { return "MyBot"; } @Override public String getBotToken() { return "YOUR_API_KEY"; } } ``` 在上面的代码中,我们在收到用户消息时,发送一条消息回复用户,并附带一个可以点击的按钮,点击按钮后可以复制文本。当用户点击按钮时,我们使用`callbackData`来将文本数据传递回来,然后您可以在`onUpdateReceived`方法中处理这个回调数据。 请注意,上述代码仅供参考,您需要根据自己的需求进行适当的修改和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值