or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdapplication-framework.mdbot-api.mdfiles.mdfilters.mdhandlers.mdindex.mdkeyboards.mdtelegram-types.md

files.mddocs/

0

# File Operations

1

2

Complete file handling system supporting uploads, downloads, and media processing for all Telegram file types including photos, videos, documents, audio, stickers, and voice messages.

3

4

## Capabilities

5

6

### Input Files

7

8

Upload files to Telegram from various sources.

9

10

```python { .api }

11

class InputFile:

12

def __init__(

13

self,

14

obj: BinaryIO | bytes | str,

15

filename: str = None,

16

attach: bool = None

17

): ...

18

19

def __enter__(self) -> 'InputFile': ...

20

def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...

21

22

@property

23

def field_tuple(self) -> tuple: ...

24

```

25

26

Usage examples:

27

28

```python

29

from telegram import InputFile

30

31

# From file path

32

photo = InputFile("/path/to/photo.jpg")

33

await bot.send_photo(chat_id, photo)

34

35

# From bytes

36

with open("/path/to/document.pdf", "rb") as f:

37

document_bytes = f.read()

38

39

document = InputFile(document_bytes, filename="document.pdf")

40

await bot.send_document(chat_id, document)

41

42

# From file-like object

43

import io

44

45

buffer = io.BytesIO()

46

# ... write data to buffer

47

buffer.seek(0)

48

49

file_obj = InputFile(buffer, filename="generated.txt")

50

await bot.send_document(chat_id, file_obj)

51

52

# From URL (string)

53

await bot.send_photo(chat_id, "https://example.com/photo.jpg")

54

55

# From file_id (string)

56

await bot.send_photo(chat_id, "AgACAgIAAxkDAAIC...")

57

```

58

59

### File Downloads

60

61

Download files from Telegram servers.

62

63

```python { .api }

64

class File:

65

file_id: str

66

file_unique_id: str

67

file_size: int | None

68

file_path: str | None

69

70

async def download_to_drive(

71

self,

72

custom_path: str = None,

73

block: bool = True

74

) -> str: ...

75

76

async def download_as_bytearray(self, block: bool = True) -> bytearray: ...

77

async def download_to_memory(self, out: BinaryIO = None, block: bool = True) -> BinaryIO: ...

78

```

79

80

Usage examples:

81

82

```python

83

# Get file object from message

84

if update.message.photo:

85

# Get largest photo size

86

photo = update.message.photo[-1]

87

file = await bot.get_file(photo.file_id)

88

89

# Download to specific path

90

file_path = await file.download_to_drive("downloads/photo.jpg")

91

print(f"Downloaded to: {file_path}")

92

93

# Download to default path (uses file_id as filename)

94

file_path = await file.download_to_drive()

95

96

# Download as bytes

97

file_bytes = await file.download_as_bytearray()

98

99

# Download to memory stream

100

import io

101

buffer = io.BytesIO()

102

await file.download_to_memory(buffer)

103

buffer.seek(0)

104

data = buffer.read()

105

106

# Handle document downloads

107

if update.message.document:

108

file = await bot.get_file(update.message.document.file_id)

109

filename = update.message.document.file_name or "unknown"

110

await file.download_to_drive(f"downloads/{filename}")

111

```

112

113

### Media Groups

114

115

Send multiple media files as a grouped message.

116

117

```python { .api }

118

class InputMediaPhoto:

119

def __init__(

120

self,

121

media: str | InputFile,

122

caption: str = None,

123

parse_mode: str = None,

124

caption_entities: list[MessageEntity] = None,

125

show_caption_above_media: bool = None,

126

has_spoiler: bool = None

127

): ...

128

129

class InputMediaVideo:

130

def __init__(

131

self,

132

media: str | InputFile,

133

thumbnail: str | InputFile = None,

134

caption: str = None,

135

parse_mode: str = None,

136

caption_entities: list[MessageEntity] = None,

137

show_caption_above_media: bool = None,

138

width: int = None,

139

height: int = None,

140

duration: int = None,

141

supports_streaming: bool = None,

142

has_spoiler: bool = None

143

): ...

144

145

class InputMediaAnimation:

146

def __init__(

147

self,

148

media: str | InputFile,

149

thumbnail: str | InputFile = None,

150

caption: str = None,

151

parse_mode: str = None,

152

caption_entities: list[MessageEntity] = None,

153

show_caption_above_media: bool = None,

154

width: int = None,

155

height: int = None,

156

duration: int = None,

157

has_spoiler: bool = None

158

): ...

159

160

class InputMediaAudio:

161

def __init__(

162

self,

163

media: str | InputFile,

164

thumbnail: str | InputFile = None,

165

caption: str = None,

166

parse_mode: str = None,

167

caption_entities: list[MessageEntity] = None,

168

duration: int = None,

169

performer: str = None,

170

title: str = None

171

): ...

172

173

class InputMediaDocument:

174

def __init__(

175

self,

176

media: str | InputFile,

177

thumbnail: str | InputFile = None,

178

caption: str = None,

179

parse_mode: str = None,

180

caption_entities: list[MessageEntity] = None,

181

disable_content_type_detection: bool = None

182

): ...

183

```

184

185

Usage example:

186

187

```python

188

from telegram import InputMediaPhoto, InputMediaVideo

189

190

# Send media group

191

media_group = [

192

InputMediaPhoto("photo1.jpg", caption="First photo"),

193

InputMediaPhoto("photo2.jpg", caption="Second photo"),

194

InputMediaVideo("video.mp4", caption="A video")

195

]

196

197

messages = await bot.send_media_group(chat_id, media_group)

198

```

199

200

### Paid Media

201

202

Handle paid media content with star payments.

203

204

```python { .api }

205

class InputPaidMediaPhoto:

206

def __init__(self, media: str | InputFile): ...

207

208

media: str | InputFile

209

210

class InputPaidMediaVideo:

211

def __init__(

212

self,

213

media: str | InputFile,

214

thumbnail: str | InputFile = None,

215

width: int = None,

216

height: int = None,

217

duration: int = None,

218

supports_streaming: bool = None

219

): ...

220

221

media: str | InputFile

222

thumbnail: str | InputFile | None

223

width: int | None

224

height: int | None

225

duration: int | None

226

supports_streaming: bool | None

227

228

class PaidMediaInfo:

229

star_count: int

230

paid_media: list[PaidMedia]

231

232

class PaidMediaPhoto:

233

type: str = "photo"

234

photo: list[PhotoSize]

235

236

class PaidMediaVideo:

237

type: str = "video"

238

video: Video

239

240

class PaidMediaPreview:

241

type: str = "preview"

242

width: int | None

243

height: int | None

244

duration: int | None

245

```

246

247

Usage example:

248

249

```python

250

from telegram import InputPaidMediaPhoto, InputPaidMediaVideo

251

252

# Send paid media

253

paid_media = [

254

InputPaidMediaPhoto("exclusive_photo.jpg"),

255

InputPaidMediaVideo("exclusive_video.mp4")

256

]

257

258

message = await bot.send_paid_media(

259

chat_id=chat_id,

260

star_count=10, # Cost in Telegram Stars

261

media=paid_media,

262

caption="Exclusive content for 10 stars!"

263

)

264

```

265

266

### Stickers

267

268

Handle sticker uploads and sticker set management.

269

270

```python { .api }

271

class InputSticker:

272

def __init__(

273

self,

274

sticker: str | InputFile,

275

format: str,

276

emoji_list: list[str],

277

mask_position: MaskPosition = None,

278

keywords: list[str] = None

279

): ...

280

281

sticker: str | InputFile

282

format: str # "static", "animated", "video"

283

emoji_list: list[str]

284

mask_position: MaskPosition | None

285

keywords: list[str] | None

286

287

class MaskPosition:

288

def __init__(

289

self,

290

point: str,

291

x_shift: float,

292

y_shift: float,

293

scale: float

294

): ...

295

296

point: str # "forehead", "eyes", "mouth", "chin"

297

x_shift: float

298

y_shift: float

299

scale: float

300

301

class Sticker:

302

file_id: str

303

file_unique_id: str

304

type: str # "regular", "mask", "custom_emoji"

305

width: int

306

height: int

307

is_animated: bool

308

is_video: bool

309

thumbnail: PhotoSize | None

310

emoji: str | None

311

set_name: str | None

312

premium_animation: File | None

313

mask_position: MaskPosition | None

314

custom_emoji_id: str | None

315

needs_repainting: bool | None

316

file_size: int | None

317

318

async def get_file(self, **kwargs) -> File: ...

319

320

class StickerSet:

321

name: str

322

title: str

323

sticker_type: str

324

stickers: list[Sticker]

325

thumbnail: PhotoSize | None

326

```

327

328

Usage examples:

329

330

```python

331

# Send existing sticker

332

await bot.send_sticker(chat_id, sticker_file_id)

333

334

# Create new sticker set

335

from telegram import InputSticker, MaskPosition

336

337

stickers = [

338

InputSticker(

339

sticker="sticker1.png",

340

format="static",

341

emoji_list=["πŸ˜€", "πŸ˜ƒ"]

342

),

343

InputSticker(

344

sticker="sticker2.png",

345

format="static",

346

emoji_list=["😎"],

347

keywords=["cool", "sunglasses"]

348

)

349

]

350

351

success = await bot.create_new_sticker_set(

352

user_id=user_id,

353

name="my_sticker_set_by_mybot",

354

title="My Sticker Set",

355

stickers=stickers

356

)

357

358

# Add sticker to existing set

359

new_sticker = InputSticker(

360

sticker="new_sticker.png",

361

format="static",

362

emoji_list=["πŸŽ‰"]

363

)

364

365

await bot.add_sticker_to_set(

366

user_id=user_id,

367

name="my_sticker_set_by_mybot",

368

sticker=new_sticker

369

)

370

371

# Get sticker set

372

sticker_set = await bot.get_sticker_set("my_sticker_set_by_mybot")

373

for sticker in sticker_set.stickers:

374

print(f"Sticker: {sticker.emoji} - {sticker.file_id}")

375

```

376

377

### File Type Detection

378

379

Utilities for working with different file types.

380

381

```python

382

# Check file types in messages

383

async def handle_media(update, context):

384

message = update.message

385

386

if message.photo:

387

# Handle photo

388

photo = message.photo[-1] # Get largest size

389

file = await bot.get_file(photo.file_id)

390

await file.download_to_drive(f"photos/{photo.file_id}.jpg")

391

392

elif message.video:

393

# Handle video

394

video = message.video

395

file = await bot.get_file(video.file_id)

396

filename = f"videos/{video.file_id}.mp4"

397

await file.download_to_drive(filename)

398

399

elif message.document:

400

# Handle document

401

document = message.document

402

file = await bot.get_file(document.file_id)

403

filename = document.file_name or f"document_{document.file_id}"

404

await file.download_to_drive(f"documents/{filename}")

405

406

elif message.audio:

407

# Handle audio

408

audio = message.audio

409

file = await bot.get_file(audio.file_id)

410

filename = f"{audio.performer or 'Unknown'} - {audio.title or 'Untitled'}.mp3"

411

await file.download_to_drive(f"audio/{filename}")

412

413

elif message.voice:

414

# Handle voice message

415

voice = message.voice

416

file = await bot.get_file(voice.file_id)

417

await file.download_to_drive(f"voice/{voice.file_id}.ogg")

418

419

elif message.video_note:

420

# Handle video note (circle video)

421

video_note = message.video_note

422

file = await bot.get_file(video_note.file_id)

423

await file.download_to_drive(f"video_notes/{video_note.file_id}.mp4")

424

425

elif message.sticker:

426

# Handle sticker

427

sticker = message.sticker

428

file = await bot.get_file(sticker.file_id)

429

extension = "tgs" if sticker.is_animated else "webm" if sticker.is_video else "webp"

430

await file.download_to_drive(f"stickers/{sticker.file_id}.{extension}")

431

```

432

433

### File Size and Limits

434

435

Understanding Telegram file limitations.

436

437

```python

438

from telegram.constants import FileSizeLimit

439

440

# File size limits (in bytes)

441

max_photo_size = FileSizeLimit.FILESIZE_UPLOAD # 50 MB for bots

442

max_file_size = FileSizeLimit.FILESIZE_UPLOAD # 50 MB for bots

443

max_thumb_size = FileSizeLimit.FILESIZE_DOWNLOAD # 20 MB for downloads

444

445

# Check file size before upload

446

import os

447

448

def check_file_size(file_path):

449

size = os.path.getsize(file_path)

450

if size > FileSizeLimit.FILESIZE_UPLOAD:

451

raise ValueError(f"File too large: {size} bytes (max: {FileSizeLimit.FILESIZE_UPLOAD})")

452

return size

453

454

# Handle large files

455

async def send_large_file(bot, chat_id, file_path):

456

try:

457

check_file_size(file_path)

458

with open(file_path, 'rb') as f:

459

await bot.send_document(chat_id, InputFile(f))

460

except ValueError as e:

461

await bot.send_message(chat_id, f"Cannot send file: {e}")

462

```

463

464

### Thumbnails

465

466

Generate and use thumbnails for media files.

467

468

```python

469

# Send video with custom thumbnail

470

video_file = InputFile("video.mp4")

471

thumbnail_file = InputFile("thumbnail.jpg")

472

473

await bot.send_video(

474

chat_id=chat_id,

475

video=video_file,

476

thumbnail=thumbnail_file,

477

duration=120,

478

width=1920,

479

height=1080,

480

caption="Video with custom thumbnail"

481

)

482

483

# Send document with thumbnail

484

document_file = InputFile("document.pdf")

485

thumbnail_file = InputFile("doc_preview.jpg")

486

487

await bot.send_document(

488

chat_id=chat_id,

489

document=document_file,

490

thumbnail=thumbnail_file,

491

caption="PDF document with preview"

492

)

493

```

494

495

### File Processing Utilities

496

497

Helper functions for common file operations.

498

499

```python

500

import mimetypes

501

import os

502

from pathlib import Path

503

504

def get_file_info(file_path):

505

"""Get comprehensive file information."""

506

path = Path(file_path)

507

return {

508

'name': path.name,

509

'stem': path.stem,

510

'suffix': path.suffix,

511

'size': path.stat().st_size,

512

'mime_type': mimetypes.guess_type(str(path))[0],

513

'is_image': path.suffix.lower() in ['.jpg', '.jpeg', '.png', '.gif', '.webp'],

514

'is_video': path.suffix.lower() in ['.mp4', '.avi', '.mov', '.mkv'],

515

'is_audio': path.suffix.lower() in ['.mp3', '.wav', '.ogg', '.m4a']

516

}

517

518

async def process_uploaded_file(bot, message):

519

"""Process any type of uploaded file."""

520

file_obj = None

521

file_info = {}

522

523

if message.document:

524

file_obj = message.document

525

file_info = {

526

'type': 'document',

527

'name': file_obj.file_name,

528

'mime_type': file_obj.mime_type,

529

'size': file_obj.file_size

530

}

531

elif message.photo:

532

file_obj = message.photo[-1] # Largest size

533

file_info = {

534

'type': 'photo',

535

'width': file_obj.width,

536

'height': file_obj.height,

537

'size': file_obj.file_size

538

}

539

elif message.video:

540

file_obj = message.video

541

file_info = {

542

'type': 'video',

543

'duration': file_obj.duration,

544

'width': file_obj.width,

545

'height': file_obj.height,

546

'size': file_obj.file_size

547

}

548

# ... handle other types

549

550

if file_obj:

551

# Download file

552

file = await bot.get_file(file_obj.file_id)

553

local_path = await file.download_to_drive()

554

555

# Process file as needed

556

return {

557

'telegram_file': file_obj,

558

'local_path': local_path,

559

'info': file_info

560

}

561

562

return None

563

```

564

565

## Types

566

567

```python { .api }

568

from typing import BinaryIO, Union

569

from pathlib import Path

570

571

FileInput = Union[str, InputFile, BinaryIO, Path]

572

```