2019年9月13日 星期五

telegram BotAPI

安裝好 telegram 後,開啟 https://core.telegram.org/bots 文檔

開啟你的 telegram,然後點紅框的連結,即可加入 BotFather
指令查詢:輸入 /start 或 /help 會出現可以打得指令
/newbot 新增一個 bot

出現 Alright, a new bot. How are we going to call it? Please choose a name for your bot. 後
為你的 bot 取一個名字

取好後,會出現
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.

再取一個使用者名稱,一定要 bot 結尾
這個地方我試了好幾個名稱都不行

不行的訊息:
Sorry, this username is already taken. Please try something different.

成功後,會出現 Done! Congratulations on your new bot. You will find it at 開頭的
同時 telegram 也會增加一個 bot
Use this token to access the HTTP API 是取得的 token




可以使用 /token 和 /revoke 重新產生 token 和註消 token

如果按了清螢幕,所以看不到 token 了,還可以用 /mybots
然後點擊你取的 username,再點擊 API Token 即可

開啟群組:

/setjoingroups
@你的 username
然後開啟或關閉
這個功能能讓你的 bot 加入其他的群組
然後在 xxxbot 隨便打幾個字,然後新建群組後,將 xxxbot 加進去就可以對這個群發送訊息了




https://api.telegram.org/bot{你的 token}/getUpdates 可以取得你向你的 bot 發訊息的 json 內容
其中 id 表示此群的 id,如果有加入群組,每個群組的 id 會不一樣

加入群組:
創一個群組後,將機器人加入,並發訊息,然後在上面的網址 getUpdates 裡會有 id


使用 java 11 發送訊息:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class TestTelegram {
    private final String TELEGRAM_TOKEN = "你的 token";
    private final String CHAT_ID = "你的群組 id 或機器人 id";
    private final String TEXT = "要發送的訊息";

    public static void main(String[] args) throws Exception {
        TestTelegram telegram = new TestTelegram();
        HttpClient client = HttpClient.newBuilder().build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(
                        "https://api.telegram.org/bot" + telegram.TELEGRAM_TOKEN +
                                "/sendMessage")
                )
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString("chat_id=" + telegram.CHAT_ID + "&text=" + telegram.TEXT))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
    }
}




使用 apache 發送訊息:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://api.telegram.org/bot" + 得到的 token +
"/sendMessage");

httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("chat_id", CHAT_ID));
urlParameters.add(new BasicNameValuePair("text", TEXT));
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));

CloseableHttpResponse execute = httpClient.execute(httpPost);
execute.close();

沒有留言:

張貼留言