0%

TelegramBot申請與開發

telegrambot的使用與開發相較於linebot來說是好上手很多
接下來就是介紹開發與使用方式

telegrambot 申請

在telegram search bar上搜尋@BotFather
然後完成附圖的流程

telegrambot API使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
https://api.telegram.org/bot{token}/getUpdates
# 取得chatid
{
"ok": true,
"result": [
{
"update_id": 123456789,
"message": {
"message_id": 99,
"from": {
"id": 123456789,
"is_bot": false,
"first_name": "",
"last_name": "",
"username": "",
"language_code": ""
},
"chat": {
"id": -314847207,
"title": "this is a title",
"type": "group",
"all_members_are_administrators": true
},
"date": 1573288754,
"text": "messsage"
}
}
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
https://api.telegram.org/bot{token}/sendMessage?chat_id={channelid}&text={message}
# 嘗試發送訊息
{
"ok": true,
"result": {
"message_id": 99,
"from": {
"id": 123456789,
"is_bot": true,
"first_name": "",
"username": ""
},
"chat": {
"id": 123456789,
"title": "this is a title",
"type": "group",
"all_members_are_administrators": true
},
"date": 1573289062,
"text": "messsage"
}
}

更多API參考 Telegram Bot API

telegrambot JAVASDK使用

maven引用

1
2
3
4
5
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>4.4.0.1</version>
</dependency>

繼承TelegramLongPollingBot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Override
public String getBotUsername()
{
return "userName";
}

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

@Override
public void onUpdateReceived(Update update)
{
if (update.hasMessage() && update.getMessage().hasText())
{
User user = update.getMessage().getFrom();
String rcvMessage = update.getMessage().getText();
String source = String.format("收到來自[%s%s]的訊息內容=%s", user.getFirstName(), user.getLastName(), rcvMessage);
SendMessage message = new SendMessage().setChatId(update.getMessage().getChatId()).setText(source);
try
{
execute(message);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

BotClass使用

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args)
{
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
try
{
botsApi.registerBot(new Telegram());
}
catch (Exception e)
{
e.printStackTrace();
}
}

最後完成範例