Skip to content

Instantly share code, notes, and snippets.

@max-lt
Created December 22, 2021 14:32
Show Gist options
  • Save max-lt/8ef16a4dd93780a0eee81e62e07c8cee to your computer and use it in GitHub Desktop.
Save max-lt/8ef16a4dd93780a0eee81e62e07c8cee to your computer and use it in GitHub Desktop.
Basic telegram bot
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
})
function sendMessage(chat_id, text) {
return fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id,
text
})
});
}
async function getMembers() {
const members = await kv.get('telegram-chat-members');
return new Set(members?.split(','));
}
async function saveMembers(members) {
await kv.put('telegram-chat-members', String([...members]));
return members;
}
// https://core.telegram.org/bots/api#getting-updates
// https://core.telegram.org/bots/api#update
// https://core.telegram.org/bots/api#message
// https://core.telegram.org/bots/api#messageentity
async function handleUpdate(update) {
if (update.message) {
const members = await getMembers();
const message = update.message;
const from = message.from;
// We do nothing with other bots here
if (from.is_bot) {
return new Response(null, { status: 204 });
}
else if (/^\/start$/.test(message.text)) {
if (members.has(String(from.id))) {
await sendMessage(message.chat.id, `Bonjour ${from.first_name}, content de te revoir !`);
} else {
await saveMembers(members.add(from.id));
await sendMessage(message.chat.id, `Bienvenue ${from.first_name}`);
}
}
else if (/^\/ping$/.test(message.text)) {
await sendMessage(message.chat.id, 'pong');
}
else if (/(bonjour|salut|hello|yo)/i.test(message.text)) {
await sendMessage(message.chat.id, `Bonjour ${from.first_name} 😊`);
}
else if (/(btc|bitcoin)/i.test(message.text)) {
const res = await fetch('https://api.kraken.com/0/public/Ticker?pair=BTCEUR');
const json = await res.json();
const price = parseInt(json.result.XXBTZEUR.a[0]);
await sendMessage(message.chat.id, `Le Bitcoin s'échange actuellement à ${price}€`);
}
}
return new Response(null, { status: 204 });
}
/**
* Many more examples available at:
* https://developers.cloudflare.com/workers/examples
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const { pathname } = new URL(request.url);
if (request.method == 'POST' && pathname.startsWith("/api/hook")) {
const token = pathname.slice(10);
// https://core.telegram.org/bots/api#setwebhook
// https://core.telegram.org/bots/api#deletewebhook
if (token != BOT_HOOK_SECRET) {
return new Response("Invalid token", { status: 401 });
}
return request.json().then((update) => handleUpdate(update));
}
return new Response(null, { status: 204 });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment