求大佬搭建个Telegram私聊机器人

image
类似于这样。
然后私聊后会提示
“消息已送达”,然后会自动删除
那位大佬懂得。

29 Likes

太久没玩了,都忘了,有没有大佬懂得。

1 Like

有没有大佬懂得。

用gpt整了一个,感觉很拉。

可以尝试一下这个项目:pmcenter

有没有cloudflare的worker的项目。

这个功能 不难呀

求带,大佬。主要想用cf的worker。

这个自动删除是什么意思,阅后即焚?

转发很简单, sendMessage(DESTINATION_USER_ID, ctx.message.text)
删除可以这样写

bot.on('message_read', async (ctx) => {
        // Check if the read message is for the destination user
        if (ctx.chat.id.toString() === DESTINATION_USER_ID) {
          try {
            // Delete the last message from the source user
            await ctx.telegram.deleteMessage(
              SOURCE_USER_ID, 
              ctx.message.message_id
            );
          } catch (deleteError) {
            console.error('Error deleting message:', deleteError);
          }
        }
      });

然后正常配置webhook就行

1 Like

gpt写个轮询很简单的是 ,其实很多时候不是写的不好,是你没有调教好gpt

Modular bot可以,还有很多其他功能,不需要服务器 Telegram: Contact @ModularBot

有没有详细的教程

在 Telegram 中创建聊天机器人

  1. 登录 Telegram 并转到 Telegram: Contact @botfather
  2. 点击网页界面中的 Start 按钮或输入 /start
  3. 点击或输入 /newbot 并输入名称
  4. 为聊天机器人输入一个用户名,该名称应以“bot”结尾(例如 garthsweatherbot)
  5. 复制生成的访问令牌

不是,这个都懂,命令行的。

如果你会写CloudFlare Worker,我提供的这部分代码其实已经实现了主要功能,
如果你不太会写代码,可以交给 Claude 3.5 Sonnet,让它帮你实现这个功能,你可以参考我的prompt:

Write a Cloudflare Worker that acts as a Telegram bot.
    The bot should forward messages from one user to another.
    Once the message has been successfully delivered to the second user and they have read it, the bot should delete the message.

有很多成熟的方案啊,我现在在用modularbot,总体还行

可以看看Nonebot2,有类似功能的插件

我整了一个,变量啥的配置好,但还是不行。

// Telegram Message Forwarding Bot with Confirmation

// Configuration - REPLACE WITH YOUR ACTUAL VALUES
const BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN';
const FORWARD_TO_CHAT_ID = 'TARGET_USER_CHAT_ID';

// Telegram Bot API Base URL
const TELEGRAM_API_BASE = `https://api.telegram.org/bot${BOT_TOKEN}`;

addEventListener('fetch', event => {
  event.respondWith(handleWebhook(event.request));
});

async function handleWebhook(request) {
  // Only accept POST requests
  if (request.method !== 'POST') {
    return new Response('Method Not Allowed', { status: 405 });
  }

  try {
    // Parse incoming webhook payload
    const update = await request.json();

    // Handle different types of webhook events
    if (update.message) {
      // Forward the original message
      const forwardResult = await forwardMessage(update.message);
      
      return new Response('OK', { status: 200 });
    }

    // Handle callback queries (for forward_success)
    if (update.callback_query) {
      const callbackQuery = update.callback_query;
      
      // Check if the callback data is 'forward_success'
      if (callbackQuery.data === 'forward_success') {
        // Confirm forward success and delete original message
        await handleForwardSuccess(callbackQuery);
      }

      return new Response('Processed', { status: 200 });
    }

    return new Response('Processed', { status: 200 });
  } catch (error) {
    console.error('Webhook processing error:', error);
    return new Response('Error', { status: 500 });
  }
}

async function forwardMessage(message) {
  // Prepare forwarded message payload
  const forwardPayload = prepareMessagePayload(message);

  // Add inline keyboard for forward confirmation
  forwardPayload.reply_markup = {
    inline_keyboard: [[
      {
        text: "Forward Success ✅",
        callback_data: "forward_success"
      }
    ]]
  };

  // Send the message to the target chat
  const forwardUrl = `${TELEGRAM_API_BASE}/sendMessage`;
  const response = await fetch(forwardUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(forwardPayload)
  });

  // Handle special message types
  if (!response.ok) {
    console.error('Failed to forward message', await response.text());
    return false;
  }

  // Additional media forwarding for different types
  if (message.photo) {
    await forwardPhoto(message);
  }
  if (message.document) {
    await forwardDocument(message);
  }
  if (message.audio) {
    await forwardAudio(message);
  }
  if (message.video) {
    await forwardVideo(message);
  }

  return true;
}

async function handleForwardSuccess(callbackQuery) {
  // Send confirmation message
  const confirmUrl = `${TELEGRAM_API_BASE}/sendMessage`;
  await fetch(confirmUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      chat_id: FORWARD_TO_CHAT_ID,
      text: "forward_success"
    })
  });

  // Delete the original message
  await deleteOriginalMessage(callbackQuery.message);

  // Answer the callback query
  const answerCallbackUrl = `${TELEGRAM_API_BASE}/answerCallbackQuery`;
  await fetch(answerCallbackUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      callback_query_id: callbackQuery.id,
      text: "Message forwarded successfully!"
    })
  });
}

async function deleteOriginalMessage(message) {
  const deleteUrl = `${TELEGRAM_API_BASE}/deleteMessage`;
  
  await fetch(deleteUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      chat_id: message.chat.id,
      message_id: message.message_id
    })
  });
}

function prepareMessagePayload(message) {
  const payload = {
    chat_id: FORWARD_TO_CHAT_ID
  };

  // Handle text messages
  if (message.text) {
    payload.text = message.text;
  }

  // Add sender information
  if (message.from) {
    payload.text += `\n\n—— From: ${message.from.first_name || 'Unknown'} (@${message.from.username || 'N/A'})`;
  }

  return payload;
}

// Additional media forwarding functions (similar to previous implementation)
async function forwardPhoto(message) {
  const photoUrl = `${TELEGRAM_API_BASE}/sendPhoto`;
  
  const largestPhoto = message.photo[message.photo.length - 1];
  
  const photoPayload = {
    chat_id: FORWARD_TO_CHAT_ID,
    photo: largestPhoto.file_id,
    caption: message.caption || ''
  };

  await fetch(photoUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(photoPayload)
  });
}

async function forwardDocument(message) {
  const docUrl = `${TELEGRAM_API_BASE}/sendDocument`;
  
  const docPayload = {
    chat_id: FORWARD_TO_CHAT_ID,
    document: message.document.file_id,
    caption: message.caption || message.document.file_name
  };

  await fetch(docUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(docPayload)
  });
}

async function forwardAudio(message) {
  const audioUrl = `${TELEGRAM_API_BASE}/sendAudio`;
  
  const audioPayload = {
    chat_id: FORWARD_TO_CHAT_ID,
    audio: message.audio.file_id,
    caption: message.caption || message.audio.title
  };

  await fetch(audioUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(audioPayload)
  });
}

async function forwardVideo(message) {
  const videoUrl = `${TELEGRAM_API_BASE}/sendVideo`;
  
  const videoPayload = {
    chat_id: FORWARD_TO_CHAT_ID,
    video: message.video.file_id,
    caption: message.caption || ''
  };

  await fetch(videoUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(videoPayload)
  });
}

// Helper function to set webhook (call this once during setup)
async function setWebhook(webhookUrl) {
  const setWebhookUrl = `${TELEGRAM_API_BASE}/setWebhook`;
  
  const response = await fetch(setWebhookUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      url: webhookUrl
    })
  });

  return response.ok;
}

佬,好用吗,发下github呗。