downloadMedia

Download media to disk with automatic filename handling.

TypeScript
import { downloadMedia } from 'teleglance';

for await (const message of client.iterMessages('telegram', { limit: 20 })) {
  if (message.media) {
    for (const item of message.media) {
      // Download to directory (auto-generates filename)
      const path = await downloadMedia(item, './downloads');
      console.log(`Saved to ${path}`);

      // With overwrite control
      const path2 = await downloadMedia(item, './downloads', {
        overwrite: false  // Skip if file exists
      });
    }
  }
}

downloadBytes

Download media to memory for processing without saving to disk.

TypeScript
import { downloadBytes } from 'teleglance';

for await (const message of client.iterMessages('photos', { limit: 10 })) {
  if (message.media) {
    for (const photo of message.media) {
      // Download to buffer
      const data = await downloadBytes(photo);

      // With size limit
      const data2 = await downloadBytes(photo, {
        maxBytes: 10_000_000  // 10 MB limit
      });

      // Process in memory
      const sharp = require('sharp');
      await sharp(data)
        .resize(200, 200)
        .toFile('thumbnail.jpg');
    }
  }
}

Media types

Messages can contain photos, videos, stickers, documents, and more.

TypeScript
if (message.media) {
  for (const item of message.media) {
    console.log(`Type: ${item.type}`);        // photo, video, sticker, document, etc.
    console.log(`URL: ${item.url}`);          // Direct download URL
    console.log(`Size: ${item.sizeBytes}`);   // File size (if available)

    // Type-specific fields
    if (item.type === 'photo') {
      console.log(`Dimensions: ${item.width}x${item.height}`);
    } else if (item.type === 'video') {
      console.log(`Duration: ${item.durationSeconds}s`);
    }
  }
}

Error handling

Handle download failures gracefully.

TypeScript
import { RequestFailed } from 'teleglance';

for await (const message of client.iterMessages('channel', { limit: 50 })) {
  if (message.media) {
    for (const item of message.media) {
      try {
        const path = await downloadMedia(item, './downloads');
        console.log(`Downloaded: ${path}`);
      } catch (err) {
        if (err instanceof RequestFailed) {
          console.error(`Failed to download ${item.url}: ${err.message}`);
        } else {
          console.error(`Disk error: ${err}`);
        }
      }
    }
  }
}