102 lines · 3.1 KB
const API_BASE = "https://api.telegram.org";

export interface TelegramFile {
  filename: string;
  contentType: string;
  content: ArrayBuffer;
}

class TelegramApiError extends Error {
  status: number;

  constructor(status: number, message: string) {
    super(message);
    this.status = status;
  }
}

async function telegramFetch(botToken: string, method: string, init: RequestInit): Promise<Response> {
  const response = await fetch(`${API_BASE}/bot${botToken}/${method}`, init);

  if (!response.ok) {
    const body = await response.text().catch(() => "");
    throw new TelegramApiError(response.status, `Telegram API ${method} failed: ${response.status} ${body}`);
  }

  return response;
}

export interface TelegramButton {
  text: string;
  data: string;
}

// Telegram has no separate "create a DM channel" step the way Discord does:
// a chat_id is just the user's numeric id, already known from whatever
// update (a command message) established the owner in the first place.
export async function sendMessage(
  botToken: string,
  chatId: string,
  text: string,