Skip to content

Instantly share code, notes, and snippets.

@sevapp
Last active October 1, 2023 14:22
Show Gist options
  • Save sevapp/876e76399c2f88129f5259e17afe9582 to your computer and use it in GitHub Desktop.
Save sevapp/876e76399c2f88129f5259e17afe9582 to your computer and use it in GitHub Desktop.
Safe message sending script in Telegram with just 49 lines of code
import fetchify from "https://deno.land/x/fetchify@0.2.8/mod.ts";
export class TelegramMailer {
private tgApi;
private queue: Deno.Kv = undefined as unknown as Deno.Kv;
constructor(token: string) {
this.tgApi = fetchify.create({
baseURL: `https://api.telegram.org/bot${token}/`,
limiter: {
rps: 28,
"429": (res) =>
res.headers.get("retry_after") as unknown as number *
1000 || 1000,
},
headers: {
"Content-Type": "application/json",
},
});
}
async start() {
this.queue = await Deno.openKv();
this.queue.listenQueue(async (msg) => {
// @ts-expect-error
const { chat_id, text } = msg;
try {
const res = await this.tgApi.post("sendMessage", {
timeout: 10000,
body: JSON.stringify({ chat_id, text }),
});
console.log(
`message delivered to ${chat_id}; ${res.status} ${res.statusText}`,
);
} catch (e) {
console.log(`the message was not delivered to ${chat_id}`);
console.log(e);
}
});
}
async notify(chat_id: number, text: string, delay?: number) {
await this.queue.enqueue({ text, chat_id }, {
delay,
});
}
}
@sevapp
Copy link
Author

sevapp commented Oct 1, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment