In this Article, I’ll show you how to create a Telegram bot that can help improve the performance of your AdlinkFly script. Telegram bots are a great way to interact with your followers and automate tasks. They’re a great way to add some extra value to your URL shortenng service. We’ll go over everything you need to know, from setting up an account to integrating your Telegram bot with your AdlinkFly script. Lets get started.

How to Get Your Bot Token

To create a new bot, you must first speak with BotFather. No, he’s not a human; he’s a bot who serves as a leader of all Telegram bots.

1. Search for @botfather in Telegram.

2. Start a conversation with BotFather by clicking on the Start button.

3. Type /newbot, and follow the prompts to set up a new bot. The BotFather will give you a token that you will use to authenticate your bot and grant it access to the Telegram API.

How to Set Up Your AdlinkFly Bot

Goto Replit and create an account.
Then create a new Repl. Select Node.js as Template and Give a suitable Title to your Repl.
Now Paste the below Nodejs code to your Repl.
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
const fs = require('fs');

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

const port = 3000;
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

// Retrieve the Telegram bot token from the environment variable
const botToken = process.env.TELEGRAM_BOT_TOKEN;

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

// Handle /start command
bot.onText(//start/, (msg) => {
  const chatId = msg.chat.id;
  const username = msg.from.username;
  const welcomeMessage = `Hello, ${username}!nn`
    + 'Welcome to the URL Shortener Bot!n'
    + 'You can use this bot to shorten URLs using the https://snipn.cc service.nn'
    + 'To shorten a URL, just type or paste the URL directly in the chat, and the bot will provide you with the shortened URL.nn'
    + 'If you haven't set your Snipn API token yet, use the command:n/setarklinks YOUR_SNIPN_API_TOKENnn'
    + 'Now, go ahead and try it out!';

  bot.sendMessage(chatId, welcomeMessage);
});


// Command: /setarklinks
bot.onText(//setarklinks (.+)/, (msg, match) => {
  const chatId = msg.chat.id;
  const userToken = match[1].trim(); // Get the API token provided by the user

  // Save the user's Snipn API token to the database
  saveUserToken(chatId, userToken);

  const response = `SNIPN API token set successfully. Your token: ${userToken}`;
  bot.sendMessage(chatId, response);
});

// Listen for any message (not just commands)
bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  const messageText = msg.text;

  // If the message starts with "http://" or "https://", assume it's a URL and try to shorten it
  if (messageText && (messageText.startsWith('http://') || messageText.startsWith('https://'))) {
    shortenUrlAndSend(chatId, messageText);
  }
});

// Function to shorten the URL and send the result
async function shortenUrlAndSend(chatId, Url) {
  // Retrieve the user's Snipn API token from the database
  const arklinksToken = getUserToken(chatId);

  if (!arklinksToken) {
    bot.sendMessage(chatId, 'Please provide your Snipn API token first. Use the command: /setarklinks YOUR_SNIPN_API_TOKEN');
    return;
  }

  try {
    const apiUrl = `https://snipn.cc/api?api=${arklinksToken}&url=${Url}`;

    // Make a request to the Snipn API to shorten the URL
    const response = await axios.get(apiUrl);
    const shortUrl = response.data.shortenedUrl;


    const responseMessage = `Shortened URL: ${shortUrl}`;
    bot.sendMessage(chatId, responseMessage);
  } catch (error) {
    console.error('Shorten URL Error:', error);
    bot.sendMessage(chatId, 'An error occurred while shortening the URL. Please check your API token and try again.');
  }
}

// Function to validate the URL format
function isValidUrl(url) {
  const urlPattern = /^(|ftp|http|https)://[^ "]+$/;
  return urlPattern.test(url);
}

// Function to save user's Snipn API token to the database (Replit JSON database)
function saveUserToken(chatId, token) {
  const dbData = getDatabaseData();
  dbData[chatId] = token;
  fs.writeFileSync('database.json', JSON.stringify(dbData, null, 2));
}

// Function to retrieve user's Snipn API token from the database
function getUserToken(chatId) {
  const dbData = getDatabaseData();
  return dbData[chatId];
}

// Function to read the database file and parse the JSON data
function getDatabaseData() {
  try {
    return JSON.parse(fs.readFileSync('database.json', 'utf8'));
  } catch (error) {
    // Return an empty object if the file doesn't exist or couldn't be parsed
    return {};
  }
}

Now Create .env for the TELEGRAM_BOT_TOKEN in the secrets tab and paste your Telegram Bot Token you got from BotFather earlier.

Run the Repl and check your Telegram Bot if its working or not?
In my case it is working fine!
Now check whether it is giving correct outputs for the given inputs.

So, everything is working properly but there is a problem that the Repl you have created will stop after an hour!

How to fix this issue

For solving this issue we have a free solution called UpTime Robot. So, create an account for free in uptime robot and follow the process below.
Click “Add New Monitor” and select monitor type as “HTTP(s)”. Then fill the friendly name and the url of your Repl you have created earlier.
Hit “Create Monitor” and the problem is solved.

Uptime Robot will keep hitting your Repl server with an interval of every 1 minute for 30 seconds which helps to keep the Repl Running.