-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot-api.js
More file actions
50 lines (39 loc) · 1.27 KB
/
Copy pathbot-api.js
File metadata and controls
50 lines (39 loc) · 1.27 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import fetch from 'node-fetch';
export class BotApiClient {
constructor(botToken) {
if (!botToken) {
throw new Error('BotApiClient requires a bot token');
}
this.botToken = botToken;
this.baseUrl = `https://api.telegram.org/bot${botToken}`;
}
async call(method, params = undefined) {
const response = await fetch(`${this.baseUrl}/${method}`, {
method: params ? 'POST' : 'GET',
headers: params ? { 'Content-Type': 'application/json' } : undefined,
body: params ? JSON.stringify(params) : undefined
});
if (!response.ok) {
throw new Error(`Telegram Bot API request failed: ${method} returned HTTP ${response.status}`);
}
const payload = await response.json();
if (!payload.ok) {
throw new Error(`Telegram Bot API request failed: ${method} returned ${payload.description || 'unknown error'}`);
}
return payload.result;
}
async getMe() {
return this.call('getMe');
}
async getBotUsername() {
const me = await this.getMe();
if (!me.username) {
throw new Error('Bot API getMe did not return a username');
}
return me.username;
}
}
export async function resolveBotUsername(botToken) {
const client = new BotApiClient(botToken);
return client.getBotUsername();
}