YJK

独立世界

Independent World
twitter
telegram

簡単なShlinkテレグラムボット

shlink の構築方法は、https://dlsj.im.sb/self-hosted-url-shortener を参照してください。

この shlink TG ボットは、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でボットを作成してください
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;

  // ユーザーが送信したメッセージが長いURLかどうかを判断します
  if (isValidUrl(messageText)) {
    const url = new URL(messageText);
    if (url.hostname === 'mayi.ee') {
      bot.sendMessage(chatId, messageText);
    } else {
      try {
        // POSTリクエストを送信して短縮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, '短縮URLの作成に失敗しました。後でもう一度お試しください。');
      }
    }
  }

  // ユーザーが送信したメッセージが短いドメインかどうかを判断します
  if (isValidShortUrl(messageText)) {
    const shortCode = getShortCode(messageText);
    try {
      // DELETEリクエストを送信して短縮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, '短縮URLの削除に成功しました。');
      } else {
        bot.sendMessage(chatId, '短縮URLの削除に失敗しました。後でもう一度お試しください。');
      }
    } catch (error) {
      console.error(error);
      bot.sendMessage(chatId, '短縮URLの削除に失敗しました。後でもう一度お試しください。');
    }
  }
});

// 文字列が有効な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);
}

// 文字列が有効な短縮URLかどうかを判断します
function isValidShortUrl(str) {
  const pattern = new RegExp('^https:\\/\\/mayi\\.ee\\/[a-zA-Z0-9]+$');
  return pattern.test(str);
}

// 短縮URLからショートコードを取得します
function getShortCode(shortUrl) {
  return shortUrl.replace('https://mayi.ee/', '');
}

node indexを実行してエラーがないことを確認した後、バックグラウンドで実行します。

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

使用方法#

ボットに任意の長い URL を送信すると自動的に短縮され、ボットに短縮 URL を送信するとその短縮 URL が削除されます。

image

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。