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

chat-management.mddocs/

0

# Chat Management

1

2

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

3

4

## Capabilities

5

6

### Participant Management

7

8

Retrieve and iterate through chat participants with filtering options.

9

10

```python { .api }

11

def iter_participants(

12

self,

13

entity,

14

limit: int = None,

15

*,

16

search: str = '',

17

filter=None,

18

chunk_size: int = 200,

19

aggressive: bool = False

20

):

21

"""

22

Iterate through participants in a chat or channel.

23

24

Parameters:

25

- entity: Chat, channel, or supergroup

26

- limit: Maximum number of participants to retrieve

27

- search: Search for participants by name

28

- filter: Participant filter (admins, bots, recent, etc.)

29

- chunk_size: Number of participants per API request

30

- aggressive: Use more API calls for complete results

31

32

Yields:

33

User: Individual participant objects with permissions

34

35

Available filters:

36

- ChannelParticipantsAdmins: Only administrators

37

- ChannelParticipantsBots: Only bots

38

- ChannelParticipantsKicked: Banned users

39

- ChannelParticipantsRecent: Recent participants

40

- ChannelParticipantsSearch: Search by name

41

"""

42

43

async def get_participants(

44

self,

45

*args,

46

**kwargs

47

) -> TotalList:

48

"""

49

Get all participants matching criteria.

50

51

Parameters same as iter_participants().

52

53

Returns:

54

TotalList: List of User objects with total count

55

"""

56

```

57

58

### Admin Operations

59

60

Manage administrator permissions and roles in chats and channels.

61

62

```python { .api }

63

async def edit_admin(

64

self,

65

entity,

66

user,

67

*,

68

change_info: bool = None,

69

post_messages: bool = None,

70

edit_messages: bool = None,

71

delete_messages: bool = None,

72

ban_users: bool = None,

73

invite_users: bool = None,

74

pin_messages: bool = None,

75

add_admins: bool = None,

76

anonymous: bool = None,

77

manage_call: bool = None,

78

other: bool = None,

79

title: str = None,

80

is_admin: bool = None,

81

manage_topics: bool = None

82

) -> types.Updates:

83

"""

84

Edit administrator permissions for a user.

85

86

Parameters:

87

- entity: Chat or channel to edit admin in

88

- user: User to promote/demote or edit permissions

89

- change_info: Can change chat info and photo

90

- post_messages: Can post messages (channels)

91

- edit_messages: Can edit any messages (channels)

92

- delete_messages: Can delete any messages

93

- ban_users: Can ban/unban users

94

- invite_users: Can invite new users

95

- pin_messages: Can pin messages

96

- add_admins: Can add new administrators

97

- anonymous: Messages appear as channel (channels)

98

- manage_call: Can manage voice chats

99

- other: All other permissions

100

- title: Custom admin title

101

- is_admin: Promote (True) or demote (False)

102

- manage_topics: Can manage forum topics

103

104

Returns:

105

Updates object with admin change results

106

107

Raises:

108

- ChatAdminRequiredError: If not admin in chat

109

- UserAdminInvalidError: If cannot edit this admin

110

- RightForbiddenError: If permission not available

111

"""

112

```

113

114

### User Permissions

115

116

Manage individual user permissions and restrictions.

117

118

```python { .api }

119

async def edit_permissions(

120

self,

121

entity,

122

user=None,

123

until_date=None,

124

*,

125

view_messages: bool = True,

126

send_messages: bool = True,

127

send_media: bool = True,

128

send_stickers: bool = True,

129

send_gifs: bool = True,

130

send_games: bool = True,

131

send_inline: bool = True,

132

embed_link_previews: bool = True,

133

send_polls: bool = True,

134

change_info: bool = True,

135

invite_users: bool = True,

136

pin_messages: bool = True,

137

manage_topics: bool = True

138

) -> types.Updates:

139

"""

140

Edit user permissions in a chat or set default permissions.

141

142

Parameters:

143

- entity: Chat or supergroup to edit permissions in

144

- user: Specific user (None for default permissions)

145

- until_date: Restriction end date (None for permanent)

146

- view_messages: Can view chat messages

147

- send_messages: Can send text messages

148

- send_media: Can send photos, videos, files

149

- send_stickers: Can send stickers

150

- send_gifs: Can send GIFs and games

151

- send_games: Can send games

152

- send_inline: Can use inline bots

153

- embed_link_previews: Can show link previews

154

- send_polls: Can send polls

155

- change_info: Can change chat info

156

- invite_users: Can invite new users

157

- pin_messages: Can pin messages

158

- manage_topics: Can manage forum topics

159

160

Returns:

161

Updates object with permission change results

162

163

Raises:

164

- ChatAdminRequiredError: If admin rights required

165

- UserRestrictedError: If user already restricted

166

"""

167

168

async def get_permissions(

169

self,

170

entity,

171

user

172

) -> ParticipantPermissions:

173

"""

174

Get current permissions for a user in a chat.

175

176

Parameters:

177

- entity: Chat or channel

178

- user: User to check permissions for

179

180

Returns:

181

ParticipantPermissions: Object with permission flags

182

"""

183

```

184

185

### User Management

186

187

Kick, ban, and unban users from chats.

188

189

```python { .api }

190

async def kick_participant(

191

self,

192

entity,

193

user

194

) -> types.Updates:

195

"""

196

Remove a user from a chat.

197

198

Parameters:

199

- entity: Chat or supergroup

200

- user: User to remove

201

202

Returns:

203

Updates object with kick result

204

205

Note:

206

In supergroups, this bans the user permanently.

207

Use edit_permissions to restrict instead of ban.

208

209

Raises:

210

- ChatAdminRequiredError: If admin rights required

211

- UserNotParticipantError: If user not in chat

212

"""

213

```

214

215

### Admin Log

216

217

Access and monitor admin actions and chat history.

218

219

```python { .api }

220

def iter_admin_log(

221

self,

222

entity,

223

limit: int = None,

224

*,

225

max_id: int = 0,

226

min_id: int = 0,

227

search: str = None,

228

admins=None,

229

events=None,

230

join_leave: bool = None,

231

invite: bool = None,

232

restrict: bool = None,

233

unrestrict: bool = None,

234

ban: bool = None,

235

unban: bool = None,

236

kick: bool = None,

237

unkick: bool = None,

238

promote: bool = None,

239

demote: bool = None,

240

info: bool = None,

241

settings: bool = None,

242

pinned: bool = None,

243

edit: bool = None,

244

delete: bool = None,

245

group_call: bool = None

246

):

247

"""

248

Iterate through admin log events.

249

250

Parameters:

251

- entity: Channel or supergroup

252

- limit: Maximum number of events to retrieve

253

- max_id: Start from this event ID

254

- min_id: End at this event ID

255

- search: Search in event descriptions

256

- admins: Filter by specific admin users

257

- events: Filter by specific event types

258

- join_leave: Include join/leave events

259

- invite: Include invite events

260

- restrict: Include restriction events

261

- unrestrict: Include unrestriction events

262

- ban: Include ban events

263

- unban: Include unban events

264

- kick: Include kick events

265

- unkick: Include unkick events

266

- promote: Include promotion events

267

- demote: Include demotion events

268

- info: Include info change events

269

- settings: Include settings change events

270

- pinned: Include pin/unpin events

271

- edit: Include message edit events

272

- delete: Include message delete events

273

- group_call: Include voice chat events

274

275

Yields:

276

AdminLogEvent: Individual admin log entries

277

"""

278

279

async def get_admin_log(

280

self,

281

*args,

282

**kwargs

283

) -> TotalList:

284

"""

285

Get admin log events matching criteria.

286

287

Parameters same as iter_admin_log().

288

289

Returns:

290

TotalList: List of AdminLogEvent objects

291

"""

292

```

293

294

### Chat Actions

295

296

Send typing indicators and other chat actions.

297

298

```python { .api }

299

async def action(

300

self,

301

entity,

302

action,

303

*,

304

delay: float = 4,

305

auto_cancel: bool = True

306

):

307

"""

308

Send a chat action (typing, uploading, etc.).

309

310

Parameters:

311

- entity: Chat to send action to

312

- action: Action type or string

313

- delay: How long to show action (seconds)

314

- auto_cancel: Automatically cancel action after delay

315

316

Action types:

317

- 'typing': Typing text

318

- 'upload_photo': Uploading photo

319

- 'upload_video': Uploading video

320

- 'upload_audio': Uploading audio

321

- 'upload_document': Uploading document

322

- 'choose_sticker': Choosing sticker

323

- 'speaking': Speaking in voice chat

324

- 'cancel': Cancel current action

325

326

Usage:

327

async with client.action(chat, 'typing'):

328

# Do something that takes time

329

await asyncio.sleep(3)

330

await client.send_message(chat, 'Done!')

331

"""

332

```

333

334

### Profile Photos

335

336

Manage and retrieve profile photos for users and chats.

337

338

```python { .api }

339

def iter_profile_photos(

340

self,

341

entity,

342

limit: int = None,

343

*,

344

offset: int = 0,

345

max_id: int = 0

346

):

347

"""

348

Iterate through profile photos of a user or chat.

349

350

Parameters:

351

- entity: User, chat, or channel

352

- limit: Maximum number of photos to retrieve

353

- offset: Skip this many photos

354

- max_id: Start from photos with ID less than this

355

356

Yields:

357

Photo: Individual profile photo objects

358

"""

359

360

async def get_profile_photos(

361

self,

362

*args,

363

**kwargs

364

) -> TotalList:

365

"""

366

Get profile photos for an entity.

367

368

Parameters same as iter_profile_photos().

369

370

Returns:

371

TotalList: List of Photo objects

372

"""

373

```

374

375

### Chat Statistics

376

377

Get statistics and analytics for channels and supergroups.

378

379

```python { .api }

380

async def get_stats(

381

self,

382

entity,

383

message=None

384

) -> Union[types.stats.BroadcastStats, types.stats.MegagroupStats]:

385

"""

386

Get statistics for a channel or supergroup.

387

388

Parameters:

389

- entity: Channel or supergroup

390

- message: Specific message to get stats for

391

392

Returns:

393

BroadcastStats for channels or MegagroupStats for supergroups

394

395

Contains:

396

- View counts

397

- Subscriber growth

398

- Message statistics

399

- Interaction data

400

401

Raises:

402

- ChatAdminRequiredError: If admin rights required

403

- StatisticsForbiddenError: If statistics not available

404

"""

405

```

406

407

## Usage Examples

408

409

### Basic Participant Management

410

411

```python

412

import asyncio

413

from telethon import TelegramClient

414

415

async def manage_participants():

416

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

417

await client.start()

418

419

chat = 'your_group_or_channel'

420

421

# Get all participants

422

participants = await client.get_participants(chat)

423

print(f"Total participants: {participants.total}")

424

425

# Iterate through participants

426

async for user in client.iter_participants(chat, limit=50):

427

print(f"User: {user.first_name} (@{user.username})")

428

429

# Check if user is admin

430

permissions = await client.get_permissions(chat, user)

431

if permissions.is_admin:

432

print(f" - Admin: {user.first_name}")

433

434

# Search for specific users

435

async for user in client.iter_participants(chat, search='john'):

436

print(f"Found user named John: {user.first_name}")

437

438

await client.disconnect()

439

440

asyncio.run(manage_participants())

441

```

442

443

### Admin Management

444

445

```python

446

from telethon.tl.types import ChannelParticipantsAdmins

447

448

async def manage_admins():

449

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

450

await client.start()

451

452

chat = 'your_supergroup'

453

user_to_promote = 'username_to_promote'

454

455

# Get current admins

456

admins = await client.get_participants(

457

chat,

458

filter=ChannelParticipantsAdmins

459

)

460

print(f"Current admins: {len(admins)}")

461

462

# Promote user to admin with specific permissions

463

await client.edit_admin(

464

chat,

465

user_to_promote,

466

change_info=True, # Can change chat info

467

delete_messages=True, # Can delete messages

468

ban_users=True, # Can ban users

469

invite_users=True, # Can invite users

470

pin_messages=True, # Can pin messages

471

title='Moderator' # Custom admin title

472

)

473

print(f"Promoted {user_to_promote} to admin")

474

475

# Demote admin (remove admin rights)

476

await client.edit_admin(

477

chat,

478

user_to_promote,

479

is_admin=False

480

)

481

print(f"Demoted {user_to_promote}")

482

483

await client.disconnect()

484

```

485

486

### User Permissions and Restrictions

487

488

```python

489

from datetime import datetime, timedelta

490

491

async def manage_permissions():

492

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

493

await client.start()

494

495

chat = 'your_supergroup'

496

user_to_restrict = 'username_to_restrict'

497

498

# Restrict user for 1 hour

499

restriction_end = datetime.now() + timedelta(hours=1)

500

501

await client.edit_permissions(

502

chat,

503

user_to_restrict,

504

until_date=restriction_end,

505

send_messages=False, # Cannot send messages

506

send_media=False, # Cannot send media

507

send_stickers=False, # Cannot send stickers

508

embed_link_previews=False # Cannot embed links

509

)

510

print(f"Restricted {user_to_restrict} for 1 hour")

511

512

# Remove restrictions (restore default permissions)

513

await client.edit_permissions(

514

chat,

515

user_to_restrict,

516

until_date=None, # Remove time limit

517

send_messages=True, # Can send messages

518

send_media=True, # Can send media

519

send_stickers=True # Can send stickers

520

)

521

print(f"Removed restrictions from {user_to_restrict}")

522

523

# Set default chat permissions (for all members)

524

await client.edit_permissions(

525

chat,

526

user=None, # None = default permissions

527

send_polls=False, # Members cannot send polls

528

pin_messages=False # Members cannot pin messages

529

)

530

print("Updated default permissions")

531

532

await client.disconnect()

533

```

534

535

### Admin Log Monitoring

536

537

```python

538

async def monitor_admin_log():

539

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

540

await client.start()

541

542

channel = 'your_channel_or_supergroup'

543

544

# Get recent admin actions

545

async for event in client.iter_admin_log(channel, limit=20):

546

print(f"Event: {event.action}")

547

print(f"Admin: {event.user.first_name}")

548

print(f"Date: {event.date}")

549

550

# Check specific event types

551

if hasattr(event.action, 'message'):

552

print(f"Message involved: {event.action.message.message}")

553

554

if hasattr(event.action, 'participant'):

555

print(f"User affected: {event.action.participant.user_id}")

556

557

print("---")

558

559

# Filter for specific events

560

async for event in client.iter_admin_log(

561

channel,

562

ban=True, # Only ban events

563

limit=10

564

):

565

print(f"Ban event by {event.user.first_name}")

566

if hasattr(event.action, 'participant'):

567

user_id = event.action.participant.user_id

568

print(f"Banned user ID: {user_id}")

569

570

await client.disconnect()

571

```

572

573

### Chat Actions (Typing Indicators)

574

575

```python

576

async def chat_actions():

577

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

578

await client.start()

579

580

chat = 'username'

581

582

# Show typing indicator

583

async with client.action(chat, 'typing'):

584

# Simulate typing for 3 seconds

585

await asyncio.sleep(3)

586

await client.send_message(chat, 'Hello! I was typing...')

587

588

# Show uploading photo indicator

589

async with client.action(chat, 'upload_photo'):

590

# Simulate photo upload preparation

591

await asyncio.sleep(2)

592

await client.send_file(chat, 'photo.jpg')

593

594

# Manual action control

595

await client.action(chat, 'upload_document')

596

await asyncio.sleep(1)

597

await client.action(chat, 'cancel') # Cancel action

598

599

await client.disconnect()

600

```

601

602

### Chat Statistics

603

604

```python

605

async def get_chat_statistics():

606

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

607

await client.start()

608

609

channel = 'your_channel'

610

611

try:

612

stats = await client.get_stats(channel)

613

614

if hasattr(stats, 'views_graph'):

615

print(f"Channel statistics:")

616

print(f"Period: {stats.period}")

617

print(f"Followers: {stats.followers.current}")

618

print(f"Views: {stats.views_per_post.current}")

619

print(f"Shares: {stats.shares_per_post.current}")

620

621

# Get message-specific stats

622

async for message in client.iter_messages(channel, limit=5):

623

msg_stats = await client.get_stats(channel, message)

624

if hasattr(msg_stats, 'views_graph'):

625

print(f"Message {message.id} views: {msg_stats.views_graph}")

626

627

except Exception as e:

628

print(f"Could not get statistics: {e}")

629

630

await client.disconnect()

631

```

632

633

## Types

634

635

```python { .api }

636

from typing import Union, List, Optional, AsyncIterator

637

from datetime import datetime

638

from telethon.tl import types

639

from telethon import custom

640

641

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

642

UserLike = Union[int, str, types.User]

643

AdminFilter = Union[types.ChannelParticipantsFilter, None]

644

645

class ParticipantPermissions:

646

"""User permissions in a chat"""

647

is_admin: bool

648

is_creator: bool

649

can_change_info: bool

650

can_post_messages: bool

651

can_edit_messages: bool

652

can_delete_messages: bool

653

can_ban_users: bool

654

can_invite_users: bool

655

can_pin_messages: bool

656

can_add_admins: bool

657

658

class AdminLogEvent:

659

"""Admin log event entry"""

660

id: int

661

date: datetime

662

user: types.User

663

action: types.ChannelAdminLogEventAction

664

```