Skip to content

Instantly share code, notes, and snippets.

@YukiCoco
Last active July 20, 2024 03:59
Show Gist options
  • Save YukiCoco/3608d1f9542398030e40644127210937 to your computer and use it in GitHub Desktop.
Save YukiCoco/3608d1f9542398030e40644127210937 to your computer and use it in GitHub Desktop.
send notifications via Cloudflare works with simple http request to telegram account.
  1. get account id and bot token via https://t.me/BotFather and https://t.me/getmyid_bot
  2. Fullfill SENDKEY MASTER_ID and TELEGRAM_BOT_TOKEN
  3. Send notifications :
curl https://yourworker.address/your_sendkey_here.send?title=short_title&desp=long_content
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
})
const SENDKEY = 'your_sendkey_here';
const MASTER_ID = 'your_master_id_here';
const TELEGRAM_BOT_TOKEN = 'your_telegram_bot_token_here';
async function handleRequest(request) {
const url = new URL(request.url);
const pathname = url.pathname;
const searchParams = new URLSearchParams(url.search);
if (!pathname.endsWith(`/${SENDKEY}.send`)) {
return new Response('Unauthorized', { status: 401 });
}
const title = searchParams.get('title');
const desp = searchParams.get('desp');
if (!title || !desp) {
return new Response('Missing title or desp', { status: 400 });
}
// Escape special characters for MarkdownV2
const escapeMarkdown = (text) => {
return text.replace(/([*_[\]()~`>#+\-=|{}.!])/g, '\\$1');
}
const escapedTitle = escapeMarkdown(title);
const escapedDesp = escapeMarkdown(desp);
// Use MarkdownV2 to format the title in bold
const message = `*${escapedTitle}*\n\n${escapedDesp}`;
const telegramApiUrl = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
const telegramResponse = await fetch(telegramApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: MASTER_ID,
text: message,
parse_mode: 'MarkdownV2'
})
});
if (telegramResponse.ok) {
return new Response('Message sent successfully', { status: 200 });
} else {
const errorData = await telegramResponse.json();
return new Response(`Failed to send message: ${errorData.description}`, { status: 500 });
}
}
@YukiCoco
Copy link
Author

YukiCoco commented Jul 20, 2024

  1. get account id and bot token via https://t.me/BotFather and https://t.me/getmyid_bot
  2. Fullfill SENDKEY MASTER_ID and TELEGRAM_BOT_TOKEN
  3. Send notifications :
curl https://yourworker.address/your_sendkey_here.send?title=short_title&desp=long_content

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