Last active
October 1, 2023 14:22
-
-
Save sevapp/876e76399c2f88129f5259e17afe9582 to your computer and use it in GitHub Desktop.
Safe message sending script in Telegram with just 49 lines of code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More about this: 💌 Safe message sending script in Telegram with just 49 lines of code? Really?