Create & Connect Worker to Bot API

Main Gradient

Cloudflare Workers allow you to run JavaScript code at the edge, closer to users, which makes it possible to deliver faster, more personalized responses. This example demonstrates how to create a Cloudflare Worker that responds to incoming HTTP requests.

Steps to Set Up a Cloudflare Worker

  • In your Cloudflare dashboard, navigate to Workers and Pages.
  • Click on Create and on page click on Create Worker Blue Button.
  • Name your worker whatever you want then
    Deploy it!
  • In next page click on Edit Code Button
  • Remove all previous codes (Hello World) compeletly & Copy/Paste this code there:
addEventListener('fetch', event => {
    event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
    const content = await request.text();
    const update = JSON.parse(content);

    if (update.message) {
        const chatId = update.message.chat.id;
        const messageText = update.message.text;

        if (messageText === '/start' || messageText === 'Start') {

            const token = createJWT({
                userId: chatId,
                username: update.message.from.username,
                firstName: update.message.from.first_name,
                lastName: update.message.from.last_name
            });

            const appurl = `https://app.crownwp.site/?webapp`;
            const response = await sendMessage(chatId, 'Click Here to Begin Game', [
                {
                    text: 'Start Game Name',
                    web_app: { url: appurl }
                }
            ]);
            console.log({ Response: response });
        }
    } else {
        console.log("Invalid Response");
    }

    return new Response('OK', { status: 200 });
}

function base64UrlEncode(str) {
    return btoa(String.fromCharCode(...new Uint8Array(str)))
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');
}

function createJWT(payload) {
    const header = {
        alg: 'HS256',
        typ: 'JWT'
    };

    const key = 'YOUR_SECRET_KEY'; 
    const encodedHeader = base64UrlEncode(new TextEncoder().encode(JSON.stringify(header)));
    const encodedPayload = base64UrlEncode(new TextEncoder().encode(JSON.stringify(payload)));

    const signature = base64UrlEncode(
        new Uint8Array(
            crypto.subtle.digest('SHA-256', new TextEncoder().encode(encodedHeader + '.' + encodedPayload + key))
        )
    );

    return `${encodedHeader}.${encodedPayload}.${signature}`;
}


async function sendMessage(chatId, text, buttons) {
    const token = '7765886075:AAGYy8pP_BLNHCELPTxIAwZNWF74a';
    const apiUrl = `https://api.telegram.org/bot${token}/sendMessage`;

    const keyboard = {
        inline_keyboard: buttons.map(button => [
            { text: button.text, web_app: button.web_app }
        ])
    };

    const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            chat_id: chatId,
            text: text,
            reply_markup: keyboard
        })
    });

    return await response.json();
}

You have to change the Red sections with your own data:

Change
https://app.crownwp.site/?webapp
to
https://yourdomain.name/?webapp
Don’t forget to to use ‘?webapp‘ in the end of URL.

and Change
7765886075:AAGYy8pP_BLNHCELPTxIAwZNWF74a
to your Own Telegram API Bot from Botfather.

Then Deploy it again (from side right button) to Save and make changes.

Final Step: Setting Up the Webhook in Telegram

Get & use the URL of your Cloudflare Worker as the webhook URL for your Telegram bot, e.g.,
https://your-worker-name.workers.dev

Set the Webhook with Telegram

You can set up the webhook using Telegram’s API. Replace with the URL of your Worker. And replace your Telegram API instead in this link:

curl -X POST "https://api.telegram.org/bot/setWebhook?url="

Run CURL

Go to Reqbin Website and paste your complete curl code and click to Run. Then if the status is 200 your Cloudflare Worker is now integrated with Telegram! It listens for incoming messages from your bot, allowing you to process commands and respond dynamically.