-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.ts
176 lines (159 loc) · 4.03 KB
/
telegram.ts
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { debuglog } from 'node:util'
import phin from 'phin'
const debug = debuglog('notifications/telegram')
// https://core.telegram.org/bots/api#chat
interface Chat {
description?: string
first_name?: string
id: number
last_name?: string
title?: string
type: 'private' | 'group' | 'supergroup' | 'channel'
username?: string
}
// https://core.telegram.org/bots/api#user
interface User {
first_name: string
id: number
is_bot: boolean
last_name?: string
username?: string
}
interface TelegramAPISendMessageError {
description: string
error_code: number
ok: boolean
}
interface TelegramAPISendMessageSuccess {
ok: boolean
result: {
chat: Chat
date: number // unix timestamp
from: User
message_id: number
text?: string
}
}
// https://core.telegram.org/bots/api#message
type SendMessageResponseBody =
| TelegramAPISendMessageError
| TelegramAPISendMessageSuccess
export interface Config {
/**
* Unique identifier for the target chat or username of the target Telegram
* channel (in the format \@channelusername).
*/
chat_id: string
/**
* Text of the message to be sent, 1-4096 characters after entities parsing.
*/
text: string
/**
* The token of your Telegram bot.
* https://core.telegram.org/bots/api#authorizing-your-bot
*/
token: string
}
export interface Options {
/**
* Sends the message silently. Users will receive a notification with no sound.
*/
disable_notification?: boolean
/**
* Disables link previews for links in this message.
*/
disable_web_page_preview?: boolean
/**
* https://core.telegram.org/bots/api#formatting-options
*/
parse_mode?: 'HTML' | 'MarkdownV2'
}
interface ErrorMessageConfig {
chat_id: string
description: string
error_code: number
}
/**
* https://core.telegram.org/bots/api#making-requests
*/
const errorMessageFromTelegramApi = ({
chat_id,
description,
error_code
}: ErrorMessageConfig) => {
switch (error_code) {
case 400: {
return description
}
case 404: {
return `Telegram chat id ${chat_id} not found`
}
default: {
return description
}
}
}
/**
* Send a text message to a Telegram chat, using the Telegram API.
*
* https://core.telegram.org/bots/api#sendmessage
*/
export const send = async (
{ chat_id, text, token }: Config,
options?: Options
) => {
if (!chat_id) {
throw new Error('chat_id not set')
}
if (!token) {
throw new Error('token not set')
}
debug(`send Telegram message to chat id ${chat_id}`)
const data = {
chat_id,
disable_notification: options?.disable_notification || true,
disable_web_page_preview: options?.disable_web_page_preview || false,
parse_mode: options?.parse_mode || 'HTML',
text
}
try {
const res = await phin<SendMessageResponseBody>({
data,
headers: { 'Content-Type': 'application/json' },
method: 'POST',
parse: 'json',
url: `https://api.telegram.org/bot${token}/sendMessage`
})
if (!res.body.ok) {
const b = res.body as TelegramAPISendMessageError
debug(
`Telegram message was NOT delivered to chat id ${chat_id}. Original Telegram API response: %O`,
b
)
return {
delivered: false,
message: errorMessageFromTelegramApi({
chat_id,
description: b.description,
error_code: b.error_code
})
}
} else {
const b = res.body as TelegramAPISendMessageSuccess
debug(
`Telegram message delivered to chat id ${chat_id}. Original Telegram API response: %O`,
b
)
const r = b.result
const delivered_at = new Date(r.date * 1000).toISOString()
return {
delivered: true,
delivered_at,
message: `message id ${r.message_id} delivered to chat id ${r.chat.id} (username ${r.chat.username}) by bot ${r.from.first_name}`
}
}
} catch (err: any) {
debug(`Telegram API could not respond. Original error: %O`, err)
throw new Error(`Telegram API could not respond: ${err.message}`)
}
}