Skip to content

Instantly share code, notes, and snippets.

@seguri
Created May 8, 2023 23:58
Show Gist options
  • Save seguri/304388263e807fbff3fd2134d464829e to your computer and use it in GitHub Desktop.
Save seguri/304388263e807fbff3fd2134d464829e to your computer and use it in GitHub Desktop.
Telegram Bot with Cloudflare Workers
/**
* After Save & Deploy, invoke `/register`
* Open Telegram, go to your bot, write something: you should receive it back.
*/
export default {
async fetch(request, env, context) {
const { headers } = request
const { hostname, pathname } = new URL(request.url)
const telegram = 'https://api.telegram.org/bot' + env.TOKEN
const sendText = async (chatId, text) => {
const params = new URLSearchParams({ chat_id: chatId, text })
const r = await fetch(telegram + '/sendMessage?' + params)
return await r.json()
}
const setWebhook = async (url) => {
const r = await fetch(url)
const j = await r.json()
return new Response('ok' in j && j.ok ? 'Ok' : JSON.stringify(j, null, 2))
}
if (pathname === '/update') {
if (env.SECRET_TOKEN !== headers.get('X-Telegram-Bot-Api-Secret-Token')) {
return new Response('Unauthorized', { status: 403 })
}
const requestData = await request.json()
if ('message' in requestData) {
const chatId = requestData.message.chat.id
const text = 'Echo:\n' + requestData.message.text
// Non-blocking; might end after we return the Response
context.waitUntil(sendText(chatId, text))
return new Response('Ok')
} else {
return new Response('Bad Request', { status: 400 })
}
} else if (pathname === '/register') {
const updateUrl = `https://${hostname}/update`
const setWebhookParams = new URLSearchParams({ url: updateUrl, secret_token: env.SECRET_TOKEN })
const setWebhookUrl = telegram + '/setWebhook?' + setWebhookParams
return await setWebhook(setWebhookUrl)
} else if (pathname === '/deregister') {
const unsetWebhookUrl = telegram + '/setWebhook?url='
return await setWebhook(unsetWebhookUrl)
} else {
return new Response('Not Found', { status: 404 })
}
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment