Tmirror

How to Creating a Telegram Bot Using cloudflare Workers Serverless ?


How to Creating a Telegram Bot Using cloudflare Workers Serverless ?

Here we Explained Creating a Telegram Bot Webhook Cloudflare Workers and Google Public Calendar.

Streamlining Holiday Updates with Cloudflare Workers and Google Calendar Integration.

Building a Telegram bot with Cloudflare Workers and Google Calendar integration offers real-time holiday notifications, customizable alerts, and seamless automation. By fetching and formatting holiday data from the Google Calendar API, the bot provides users with upcoming holiday information upon command, creating a user-friendly and efficient experience. Leveraging Cloudflare Workers’ scalability and reliability, developers can quickly set up this bot and experiment with APIs, making it a powerful tool for delivering timely and valuable holiday updates to users.

In this tutorial, we will show you how to create a Telegram bot webhook using Cloudflare Workers and integrate it with Google Public Calendar. The resulting bot will provide information about upcoming holidays in your country upon receiving the “/holidays” command. Let’s get started!

Prerequisites

Before proceeding, make sure you have the following prerequisites:

  • A Telegram bot token — To obtain one, create a bot on Telegram by chatting with the BotFather https://t.me/botfather.
  • A Google Calendar API key — Visit the Google Developers Console https://console.developers.google.com/, create a project, enable the Google Calendar API, and generate an API key.
  • A public holiday calendar ID from Google Calendar — You can find this ID in the settings of your public holiday calendar.

Cloudflare Worker Setup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Cloudflare Worker example for Google Calendar integration

// Your Google Calendar API base URL
const GOOGLE_CALENDAR_API_BASE_URL = 'https://www.googleapis.com/calendar/v3';

// Replace 'YOUR_GOOGLE_CALENDAR_API_KEY' with your actual Google Calendar API key
const GOOGLE_CALENDAR_API_KEY = 'YOUR_GOOGLE_CALENDAR_API_KEY';

// Replace 'YOUR_CALENDAR_ID' with your actual public holiday calendar ID
const CALENDAR_ID = 'YOUR_CALENDAR_ID';

// Replace 'YOUR_TELEGRAM_BOT_TOKEN' with your actual Telegram bot token
const TELEGRAM_BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN';

// Cloudflare Worker code
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Sends a Telegram response to the specified chat ID with the given message.
 * @param {string} chatId - The chat ID where the message will be sent.
 * @param {string} message - The message to send.
 * @returns {Response} - The response from the Telegram API.
 */
async function sendTelegramResponse(chatId, message) {
  const apiUrl = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
  const params = {
    chat_id: chatId,
    text: message,
  };

  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });

    if (response.ok) {
      return new Response('Message sent successfully!', { status: 200 });
    } else {
      return new Response('Failed to send message.', { status: 500 });
    }
  } catch (error) {
    console.error(error);
    return new Response('Error occurred while sending the message.', { status: 500 });
  }
}

/**
 * Retrieves upcoming holidays from Google Calendar API.
 * @returns {Array} - An array of upcoming holidays with name and date.
 */
async function getUpcomingHolidays() {
  const url = `${GOOGLE_CALENDAR_API_BASE_URL}/calendars/${encodeURIComponent(CALENDAR_ID)}/events?key=${GOOGLE_CALENDAR_API_KEY}&timeMin=${encodeURIComponent(new Date().toISOString())}&maxResults=5&orderBy=startTime&singleEvents=true`;

  try {
    const response = await fetch(url);

    const data = await response.json();
    const events = data.items;
    if (!events || events.length === 0) {
      return [];
    }

    return events.map(event => {
      return {
        name: event.summary,
        date: event.start.date || event.start.dateTime,
      };
    });
  } catch (error) {
    console.error('Error fetching holidays:', error);
    return [];
  }
}

/**
 * Handles incoming requests and responds with the appropriate action.
 * @param {Request} request - The incoming request to handle.
 * @returns {Response} - The response to the request.
 */
async function handleRequest(request) {
  const { method, headers } = request;

  const url = new URL(request.url);

  // Check if the request is a POST request to /webhooks/telegram and has JSON content-type
  if (method === 'POST' && url.pathname == '/webhooks/telegram' && headers.get('content-type') === 'application/json') {
    const data = await request.json();
    const { message } = data;

    if (message && message.text) {
      const command = message.text.trim();

      if (command.startsWith('/holidays')) {
        const holidays = await getUpcomingHolidays();
        const response = formatHolidaysResponse(holidays);

        const chatId = message.chat.id

        await sendTelegramResponse(chatId, response)

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

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

/**
 * Formats the list of upcoming holidays into a readable response for Telegram.
 * @param {Array} holidays - The array of upcoming holidays.
 * @returns {string} - The formatted response for Telegram.
 */
function formatHolidaysResponse(holidays) {
  if (holidays.length === 0) {
    return 'No upcoming holidays found.';
  }

  const formattedHolidays = holidays.map(holiday => `- ${holiday.name} - ${holiday.date}`).join('\n');
  return `Upcoming holidays in your country:\n${formattedHolidays}`;
}

In this code block, replace <YOUR_GOOGLE_CALENDAR_API_KEY> , <YOUR_CALENDAR_ID>, and <YOUR_TELEGRAM_BOT_TOKEN> with your actual Google Calendar API key, public calendar ID, and Telegram bot token respectively.

Code Explanation

  • sendTelegramResponse: This function sends a response message to the specified chat ID using the Telegram API.
  • getUpcomingHolidays: This function retrieves upcoming holidays from the Google Calendar API.
  • formatHolidaysResponse: This function formats the list of upcoming holidays into a readable response for Telegram.
  • handleRequest: This function handles incoming requests and responds with the appropriate action. It listens for POST requests to “/webhooks/telegram” with JSON content-type. When the “/holidays” command is received, it fetches the upcoming holidays, formats the response, and sends it back to the user.

Deploying the Cloudflare Worker

After setting up the Worker and making sure everything works as expected, click the “Save and Deploy” button in the Cloudflare Workers dashboard to deploy the Worker to your Cloudflare domain.

Configuring the Telegram Bot Webhook

To configure the Telegram bot webhook, follow these steps:

  • Open your browser and navigate to the following URL (replace <YOUR_CLOUDFLARE_WORKER_URL> with the URL of your Cloudflare Worker)

https://api.telegram.org/bot <YOUR_TELEGRAM_BOT_TOKEN> /setWebhook?url=<YOUR_CLOUDFLARE_WORKER_URL>/webhooks/telegram

  • If everything is set up correctly, you should receive a response confirming that the webhook has been set.

Using the Telegram Bot

Now that your Telegram bot webhook is up and running, open Telegram and find your bot. Type “/holidays” in the chat, and the bot will fetch and respond with a list of upcoming holidays in your country from the configured Google Public Calendar.

Conclusion

Congratulations! You have successfully set up a Telegram bot webhook using Cloudflare Workers and integrated it with Google Public Calendar. This powerful combination allows you to create dynamic and interactive bots that fetch and deliver information from various APIs. Feel free to explore further and enhance your bot’s capabilities, such as providing weather forecasts, news updates, or any other data of interest to your users. Happy coding and bot-building!

comments powered by Disqus