cloudflare worker telegram bot send broadcast message to user
- User
cloudflare worker telegram bot send broadcast message to user
Assistant
cloudflare worker telegram bot send broadcast message to user
Here's how to create a Cloudflare Worker that handles a Telegram bot and sends broadcast messages:
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
if (url.pathname === '/webhook' && request.method === 'POST') {
return handleTelegramWebhook(request, env);
}
if (url.pathname === '/broadcast' && request.method === 'POST') {
return handleBroadcast(request, env);
}
return new Response('Bot is running', { status: 200 });
}
};
// Handle incoming Telegram messages
async function handleTelegramWebhook(request, env) {
try {
const update = await request.json();
if (update.message) {
const chatId = update.message.chat.id;
const text = update.message.text;
// Store user in KV for broadcasting
await env.USERS_KV.put(`user:${chatId}`, JSON.stringify({
chatId,
username: update.message.from.username,
firstName: update.message.from.first_name,
joinedAt: new Date().toISOString()
}));
// Handle /start command
if (text === '/start') {
await sendMessage(env.BOT_TOKEN, chatId, 'Welcome! You\'ll receive broadcast messages.');
}
}
return new Response('OK', { status: 200 });
} catch (error) {
return new Response('Error', { status: 500 });
}
}
// Send broadcast message
async function handleBroadcast(request, env) {
try {
const { message, auth } = await request.json();
// Simple auth check
if (auth !== env.BROADCAST_SECRET) {
return new Response('Unauthorized', { status: 401 });
}
// Get all users from KV
const usersList = await env.USERS_KV.list({ prefix: 'user:' });
const users = [];
for (const key of usersList.keys) {
const userData = await env.USERS_KV.get(key.name);
if (userData) {
users.push(JSON.parse(userData));
}
}
// Send message to all users
const results = await Promise.allSettled(
users.map(user => sendMessage(env.BOT_TOKEN, user.chatId, message))
);
const successful = results.filter(r => r.status === 'fulfilled').length;
const failed = results.filter(r => r.status === 'rejected').length;
return new Response(JSON.stringify({
success: true,
sent: successful,
failed: failed,
total: users.length
}), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
// Send message via Telegram API
async function sendMessage(botToken, chatId, text) {
const response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text: text,
parse_mode: 'HTML'
})
});
if (!response.ok) {
throw new Error(`Telegram API error: ${response.status}`);
}
return response.json();
}
In your Cloudflare Worker settings, add these environment variables:
BOT_TOKEN=your_telegram_bot_token
BROADCAST_SECRET=your_secret_key_for_broadcasts
And bind a KV namespace called USERS_KV to store user data.
Set your Telegram webhook URL:
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
-H "Content-Type: application/json" \
-d '{"url": "https://your-worker.your-subdomain.workers.dev/webhook"}'
Send a POST request to trigger broadcasts:
// Example broadcast request
fetch('https://your-worker.your-subdomain.workers.dev/broadcast', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'Hello everyone! This is a broadcast message.',
auth: 'your_secret_key_for_broadcasts'
})
});
For more advanced functionality, you could add:
User management with categories:
// Store users with categories for targeted broadcasts
await env.USERS_KV.put(`user:${chatId}`, JSON.stringify({
chatId,
username: update.message.from.username,
category: 'general', // or 'premium', 'beta', etc.
subscribed: true,
joinedAt: new Date().toISOString()
}));
Scheduled broadcasts using Cron Triggers:
export default {
async scheduled(event, env, ctx) {
// Send daily/weekly broadcasts
await handleScheduledBroadcast(env);
}
};
This setup gives you a robust foundation for a Telegram broadcast bot running on Cloudflare Workers with automatic scaling and global distribution.