YJK

独立世界

Independent World
twitter
telegram

A simple Shlink Telegram bot

The method of building shlink can refer to https://dlsj.im.sb/self-hosted-url-shortener

This shlink TG bot is generated by ChatGPT 3.5, and the process link is as follows:

Installation Method#

It is recommended to deploy on an overseas VPS.

Install nodejs & pm2

bash <(curl -L https://raw.githubusercontent.com/tj/n/master/bin/n) lts
npm i -g pm2

Create a folder and initialize it

mkdir shlinkbot
cd shlinkbot
npm init
# Press enter for all prompts

Install the basic libraries

npm i node-telegram-bot-api axios
npm i

Create an index.js file based on the following code

// Replace mayi.ee in the code below with your own domain name
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');

// Replace with your own Telegram Bot Token and X-Api-Key
// Create a bot at https://t.me/BotFather
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
const apiKey = 'YOUR_API_KEY';

// Create a Telegram Bot instance
const bot = new TelegramBot(token, { polling: true });

// Listen for messages sent by users
bot.on('message', async (msg) => {
  const chatId = msg.chat.id;
  const messageText = msg.text;

  // Check if the message sent by the user is a long URL
  if (isValidUrl(messageText)) {
    const url = new URL(messageText);
    if (url.hostname === 'mayi.ee') {
      bot.sendMessage(chatId, messageText);
    } else {
      try {
        // Send a POST request to create a short URL
        const response = await axios.post(
          'https://mayi.ee/rest/v3/short-urls',
          { longUrl: messageText },
          { headers: { 'X-Api-Key': apiKey } }
        );
        const shortUrl = response.data.shortUrl;
        bot.sendMessage(chatId, shortUrl);
      } catch (error) {
        console.error(error);
        bot.sendMessage(chatId, 'Failed to create a short URL. Please try again later.');
      }
    }
  }

  // Check if the message sent by the user is a short URL
  if (isValidShortUrl(messageText)) {
    const shortCode = getShortCode(messageText);
    try {
      // Send a DELETE request to delete the short URL
      const response = await axios.delete(
        `https://mayi.ee/rest/v3/short-urls/${shortCode}`,
        { headers: { 'X-Api-Key': apiKey } }
      );
      if (response.status === 204) {
        bot.sendMessage(chatId, 'Short URL deleted successfully.');
      } else {
        bot.sendMessage(chatId, 'Failed to delete the short URL. Please try again later.');
      }
    } catch (error) {
      console.error(error);
      bot.sendMessage(chatId, 'Failed to delete the short URL. Please try again later.');
    }
  }
});

// Check if a string is a valid URL
function isValidUrl(str) {
  const pattern = new RegExp(
    '^(https?:\\/\\/)?' + // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
      '(\\#[-a-z\\d_]*)?$',
    'i'
  );
  return pattern.test(str);
}

// Check if a string is a valid short URL
function isValidShortUrl(str) {
  const pattern = new RegExp('^https:\\/\\/mayi\\.ee\\/[a-zA-Z0-9]+$');
  return pattern.test(str);
}

// Get the short code from a short URL
function getShortCode(shortUrl) {
  return shortUrl.replace('https://mayi.ee/', '');
}

Run node index once without any errors, then run it in the background:

pm2 start index.js --name shlinkbot
pm2 startup
pm2 save

Usage#

Send any long URL to the bot to shorten it automatically. Send a short URL to the bot to delete it.

image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.