Building a Telegram Bot for File Sharing and Song Search with Vercel Deployment

Sh Raj - Jul 20 '23 - - Dev Community

Title: Building a Telegram Bot for File Sharing and Song Search

Example Bot :- https://telegram.me/saavnmp3_bot

Introduction

Telegram bots provide an excellent way to engage with users and offer various interactive functionalities. In this article, we have explored the process of building a Telegram bot that allows users to share files and search for songs using the saavn.me API. Leveraging Node.js, node-telegram-bot-api, axios, and express, we created an intuitive bot that seamlessly integrates with Telegram. To further enhance its performance and responsiveness, we deployed the bot using Vercel's serverless deployment platform.

Getting Started

To get started, let's set up our Telegram bot using the node-telegram-bot-api library. First, make sure you have Node.js and npm installed on your machine. Then, create a new directory for your project and initialize it with npm:

mkdir telegram-bot-project
cd telegram-bot-project
npm init -y
Enter fullscreen mode Exit fullscreen mode

Next, install the required libraries:

npm install node-telegram-bot-api axios express
Enter fullscreen mode Exit fullscreen mode

Now, let's create our bot.js file and add the following code to set up our Telegram bot:

const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
const fs = require('fs');
const express = require('express');

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

// Create a new instance of the Telegram bot
const bot = new TelegramBot(botToken, { polling: true });

// ... (continue with the rest of the code)
Enter fullscreen mode Exit fullscreen mode
  1. File Sharing Functionality

The first part of our Telegram bot allows users to share file URLs. When a user sends a message containing one or more URLs, the bot will process each URL and download the files from the provided URLs using axios. We will then save the files temporarily and send them back to the user as Telegram files using the sendDocument method. Here's the code for the file sharing functionality:

// Message handler for handling file URLs
bot.onText(/^(?!\/start)(.*)/, (msg, match) => {
  const chatId = msg.chat.id;
  const urls = match[0].split(/\s+/);

  if (!urls || urls.length === 0) {
    bot.sendMessage(chatId, "Please provide at least one URL.");
    return;
  }

  urls.forEach((url) => {
    downloadFile(url)
      .then((fileData) => {
        if (fileData) {
          const fileName = getFileNameFromURL(url);
          bot.sendDocument(chatId, fileData, {}, { filename: fileName });
        } else {
          bot.sendMessage(chatId, `Failed to download file from ${url}`);
        }
      })
      .catch((error) => {
        bot.sendMessage(chatId, `Failed to download file from ${url}: ${error.message}`);
      });
  });
});

async function downloadFile(url) {
  try {
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    return Buffer.from(response.data);
  } catch (error) {
    throw new Error(`Failed to download file from ${url}: ${error.message}`);
  }
}

function getFileNameFromURL(url) {
  const fileName = url.split('/').pop();
  return fileName;
}
Enter fullscreen mode Exit fullscreen mode
  1. Song Search Functionality

The second part of our Telegram bot enables users to search for songs. When a user sends a song name as a message, the bot will process the query and query a song search API using axios to retrieve relevant song data. The bot will then filter the results and send back song details such as song name, album, year, duration, artists, lyrics availability, and download links. Here's the code for the song search functionality:

async function searchSong(query) {
  const apiUrl = `https://saavn.me/search/songs?limit=5&query=${encodeURIComponent(query)}`;
  try {
    const response = await axios.get(apiUrl);
    const data = response.data;
    if (data.status === 'SUCCESS' && data.data && data.data.results.length > 0) {
      const results = data.data.results;
      return results.map((result) => {
        return {
          Song: result.name,
          Album: result.album.name,
          Year: result.year,
          Duration: convertDuration(result.duration),
          Artists: result.primaryArtists,
          Lyrics: result.hasLyrics === 'true' ? 'Available' : 'Not Available',
          DownloadLinks: result.downloadUrl.map((download) => ({
            Quality: download.quality,
            Link: download.link,
          })),
        };
      });
    } else {
      return 'No results found.';
    }
  } catch (error) {
    console.error('Error fetching data:', error.message);
    return 'An error occurred while fetching data.';
  }
}

function convertDuration(durationInSeconds) {
  const minutes = Math.floor(durationInSeconds / 60);
  const seconds = durationInSeconds % 60;
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}

// Event listener for incoming messages
bot.on('message', async (msg) => {
  const chatId = msg.chat.id;
  const messageText = msg.text.toLowerCase();

  // Check if the message contains the word "hi" and respond accordingly
  if (messageText.includes('hi')) {
    bot.sendMessage(chatId, 'Hi there! How can I assist you?');
    return;
  }

  // Check if the message is the /start command
  if (messageText === '/start') {
    const welcomeMessage = `
Welcome to the Telegram bot!

Send me the name of a song to get details about it.
For example, send "Baarish Lete Aana" to get details about the song "Baarish Lete Aana".
`;
    bot.sendMessage(chatId, welcomeMessage);
    return;
  }

  // Check if the message contains a query and perform the song search
  const query = messageText.trim();
  try {
    const results = await searchSong(query);
    if (Array.isArray(results) && results.length > 0) {
      results.forEach((result) => {
        const responseText = `
Song Details:
Song: ${result.Song}
Album: ${result.Album}
Year: ${result.Year}
Duration: ${result.Duration}
Artists: ${result.Artists}
Lyrics: ${result.Lyrics}
Download Links: ${result.DownloadLinks.map(
          (download) => `\n${download.Quality}: ${download.Link}`
        )}
        `;

        bot.sendMessage(chatId, responseText);
      });
    } else {
      bot.sendMessage(chatId, 'No results found.');
    }
  } catch (error) {
    console.error('Error searching for songs:', error.message);
    bot.sendMessage(chatId, 'An error occurred while searching for songs.');
  }
});
Enter fullscreen mode Exit fullscreen mode
  1. Webhook Integration

To enhance bot performance and responsiveness, let's set up a webhook using express. The webhook will allow Telegram to send updates directly to our deployed website URL on Vercel, avoiding the need for constant polling. Here's the code for webhook integration:

// Create an Express app to handle webhook requests from Telegram
const app = express();

// This endpoint will receive updates from Telegram
app.post(`/bot${botToken}`, (req, res

) => {
  bot.processUpdate(req.body);
  res.sendStatus(200);
});

// Start the Express app on a specified port
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Telegram File Sharing Bot is running on port ${PORT}`);
});

// Register the webhook with Telegram (run this once)
const webhookUrl = 'YOUR_VERCEL_DEPLOYED_WEBSITE_URL/bot' + botToken;
bot.setWebHook(webhookUrl).then(() => {
  console.log(`Webhook set to: ${webhookUrl}`);
}).catch((error) => {
  console.error('Error setting webhook:', error.message);
});
Enter fullscreen mode Exit fullscreen mode

Step 7: Deploying the Bot to Vercel

Vercel is a popular platform that allows us to deploy serverless applications with ease. To deploy our Telegram bot, follow these steps:

  1. Install the Vercel CLI globally (if not already installed):
npm install -g vercel
Enter fullscreen mode Exit fullscreen mode
  1. Deploy the bot to Vercel using the following command:
vercel
Enter fullscreen mode Exit fullscreen mode

Follow the prompts and choose your Vercel account. Vercel will build and deploy your bot, providing you with a unique URL where your bot will be accessible.

Step 8: Setting Up Telegram Webhook

After deploying to Vercel, obtain the URL of your deployed bot from the Vercel dashboard (e.g., https://your-bot-name.vercel.app). Now, set the Telegram webhook to point to your deployed bot URL using the following command (replace YOUR_BOT_TOKEN and YOUR_DEPLOYED_BOT_URL with your actual bot token and deployed bot URL):

curl -F "url=https://YOUR_DEPLOYED_BOT_URL/botYOUR_BOT_TOKEN" https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we successfully built and deployed a Telegram bot that empowers users to share files and explore songs effortlessly. By leveraging Node.js and popular libraries, we crafted a dynamic bot capable of interacting with users in real-time. The saavn.me API enriched the bot with a powerful song search functionality, making it even more engaging.

Deploying the bot to Vercel brought several advantages. With Vercel's serverless deployment, the bot enjoys improved performance, scalability, and reduced operational overhead. Moreover, the seamless integration with Telegram allows users to access the bot from anywhere, anytime.

The possibilities of Telegram bot development are endless. With the knowledge gained from building this bot, you can explore further customizations, add new features, and cater to your users' preferences. So go ahead and create your personalized Telegram bot to revolutionize your user interactions and elevate their experience! Happy bot building and deploying!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .