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

client-management.mddocs/

0

# Client Management

1

2

Core client functionality for managing connections, configuration, and basic client operations in Telethon.

3

4

## Capabilities

5

6

### Client Initialization

7

8

Create and configure a TelegramClient instance with various connection and behavior options.

9

10

```python { .api }

11

class TelegramClient:

12

def __init__(

13

self,

14

session: Union[str, pathlib.Path, Session],

15

api_id: int,

16

api_hash: str,

17

*,

18

connection: Type[Connection] = ConnectionTcpFull,

19

use_ipv6: bool = False,

20

proxy: Union[tuple, dict] = None,

21

local_addr: Union[str, tuple] = None,

22

timeout: int = 10,

23

request_retries: int = 5,

24

connection_retries: int = 5,

25

retry_delay: int = 1,

26

auto_reconnect: bool = True,

27

sequential_updates: bool = False,

28

flood_sleep_threshold: int = 60,

29

raise_last_call_error: bool = False,

30

device_model: str = None,

31

system_version: str = None,

32

app_version: str = None,

33

lang_code: str = 'en',

34

system_lang_code: str = 'en',

35

loop: asyncio.AbstractEventLoop = None,

36

base_logger: Union[str, logging.Logger] = None,

37

receive_updates: bool = True,

38

catch_up: bool = False,

39

entity_cache_limit: int = 5000

40

):

41

"""

42

Initialize a new TelegramClient.

43

44

Parameters:

45

- session: Session storage (filename, Session object, or StringSession)

46

- api_id: API ID from https://my.telegram.org

47

- api_hash: API hash from https://my.telegram.org

48

- connection: Connection type to use (default: ConnectionTcpFull)

49

- use_ipv6: Whether to use IPv6 connections

50

- proxy: Proxy configuration (tuple or dict)

51

- local_addr: Local address to bind to

52

- timeout: Request timeout in seconds

53

- request_retries: Number of request retries

54

- connection_retries: Number of connection retries

55

- retry_delay: Delay between retries in seconds

56

- auto_reconnect: Automatically reconnect on disconnection

57

- sequential_updates: Process updates sequentially

58

- flood_sleep_threshold: Sleep threshold for flood wait (seconds)

59

- raise_last_call_error: Raise error on last call failure

60

- device_model: Device model string

61

- system_version: System version string

62

- app_version: Application version string

63

- lang_code: Language code

64

- system_lang_code: System language code

65

- loop: Event loop to use

66

- base_logger: Logger for client operations

67

- receive_updates: Whether to receive updates

68

- catch_up: Catch up on missed updates when connecting

69

- entity_cache_limit: Entity cache size limit

70

"""

71

```

72

73

### Connection Management

74

75

Manage the connection to Telegram servers including connecting, disconnecting, and checking connection status.

76

77

```python { .api }

78

async def connect(self) -> None:

79

"""

80

Connect to Telegram servers.

81

82

Must be called before using any client methods.

83

Handles authentication if session exists.

84

"""

85

86

async def disconnect(self) -> None:

87

"""

88

Disconnect from Telegram servers and clean up resources.

89

90

Should be called when done using the client.

91

"""

92

93

def is_connected(self) -> bool:

94

"""

95

Check if the client is currently connected to Telegram.

96

97

Returns:

98

bool: True if connected, False otherwise

99

"""

100

```

101

102

### Convenient Client Startup

103

104

Simplified client startup that handles connection and authentication in one step.

105

106

```python { .api }

107

def start(

108

self,

109

phone: Union[Callable[[], str], str] = lambda: input('Please enter your phone (or bot token): '),

110

password: Union[Callable[[], str], str] = lambda: getpass.getpass('Please enter your password: '),

111

*,

112

bot_token: str = None,

113

force_sms: bool = False,

114

code_callback: Callable[[], Union[str, int]] = None,

115

first_name: str = 'New User',

116

last_name: str = '',

117

max_attempts: int = 3

118

) -> 'TelegramClient':

119

"""

120

Start the client and handle authentication interactively.

121

122

Parameters:

123

- phone: Phone number or callback to get phone number

124

- password: Password or callback to get password for 2FA

125

- bot_token: Bot token for bot authentication

126

- force_sms: Force SMS code instead of Telegram app

127

- code_callback: Callback to get verification code

128

- first_name: First name for new user registration

129

- last_name: Last name for new user registration

130

- max_attempts: Maximum login attempts

131

132

Returns:

133

TelegramClient: The client instance for method chaining

134

"""

135

```

136

137

### Client Properties

138

139

Access client configuration and state information.

140

141

```python { .api }

142

@property

143

def loop(self) -> asyncio.AbstractEventLoop:

144

"""Get the event loop used by the client."""

145

146

@property

147

def disconnected(self) -> asyncio.Future:

148

"""Get a future that completes when the client disconnects."""

149

150

@property

151

def flood_sleep_threshold(self) -> int:

152

"""Get the flood sleep threshold in seconds."""

153

154

@flood_sleep_threshold.setter

155

def flood_sleep_threshold(self, value: int):

156

"""Set the flood sleep threshold in seconds."""

157

```

158

159

### Proxy Configuration

160

161

Configure and manage proxy settings for the client connection.

162

163

```python { .api }

164

def set_proxy(self, proxy: Union[tuple, dict]) -> None:

165

"""

166

Set proxy configuration for the client.

167

168

Parameters:

169

- proxy: Proxy configuration as tuple (type, addr, port, username, password)

170

or dict with proxy parameters

171

"""

172

```

173

174

### User Information

175

176

Get information about the current authenticated user.

177

178

```python { .api }

179

async def get_me(self, input_peer: bool = False) -> Union[types.User, types.InputPeerUser]:

180

"""

181

Get information about the current user.

182

183

Parameters:

184

- input_peer: Return InputPeerUser instead of User

185

186

Returns:

187

User object or InputPeerUser if input_peer=True

188

"""

189

190

async def is_bot(self) -> bool:

191

"""

192

Check if the current user is a bot.

193

194

Returns:

195

bool: True if the current user is a bot, False otherwise

196

"""

197

198

async def is_user_authorized(self) -> bool:

199

"""

200

Check if the user is currently authorized.

201

202

Returns:

203

bool: True if authorized, False otherwise

204

"""

205

```

206

207

## Usage Examples

208

209

### Basic Client Setup

210

211

```python

212

import asyncio

213

from telethon import TelegramClient

214

215

async def main():

216

# Create client with basic configuration

217

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

218

219

# Connect and start

220

await client.start()

221

222

# Check if connected

223

if client.is_connected():

224

print("Connected successfully!")

225

226

# Get current user info

227

me = await client.get_me()

228

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

229

230

# Check if bot

231

if await client.is_bot():

232

print("Running as a bot")

233

else:

234

print("Running as a user")

235

236

# Clean disconnect

237

await client.disconnect()

238

239

asyncio.run(main())

240

```

241

242

### Client with Custom Configuration

243

244

```python

245

from telethon import TelegramClient

246

from telethon.network import ConnectionTcpObfuscated

247

248

# Create client with custom settings

249

client = TelegramClient(

250

'session_name',

251

api_id,

252

api_hash,

253

connection=ConnectionTcpObfuscated, # Use obfuscated connection

254

proxy=('socks5', '127.0.0.1', 9050), # Use SOCKS5 proxy

255

timeout=30, # 30 second timeout

256

request_retries=10, # More retries

257

flood_sleep_threshold=120, # Higher flood threshold

258

device_model='Custom Device', # Custom device model

259

app_version='1.0.0' # Custom app version

260

)

261

```

262

263

### Context Manager Usage

264

265

```python

266

async def main():

267

async with TelegramClient('session', api_id, api_hash) as client:

268

# Client automatically connects on enter

269

me = await client.get_me()

270

print(f"Hello, {me.first_name}!")

271

# Client automatically disconnects on exit

272

```

273

274

## Types

275

276

```python { .api }

277

from typing import Union, Callable, Optional, Type

278

import pathlib

279

import asyncio

280

import logging

281

282

Session = Union[str, pathlib.Path, 'telethon.sessions.Session']

283

Connection = Type['telethon.network.connection.Connection']

284

ProxyConfig = Union[tuple, dict]

285

EntityLike = Union[int, str, 'types.InputPeer']

286

```