YJK

独立世界

Independent World
twitter
telegram

一个简易的 Shlink Telegram bot

shlink 搭建方法可参照 https://dlsj.im.sb/self-hosted-url-shortener

本 shlink TG bot 是由 ChatGPT 3.5 生成的,过程链接如下:

搭建方法#

推荐在海外 VPS 部署。

安装 nodejs & pm2

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

创建一个文件夹,并初始化

mkdir shlinkbot
cd shlinkbot
npm init
# 全部回车即可

安装基础库

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

基于以下代码创建一个 index.js 文件

// 将以下代码中的 mayi.ee 替换为您自己的域名
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');

// 这里替换成自己的 Telegram Bot Token 和 X-Api-Key
// 在 https://t.me/BotFather 新建 bot
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
const apiKey = 'YOUR_API_KEY';

// 创建 Telegram Bot 实例
const bot = new TelegramBot(token, { polling: true });

// 监听用户发送的消息
bot.on('message', async (msg) => {
  const chatId = msg.chat.id;
  const messageText = msg.text;

  // 判断用户发送的消息是否是一个长网址
  if (isValidUrl(messageText)) {
    const url = new URL(messageText);
    if (url.hostname === 'mayi.ee') {
      bot.sendMessage(chatId, messageText);
    } else {
      try {
        // 发送 POST 请求创建短链接
        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, '创建短链接失败,请稍后再试');
      }
    }
  }

  // 判断用户发送的消息是否是一个短域名
  if (isValidShortUrl(messageText)) {
    const shortCode = getShortCode(messageText);
    try {
      // 发送 DELETE 请求删除短链接
      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, '删除短链接成功');
      } else {
        bot.sendMessage(chatId, '删除短链接失败,请稍后再试');
      }
    } catch (error) {
      console.error(error);
      bot.sendMessage(chatId, '删除短链接失败,请稍后再试');
    }
  }
});

// 判断一个字符串是否是一个合法的 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);
}

// 判断一个字符串是否是一个合法的短链接
function isValidShortUrl(str) {
  const pattern = new RegExp('^https:\\/\\/mayi\\.ee\\/[a-zA-Z0-9]+$');
  return pattern.test(str);
}

// 从一个短链接中获取短码
function getShortCode(shortUrl) {
  return shortUrl.replace('https://mayi.ee/', '');
}

先运行一次 node index 无报错后后台运行:

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

使用方法#

向 bot 发送任意长链接自动缩短,向 bot 发送短链接则删除该短链。

image

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。