or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication-sessions.mdchat-management.mdclient-management.mderror-handling.mdevent-system.mdfile-handling.mdindex.mdmessage-operations.mdutilities-helpers.md

index.mddocs/

0

# Telethon

1

2

A comprehensive Python 3 asyncio-based MTProto library for interacting with Telegram's API as both user and bot accounts. Telethon provides full access to Telegram's features including message handling, file transfers, user authentication, real-time updates, and complete raw API access, making it ideal for building sophisticated Telegram applications, bots, and automation tools.

3

4

## Package Information

5

6

- **Package Name**: Telethon

7

- **Language**: Python

8

- **Installation**: `pip install Telethon`

9

- **Requirements**: Python 3.5+, asyncio support

10

- **Optional Dependencies**: `cryptg` for performance improvements

11

12

## Core Imports

13

14

```python

15

from telethon import TelegramClient, events, Button

16

```

17

18

For specific components:

19

20

```python

21

from telethon import TelegramClient, events, Button, utils, errors

22

from telethon.tl import types, functions

23

from telethon.sessions import StringSession, SQLiteSession

24

```

25

26

## Basic Usage

27

28

### Client Setup and Authentication

29

30

```python

31

import asyncio

32

from telethon import TelegramClient

33

34

# Replace with your actual values from https://my.telegram.org

35

api_id = 'your_api_id'

36

api_hash = 'your_api_hash'

37

38

async def main():

39

# Create client

40

client = TelegramClient('session_name', api_id, api_hash)

41

42

# Connect and authenticate

43

await client.start()

44

45

# Get current user info

46

me = await client.get_me()

47

print(f"Logged in as {me.first_name}")

48

49

# Send a message

50

await client.send_message('username', 'Hello from Telethon!')

51

52

# Disconnect

53

await client.disconnect()

54

55

# Run the client

56

asyncio.run(main())

57

```

58

59

### Bot Usage

60

61

```python

62

from telethon import TelegramClient, events

63

64

bot = TelegramClient('bot_session', api_id, api_hash)

65

66

@bot.on(events.NewMessage(pattern='/start'))

67

async def start_handler(event):

68

await event.respond('Hello! I am a bot created with Telethon.')

69

70

@bot.on(events.NewMessage)

71

async def echo_handler(event):

72

if not event.text.startswith('/'):

73

await event.respond(f'You said: {event.text}')

74

75

async def main():

76

await bot.start(bot_token='your_bot_token')

77

print("Bot is running...")

78

await bot.run_until_disconnected()

79

80

asyncio.run(main())

81

```

82

83

## Architecture

84

85

Telethon uses a layered architecture built around the MTProto protocol:

86

87

- **TelegramClient**: Main interface combining all functionality through mixin classes

88

- **Session Management**: Persistent storage of authentication and cache data

89

- **Event System**: Real-time update handling with decorators and handlers

90

- **TL Objects**: Type Language objects representing Telegram's data structures

91

- **Network Layer**: Connection management, encryption, and protocol handling

92

- **Utility Layer**: Helper functions for common operations and conversions

93

94

The client uses Python's asyncio for asynchronous operations and supports both high-level convenience methods and low-level raw API access for maximum flexibility.

95

96

## Capabilities

97

98

### Client Management

99

100

Core client functionality including connection management, authentication, session handling, and basic client operations.

101

102

```python { .api }

103

class TelegramClient:

104

def __init__(self, session, api_id: int, api_hash: str, **kwargs): ...

105

async def start(self, phone=None, password=None, *, bot_token=None, **kwargs): ...

106

async def connect(self) -> None: ...

107

async def disconnect(self) -> None: ...

108

def is_connected(self) -> bool: ...

109

```

110

111

[Client Management](./client-management.md)

112

113

### Authentication & Sessions

114

115

User and bot authentication, session management, two-factor authentication, and QR code login functionality.

116

117

```python { .api }

118

async def sign_in(self, phone: str = None, code: Union[str, int] = None, **kwargs): ...

119

async def sign_up(self, code: Union[str, int], first_name: str, last_name: str = '', **kwargs): ...

120

async def send_code_request(self, phone: str, *, force_sms: bool = False): ...

121

async def log_out(self) -> bool: ...

122

async def qr_login(self, ignored_ids: List[int] = None): ...

123

```

124

125

[Authentication & Sessions](./authentication-sessions.md)

126

127

### Message Operations

128

129

Comprehensive message handling including sending, receiving, editing, deleting, forwarding, and reading messages with support for formatting, media, and buttons.

130

131

```python { .api }

132

async def send_message(self, entity, message='', *, reply_to=None, parse_mode=(), **kwargs): ...

133

async def get_messages(self, entity, *args, **kwargs): ...

134

def iter_messages(self, entity, limit: int = 1, **kwargs): ...

135

async def edit_message(self, entity, message=None, text: str = None, **kwargs): ...

136

async def delete_messages(self, entity, message_ids, *, revoke: bool = True): ...

137

async def forward_messages(self, entity, messages, from_peer=None, **kwargs): ...

138

```

139

140

[Message Operations](./message-operations.md)

141

142

### File Handling

143

144

File upload and download operations with progress tracking, including sending media, documents, photos, and handling various file formats.

145

146

```python { .api }

147

async def send_file(self, entity, file, *, caption: str = '', **kwargs): ...

148

async def upload_file(self, file, *, part_size_kb: int = None, **kwargs): ...

149

async def download_media(self, message, file=None, **kwargs) -> str: ...

150

async def download_file(self, input_location, file=None, **kwargs) -> bytes: ...

151

def iter_download(self, file, **kwargs): ...

152

```

153

154

[File Handling](./file-handling.md)

155

156

### Chat Management

157

158

Chat and channel administration including member management, permissions, admin operations, and participant handling.

159

160

```python { .api }

161

def iter_participants(self, entity, limit: int = None, **kwargs): ...

162

async def get_participants(self, *args, **kwargs): ...

163

async def edit_admin(self, entity, user, **kwargs): ...

164

async def edit_permissions(self, entity, user=None, until_date=None, **kwargs): ...

165

async def kick_participant(self, entity, user): ...

166

async def get_permissions(self, entity, user): ...

167

```

168

169

[Chat Management](./chat-management.md)

170

171

### Event System

172

173

Real-time update handling with event decorators, filters, and handlers for messages, edits, deletions, and other Telegram updates.

174

175

```python { .api }

176

def on(self, event): ...

177

def add_event_handler(self, callback, event=None): ...

178

def remove_event_handler(self, callback, event=None) -> int: ...

179

def run_until_disconnected(self): ...

180

181

class NewMessage: ...

182

class MessageEdited: ...

183

class ChatAction: ...

184

class CallbackQuery: ...

185

```

186

187

[Event System](./event-system.md)

188

189

### Utilities & Helpers

190

191

Utility functions for entity resolution, input conversion, media type detection, and common Telegram operations.

192

193

```python { .api }

194

def get_display_name(entity) -> str: ...

195

def get_input_peer(entity, allow_self=True, check_hash=True): ...

196

def get_peer_id(peer) -> int: ...

197

def parse_phone(phone) -> str: ...

198

def parse_username(username) -> str: ...

199

def is_image(file) -> bool: ...

200

def is_video(file) -> bool: ...

201

```

202

203

[Utilities & Helpers](./utilities-helpers.md)

204

205

### Error Handling

206

207

Comprehensive error handling system with specific exception types for different error conditions and RPC errors from Telegram.

208

209

```python { .api }

210

class RPCError(Exception): ...

211

class FloodWaitError(RPCError): ...

212

class SessionPasswordNeededError(RPCError): ...

213

class PhoneCodeInvalidError(RPCError): ...

214

class UsernameNotOccupiedError(RPCError): ...

215

216

def rpc_message_to_error(rpc_error, request): ...

217

```

218

219

[Error Handling](./error-handling.md)

220

221

## Types

222

223

### Core Types

224

225

```python { .api }

226

class TelegramClient:

227

"""Main client class for all Telegram operations"""

228

229

class Session:

230

"""Abstract base class for session storage"""

231

232

class Connection:

233

"""Abstract base class for network connections"""

234

```

235

236

### Event Types

237

238

```python { .api }

239

from typing import Union, List, Optional, Any, Callable

240

from datetime import datetime

241

242

EntityLike = Union[int, str, 'types.User', 'types.Chat', 'types.Channel']

243

MessageLike = Union[int, 'types.Message', 'custom.Message']

244

FileLike = Union[str, bytes, 'types.Document', 'types.Photo', 'io.IOBase']

245

```