-
Notifications
You must be signed in to change notification settings - Fork 7
/
telegram.js
105 lines (91 loc) · 2.5 KB
/
telegram.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { hmacSha256, hex } from './cryptoUtils.js';
const TELEGRAM_API_BASE_URL = 'https://api.telegram.org/bot';
class TelegramAPI {
constructor(token, useTestApi = false) {
this.token = token;
let testApiAddendum = useTestApi ? 'test/' : '';
this.apiBaseUrl = `${TELEGRAM_API_BASE_URL}${token}/${testApiAddendum}`;
}
async calculateHashes(initData) {
const urlParams = new URLSearchParams(initData);
const expectedHash = urlParams.get("hash");
urlParams.delete("hash");
urlParams.sort();
let dataCheckString = "";
for (const [key, value] of urlParams.entries()) {
dataCheckString += `${key}=${value}\n`;
}
dataCheckString = dataCheckString.slice(0, -1);
let data = Object.fromEntries(urlParams);
data.user = JSON.parse(data.user||null);
data.receiver = JSON.parse(data.receiver||null);
data.chat = JSON.parse(data.chat||null);
const secretKey = await hmacSha256(this.token, "WebAppData");
const calculatedHash = hex(await hmacSha256(dataCheckString, secretKey));
return {expectedHash, calculatedHash, data};
}
async getUpdates(lastUpdateId) {
const url = `${this.apiBaseUrl}getUpdates`;
const params = {};
if (lastUpdateId) {
params.offset = lastUpdateId + 1;
}
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params),
});
return response.json();
}
async sendMessage(chatId, text, parse_mode, reply_to_message_id) {
const url = `${this.apiBaseUrl}sendMessage`;
const params = {
chat_id: chatId,
text: text,
};
if (parse_mode) {
params.parse_mode = parse_mode;
}
if (reply_to_message_id) {
params.reply_to_message_id = reply_to_message_id;
}
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
});
return response.json();
}
async setWebhook(externalUrl, secretToken) {
const params = {
url: externalUrl,
};
if (secretToken) {
params.secret_token = secretToken;
}
const url = `${this.apiBaseUrl}setWebhook`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
});
return response.json();
}
async getMe() {
const url = `${this.apiBaseUrl}getMe`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
return response.json();
}
}
export { TelegramAPI as Telegram }