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 發送短鏈接則刪除該短鏈接。