MCPcopy Create free account
hub / github.com/TeleBoxOrg/TeleBox_Plugins / downloadAndProcessImage

Function downloadAndProcessImage

outdated/gpt/gpt.ts:269–336  ·  view source on GitHub ↗
(
  client: TelegramClient,
  message: Api.Message,
  infoMessage: Api.Message
)

Source from the content-addressed store, hash-verified

267
268// 下载并处理图片
269async function downloadAndProcessImage(
270 client: TelegramClient,
271 message: Api.Message,
272 infoMessage: Api.Message
273): Promise<{ imagePath: string; imageSource: string }> {
274 const tempDir = os.tmpdir();
275 const imageName = `gpt_tmp_${Math.random()
276 .toString(36)
277 .substring(7)}_${Date.now()}.png`;
278 const imagePath = path.join(tempDir, imageName);
279
280 try {
281 // 下载图片
282 await infoMessage.edit({ text: "下载图片..." });
283
284 let mediaMsg = message;
285 const replyMsg = await message.getReplyMessage();
286 if (!message.media && replyMsg?.media) {
287 mediaMsg = replyMsg;
288 }
289
290 if (!mediaMsg.media) {
291 throw new Error("未找到图片");
292 }
293
294 // 尝试下载图片
295 const buffer = await client.downloadMedia(mediaMsg.media, {
296 progressCallback: (received: any, total: any) => {
297 const percent = (Number(received) * 100) / Number(total);
298 infoMessage
299 .edit({
300 text: `下载图片 ${percent.toFixed(1)}%`,
301 })
302 .catch(() => {});
303 },
304 });
305
306 if (!buffer) {
307 throw new Error("图片下载失败");
308 }
309
310 // 保存图片
311 await fs.promises.writeFile(imagePath, buffer as any);
312 await infoMessage.edit({ text: "下载图片 100%" });
313
314 // 检查是否需要上传图片
315 const imageUploadEnabled =
316 ConfigManager.get(CONFIG_KEYS.GPT_IMAGE_UPLOAD).toLowerCase() === "true";
317
318 let imageSource: string;
319 if (imageUploadEnabled) {
320 const imageUrl = await uploadImage(imagePath);
321 imageSource = imageUrl;
322 } else {
323 const imageBuffer = await fs.promises.readFile(imagePath);
324 const base64 = imageBuffer.toString("base64");
325 imageSource = `data:image/png;base64,${base64}`;
326 }

Callers 1

handleGptRequestFunction · 0.70

Calls 4

uploadImageFunction · 0.85
editMethod · 0.45
downloadMediaMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected