本机器人放于cloudflare worker,完全不需要服务器!大善人又立功了
下面会教你怎么搭建,你也可以用我搭建好的机器人,这个机器人会一直存在
预览
下面是搭建教程
第一步
访问https://t.me/BotFather ,创建bot并记下bot-token
第二步
在cloudflare上创建一个worker,输入下面的代码
替换your-telegram-bot-token为上一步的bot-token
替换your-auth-token为随机字符串,也可以直接在16图床上点击那个齿轮后获取
// Created by rocket, the author of 111666.best
// Original link: https://www.nodeseek.com/post-170862-1
const TELEGRAM_BOT_TOKEN = 'your-telegram-bot-token'; // 替换为你的 Telegram bot token
const AUTH_TOKEN = 'your-auth-token'; // 替换为你的 Auth-Token,随机字符串,可以脸滚键盘
const TELEGRAM_API_URL = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}`;
const IMAGE_UPLOAD_URL = 'https://i.111666.best/image';
export default {
async fetch(request) {
const url = new URL(request.url);
// 设置 Webhook 的 API 路径
if (url.pathname === '/setWebhook') {
const webhookUrl = `${url.protocol}//${url.host}/webhook`; // 自动获取 Webhook URL,指向自身
const webhookResponse = await setWebhook(webhookUrl);
if (webhookResponse.ok) {
return new Response(`Webhook set successfully to ${webhookUrl}`, { status: 200 });
} else {
console.error(JSON.stringify(webhookResponse))
return new Response('Failed to set webhook', { status: 500 });
}
}
// 处理 Telegram 消息的部分
if (url.pathname === '/webhook') {
if (request.method === 'POST') {
try {
const update = await request.json(); // 获取 Telegram 发来的更新
if (update.message) {
const chatId = update.message.chat.id;
// 如果收到文本消息,提示用户发送图片
if (update.message.text) {
await sendMessage(chatId, '请发给我一张图片');
return new Response('Asked for image', { status: 200 });
}
// 如果收到的是图片消息
if (update.message.photo) {
await sendMessage(chatId, '图片收到,正在上传中...');
// 获取照片文件的 file_id
const photoArray = update.message.photo;
const fileId = photoArray[photoArray.length - 1].file_id; // 获取最大的分辨率的图片
// 调用 Telegram API 获取文件的 URL
const fileUrl = await getFileUrl(fileId);
// 上传图片
const uploadResponse = await uploadImage(fileUrl);
// 根据上传结果回复用户
if (uploadResponse.ok) {
const imageUrl = `https://i.111666.best${uploadResponse.src}`;
// 发送带有图片链接的消息
await sendImageMessage(chatId, imageUrl);
return new Response('Image processed and uploaded', { status: 200 });
} else {
await sendMessage(chatId, '图片上传失败,请稍后再试。');
}
return new Response('Image processed', { status: 200 });
}
}
return new Response('No message found', { status: 400 });
} catch (err) {
return new Response('Error processing request', { status: 500 });
}
} else {
return new Response('Only POST requests are accepted', { status: 405 });
}
}
return new Response('Not found', { status: 404 });
}
};
// 发送普通消息到 Telegram API
async function sendMessage(chatId, text) {
const url = `${TELEGRAM_API_URL}/sendMessage`;
const body = JSON.stringify({
chat_id: chatId,
text: text
});
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body
});
}
// 发送带图片链接和文本的消息到 Telegram
async function sendImageMessage(chatId, imageUrl) {
const markdownLink = ``;
const bbcodeLink = `[img]${imageUrl}[/img]`;
const messageText = `<b>Direct Link</b>
<pre>${imageUrl}</pre>
<b>Markdown</b> <pre>${markdownLink}</pre>
<b>BBCode</b> <pre>${bbcodeLink}</pre>
`;
const url = `${TELEGRAM_API_URL}/sendPhoto`;
const body = new FormData();
body.append('chat_id', chatId);
body.append('photo', imageUrl); // 直接发送图片 URL
body.append('caption', messageText); // 图片描述带有链接的各种格式
body.append('parse_mode', 'HTML'); // 设置 parse_mode 为 HTML,使链接可点击
await fetch(url, {
method: 'POST',
body
});
}
// 获取 Telegram 文件的下载 URL
async function getFileUrl(fileId) {
const fileUrlResponse = await fetch(`${TELEGRAM_API_URL}/getFile?file_id=${fileId}`);
const fileUrlData = await fileUrlResponse.json();
const filePath = fileUrlData.result.file_path;
return `https://api.telegram.org/file/bot${TELEGRAM_BOT_TOKEN}/${filePath}`;
}
// 上传图片到指定服务器
async function uploadImage(imageUrl) {
const imageResponse = await fetch(imageUrl);
const imageData = await imageResponse.blob(); // 获取图片的二进制数据
const formData = new FormData();
formData.append('image', imageData, 'image.jpg');
const uploadResponse = await fetch(IMAGE_UPLOAD_URL, {
method: 'POST',
headers: {
'Auth-Token': AUTH_TOKEN // 使用 'Auth-Token' 而非 'Authorization'
},
body: formData
});
const uploadResult = await uploadResponse.json();
// 返回包含 ok 和 src 的响应
if (uploadResponse.ok && uploadResult.ok) {
return {
ok: true,
src: uploadResult.src // 获取返回的 src,用于拼接最终图片链接
};
} else {
return { ok: false };
}
}
// 设置 Telegram Webhook
async function setWebhook(webhookUrl) {
const url = `${TELEGRAM_API_URL}/setWebhook`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: webhookUrl
})
});
return response.json();
}
第三步
访问 https://你的worker域名/setWebhook
到此结束,恭喜你获得一个无敌稳定的机器人,又白嫖到了
扩展
本机器人代码接入的后端是16图床,你也可以稍作改动接入其他图床,比如cloudflare r2/简单图床等等
欢迎魔改,但必须保留文件开头的注释!