89 lines
2.0 KiB
TypeScript
89 lines
2.0 KiB
TypeScript
export interface TelegramUpdateUser {
|
|
id: number;
|
|
username?: string;
|
|
first_name: string;
|
|
last_name?: string;
|
|
}
|
|
|
|
export interface TelegramUpdateMessage {
|
|
message_id: number;
|
|
text?: string;
|
|
from?: TelegramUpdateUser;
|
|
chat: {
|
|
id: number;
|
|
};
|
|
}
|
|
|
|
export interface TelegramUpdate {
|
|
update_id: number;
|
|
message?: TelegramUpdateMessage;
|
|
}
|
|
|
|
export interface TelegramBotTransport {
|
|
getUpdates(input: {
|
|
offset?: number;
|
|
timeoutSeconds: number;
|
|
}): Promise<TelegramUpdate[]>;
|
|
sendMessage(input: {
|
|
chatId: number;
|
|
text: string;
|
|
}): Promise<void>;
|
|
}
|
|
|
|
export function createTelegramBotApiTransport(botToken: string): TelegramBotTransport {
|
|
const baseUrl = `https://api.telegram.org/bot${botToken}`;
|
|
|
|
return {
|
|
async getUpdates({ offset, timeoutSeconds }) {
|
|
const response = await fetch(`${baseUrl}/getUpdates`, {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
timeout: timeoutSeconds,
|
|
...(offset !== undefined ? { offset } : {}),
|
|
}),
|
|
});
|
|
|
|
const payload = (await response.json()) as {
|
|
ok: boolean;
|
|
result?: TelegramUpdate[];
|
|
description?: string;
|
|
};
|
|
|
|
if (!response.ok || !payload.ok || !payload.result) {
|
|
throw new Error(
|
|
payload.description ?? `Telegram getUpdates failed with status ${response.status}.`,
|
|
);
|
|
}
|
|
|
|
return payload.result;
|
|
},
|
|
|
|
async sendMessage({ chatId, text }) {
|
|
const response = await fetch(`${baseUrl}/sendMessage`, {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
chat_id: chatId,
|
|
text,
|
|
}),
|
|
});
|
|
|
|
const payload = (await response.json()) as {
|
|
ok: boolean;
|
|
description?: string;
|
|
};
|
|
|
|
if (!response.ok || !payload.ok) {
|
|
throw new Error(
|
|
payload.description ?? `Telegram sendMessage failed with status ${response.status}.`,
|
|
);
|
|
}
|
|
},
|
|
};
|
|
}
|