or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdcdn-management.mdcloud-computing.mdcommunication-services.mdconfiguration-utilities.mddata-processing.mdfile-storage.mdindex.md

communication-services.mddocs/

0

# Communication Services

1

2

SMS messaging and real-time communication services for application integration. The communication platform provides comprehensive messaging capabilities and real-time communication features.

3

4

## Capabilities

5

6

### SMS Services

7

8

SMS message service operations including signature and template management through the `Sms` class.

9

10

```python { .api }

11

class Sms:

12

def __init__(self, auth: Auth):

13

"""

14

Initialize SMS service client.

15

16

Args:

17

auth: Auth instance for authentication

18

"""

19

20

# Signature Management

21

def createSignature(self, signature: str, source: str, pics: list = None) -> tuple:

22

"""

23

Create SMS signature.

24

25

Args:

26

signature: Signature text content

27

source: Source type or identifier

28

pics: List of signature image URLs (optional)

29

30

Returns:

31

(dict, ResponseInfo): Creation result and response info

32

"""

33

34

def querySignature(self, audit_status: str = None, page: int = 1, page_size: int = 20) -> tuple:

35

"""

36

Query SMS signatures.

37

38

Args:

39

audit_status: Audit status filter ('pending', 'approved', 'rejected')

40

page: Page number (default: 1)

41

page_size: Number of items per page (default: 20)

42

43

Returns:

44

(dict, ResponseInfo): Signature list and response info

45

"""

46

47

def updateSignature(self, id: str, signature: str) -> tuple:

48

"""

49

Update SMS signature.

50

51

Args:

52

id: Signature ID

53

signature: Updated signature text

54

55

Returns:

56

(dict, ResponseInfo): Update result and response info

57

"""

58

59

def deleteSignature(self, id: str) -> tuple:

60

"""

61

Delete SMS signature.

62

63

Args:

64

id: Signature ID

65

66

Returns:

67

(dict, ResponseInfo): Deletion result and response info

68

"""

69

70

# Template Management

71

def createTemplate(self, name: str, template: str, type: str, description: str, signature_id: str) -> tuple:

72

"""

73

Create SMS template.

74

75

Args:

76

name: Template name

77

template: Template content with variable placeholders

78

type: Template type ('notification', 'verification', 'marketing')

79

description: Template description

80

signature_id: Associated signature ID

81

82

Returns:

83

(dict, ResponseInfo): Creation result and response info

84

"""

85

86

def queryTemplate(self, audit_status: str, page: int = 1, page_size: int = 20) -> tuple:

87

"""

88

Query SMS templates.

89

90

Args:

91

audit_status: Audit status filter ('pending', 'approved', 'rejected')

92

page: Page number (default: 1)

93

page_size: Number of items per page (default: 20)

94

95

Returns:

96

(dict, ResponseInfo): Template list and response info

97

"""

98

99

def updateTemplate(self, id: str, name: str, template: str, description: str, signature_id: str) -> tuple:

100

"""

101

Update SMS template.

102

103

Args:

104

id: Template ID

105

name: Updated template name

106

template: Updated template content

107

description: Updated description

108

signature_id: Updated signature ID

109

110

Returns:

111

(dict, ResponseInfo): Update result and response info

112

"""

113

114

def deleteTemplate(self, id: str) -> tuple:

115

"""

116

Delete SMS template.

117

118

Args:

119

id: Template ID

120

121

Returns:

122

(dict, ResponseInfo): Deletion result and response info

123

"""

124

125

# Message Operations

126

def sendMessage(self, template_id: str, mobiles: list, parameters: dict) -> tuple:

127

"""

128

Send SMS message.

129

130

Args:

131

template_id: Template ID to use

132

mobiles: List of mobile phone numbers

133

parameters: Template parameter values

134

135

Returns:

136

(dict, ResponseInfo): Send result and response info

137

"""

138

139

def get_messages_info(self) -> tuple:

140

"""

141

Query SMS send records.

142

143

Returns:

144

(dict, ResponseInfo): Message records and response info

145

"""

146

```

147

148

### Real-Time Communication

149

150

Real-time communication server management and room operations through the `RtcServer` class.

151

152

```python { .api }

153

class RtcServer:

154

def __init__(self, auth: Auth):

155

"""

156

Initialize RTC server client.

157

158

Args:

159

auth: Auth instance for authentication

160

"""

161

162

def create_app(self, data: dict) -> tuple:

163

"""

164

Create RTC application.

165

166

Args:

167

data: Application configuration dictionary

168

169

Returns:

170

(dict, ResponseInfo): Creation result and response info

171

"""

172

173

def get_app(self, app_id: str = None) -> tuple:

174

"""

175

Get RTC application info or list all applications.

176

177

Args:

178

app_id: Application ID (optional, if None returns all apps)

179

180

Returns:

181

(dict, ResponseInfo): Application info and response info

182

"""

183

184

def delete_app(self, app_id: str) -> tuple:

185

"""

186

Delete RTC application.

187

188

Args:

189

app_id: Application ID

190

191

Returns:

192

(dict, ResponseInfo): Deletion result and response info

193

"""

194

195

def update_app(self, app_id: str, data: dict) -> tuple:

196

"""

197

Update RTC application configuration.

198

199

Args:

200

app_id: Application ID

201

data: Updated configuration dictionary

202

203

Returns:

204

(dict, ResponseInfo): Update result and response info

205

"""

206

207

def list_user(self, app_id: str, room_name: str) -> tuple:

208

"""

209

List users in RTC room.

210

211

Args:

212

app_id: Application ID

213

room_name: Room name

214

215

Returns:

216

(dict, ResponseInfo): User list and response info

217

"""

218

219

def kick_user(self, app_id: str, room_name: str, user_id: str) -> tuple:

220

"""

221

Kick user from RTC room.

222

223

Args:

224

app_id: Application ID

225

room_name: Room name

226

user_id: User ID to kick

227

228

Returns:

229

(dict, ResponseInfo): Operation result and response info

230

"""

231

232

def list_active_rooms(self, app_id: str, room_name_prefix: str = None) -> tuple:

233

"""

234

List active RTC rooms.

235

236

Args:

237

app_id: Application ID

238

room_name_prefix: Room name prefix filter (optional)

239

240

Returns:

241

(dict, ResponseInfo): Active room list and response info

242

"""

243

```

244

245

### RTC Token Generation

246

247

Utility function for generating room access tokens.

248

249

```python { .api }

250

def get_room_token(access_key: str, secret_key: str, room_access: dict) -> str:

251

"""

252

Generate room access token for RTC client.

253

254

Args:

255

access_key: Qiniu access key

256

secret_key: Qiniu secret key

257

room_access: Room access configuration dictionary

258

259

Returns:

260

Room access token string

261

"""

262

```

263

264

## Usage Examples

265

266

### SMS Signature Management

267

268

```python

269

from qiniu import Auth, Sms

270

271

auth = Auth(access_key, secret_key)

272

sms = Sms(auth)

273

274

# Create SMS signature

275

ret, info = sms.createSignature(

276

signature='YourCompany',

277

source='website',

278

pics=['https://example.com/company-logo.png']

279

)

280

281

if info.ok():

282

signature_id = ret['id']

283

print(f"Signature created: {signature_id}")

284

else:

285

print(f"Signature creation failed: {info.error}")

286

287

# Query signatures

288

ret, info = sms.querySignature(audit_status='approved', page=1, page_size=10)

289

if info.ok():

290

for signature in ret['items']:

291

print(f"Signature: {signature['signature']} - Status: {signature['audit_status']}")

292

293

# Update signature

294

ret, info = sms.updateSignature(signature_id, 'UpdatedCompanyName')

295

if info.ok():

296

print("Signature updated successfully")

297

```

298

299

### SMS Template Management

300

301

```python

302

from qiniu import Auth, Sms

303

304

auth = Auth(access_key, secret_key)

305

sms = Sms(auth)

306

307

# Create verification code template

308

template_content = "Your verification code is ${code}, valid for ${minutes} minutes."

309

ret, info = sms.createTemplate(

310

name='Verification Code',

311

template=template_content,

312

type='verification',

313

description='User verification code template',

314

signature_id='signature-id-123'

315

)

316

317

if info.ok():

318

template_id = ret['id']

319

print(f"Template created: {template_id}")

320

321

# Create notification template

322

notification_template = "Hello ${name}, your order ${order_id} has been ${status}."

323

ret, info = sms.createTemplate(

324

name='Order Notification',

325

template=notification_template,

326

type='notification',

327

description='Order status notification template',

328

signature_id='signature-id-123'

329

)

330

331

# Query templates

332

ret, info = sms.queryTemplate(audit_status='approved')

333

if info.ok():

334

for template in ret['items']:

335

print(f"Template: {template['name']} - {template['template']}")

336

print(f"Status: {template['audit_status']}")

337

```

338

339

### Sending SMS Messages

340

341

```python

342

from qiniu import Auth, Sms

343

344

auth = Auth(access_key, secret_key)

345

sms = Sms(auth)

346

347

# Send verification code

348

mobile_numbers = ['+86-13812345678', '+86-13987654321']

349

parameters = {

350

'code': '123456',

351

'minutes': '5'

352

}

353

354

ret, info = sms.sendMessage(

355

template_id='template-verification-123',

356

mobiles=mobile_numbers,

357

parameters=parameters

358

)

359

360

if info.ok():

361

print(f"Messages sent successfully: {ret}")

362

for result in ret['items']:

363

mobile = result['mobile']

364

status = result['status']

365

print(f"Mobile: {mobile} - Status: {status}")

366

else:

367

print(f"Failed to send messages: {info.error}")

368

369

# Send order notification

370

notification_params = {

371

'name': 'John Doe',

372

'order_id': 'ORD-2024-001',

373

'status': 'shipped'

374

}

375

376

ret, info = sms.sendMessage(

377

template_id='template-notification-456',

378

mobiles=['+86-13812345678'],

379

parameters=notification_params

380

)

381

382

# Query message records

383

ret, info = sms.get_messages_info()

384

if info.ok():

385

for record in ret['items']:

386

print(f"Message ID: {record['id']}")

387

print(f"Mobile: {record['mobile']}")

388

print(f"Status: {record['status']}")

389

print(f"Send time: {record['created_at']}")

390

```

391

392

### RTC Application Management

393

394

```python

395

from qiniu import Auth, RtcServer

396

397

auth = Auth(access_key, secret_key)

398

rtc_server = RtcServer(auth)

399

400

# Create RTC application

401

app_config = {

402

'name': 'video-chat-app',

403

'description': 'Video chat application',

404

'callback_url': 'https://api.example.com/rtc-callback'

405

}

406

407

ret, info = rtc_server.create_app(app_config)

408

if info.ok():

409

app_id = ret['appId']

410

print(f"RTC app created: {app_id}")

411

412

# Get application info

413

ret, info = rtc_server.get_app(app_id)

414

if info.ok():

415

app_info = ret

416

print(f"App name: {app_info['name']}")

417

print(f"Status: {app_info['status']}")

418

print(f"Created: {app_info['created_at']}")

419

420

# List all applications

421

ret, info = rtc_server.get_app() # No app_id returns all apps

422

if info.ok():

423

for app in ret['items']:

424

print(f"App: {app['name']} ({app['appId']})")

425

426

# Update application

427

update_config = {

428

'description': 'Updated video chat application',

429

'max_users_per_room': 50

430

}

431

432

ret, info = rtc_server.update_app(app_id, update_config)

433

if info.ok():

434

print("App updated successfully")

435

```

436

437

### Room and User Management

438

439

```python

440

from qiniu import Auth, RtcServer, get_room_token

441

442

auth = Auth(access_key, secret_key)

443

rtc_server = RtcServer(auth)

444

445

app_id = 'your-app-id'

446

room_name = 'meeting-room-001'

447

448

# Generate room access token for client

449

room_access = {

450

'appId': app_id,

451

'roomName': room_name,

452

'userId': 'user-123',

453

'expireAt': 1640995200, # Unix timestamp

454

'permission': 'admin' # 'admin' or 'user'

455

}

456

457

room_token = get_room_token(access_key, secret_key, room_access)

458

print(f"Room token: {room_token}")

459

460

# List users in room

461

ret, info = rtc_server.list_user(app_id, room_name)

462

if info.ok():

463

users = ret['users']

464

print(f"Users in room '{room_name}': {len(users)}")

465

for user in users:

466

print(f" User ID: {user['userId']}")

467

print(f" Join time: {user['joinTime']}")

468

print(f" Status: {user['status']}")

469

470

# Kick a user from room

471

user_to_kick = 'disruptive-user-456'

472

ret, info = rtc_server.kick_user(app_id, room_name, user_to_kick)

473

if info.ok():

474

print(f"User {user_to_kick} kicked from room")

475

else:

476

print(f"Failed to kick user: {info.error}")

477

478

# List active rooms

479

ret, info = rtc_server.list_active_rooms(app_id, room_name_prefix='meeting-')

480

if info.ok():

481

active_rooms = ret['rooms']

482

print(f"Active meeting rooms: {len(active_rooms)}")

483

for room in active_rooms:

484

print(f" Room: {room['roomName']}")

485

print(f" Users: {room['userCount']}")

486

print(f" Created: {room['createdAt']}")

487

```

488

489

### Bulk SMS Operations

490

491

```python

492

from qiniu import Auth, Sms

493

import csv

494

import time

495

496

auth = Auth(access_key, secret_key)

497

sms = Sms(auth)

498

499

def send_bulk_notifications(csv_file, template_id):

500

"""Send bulk SMS notifications from CSV file"""

501

502

with open(csv_file, 'r') as file:

503

reader = csv.DictReader(file)

504

505

batch_size = 100 # Send in batches

506

batch = []

507

508

for row in reader:

509

mobile = row['mobile']

510

name = row['name']

511

512

# Add to current batch

513

batch.append({

514

'mobile': mobile,

515

'parameters': {

516

'name': name,

517

'message': row.get('message', 'General notification')

518

}

519

})

520

521

# Send batch when full

522

if len(batch) >= batch_size:

523

send_batch(batch, template_id)

524

batch = []

525

time.sleep(1) # Rate limiting

526

527

# Send remaining items

528

if batch:

529

send_batch(batch, template_id)

530

531

def send_batch(batch, template_id):

532

"""Send SMS batch"""

533

mobiles = [item['mobile'] for item in batch]

534

535

# For simplicity, using first item's parameters

536

# In practice, you might need template per message

537

parameters = batch[0]['parameters']

538

539

ret, info = sms.sendMessage(template_id, mobiles, parameters)

540

541

if info.ok():

542

success_count = sum(1 for item in ret['items'] if item['status'] == 'success')

543

print(f"Batch sent: {success_count}/{len(batch)} successful")

544

else:

545

print(f"Batch failed: {info.error}")

546

547

# Usage

548

send_bulk_notifications('customers.csv', 'template-promotion-789')

549

```

550

551

### RTC Room Monitoring

552

553

```python

554

from qiniu import Auth, RtcServer

555

import time

556

import threading

557

558

auth = Auth(access_key, secret_key)

559

rtc_server = RtcServer(auth)

560

561

def monitor_rtc_rooms(app_id):

562

"""Monitor RTC room activity"""

563

564

while True:

565

try:

566

# Get active rooms

567

ret, info = rtc_server.list_active_rooms(app_id)

568

569

if info.ok():

570

rooms = ret['rooms']

571

print(f"\n=== RTC Room Status ===")

572

print(f"Active rooms: {len(rooms)}")

573

574

total_users = 0

575

for room in rooms:

576

room_name = room['roomName']

577

user_count = room['userCount']

578

total_users += user_count

579

580

print(f"Room: {room_name} - Users: {user_count}")

581

582

# Get detailed user list for rooms with many users

583

if user_count > 10:

584

ret, info = rtc_server.list_user(app_id, room_name)

585

if info.ok():

586

users = ret['users']

587

print(f" High activity room - {len(users)} users:")

588

for user in users[:5]: # Show first 5 users

589

print(f" {user['userId']} (joined: {user['joinTime']})")

590

591

print(f"Total active users: {total_users}")

592

593

except Exception as e:

594

print(f"Monitoring error: {e}")

595

596

time.sleep(30) # Check every 30 seconds

597

598

# Start monitoring in background

599

app_id = 'your-rtc-app-id'

600

monitor_thread = threading.Thread(target=monitor_rtc_rooms, args=(app_id,))

601

monitor_thread.daemon = True

602

monitor_thread.start()

603

604

print(f"Started monitoring RTC app: {app_id}")

605

```

606

607

### SMS Campaign Management

608

609

```python

610

from qiniu import Auth, Sms

611

import datetime

612

613

auth = Auth(access_key, secret_key)

614

sms = Sms(auth)

615

616

class SMSCampaign:

617

def __init__(self, sms_client):

618

self.sms = sms_client

619

self.campaign_stats = {}

620

621

def create_campaign_template(self, campaign_name, signature_id):

622

"""Create template for campaign"""

623

template_content = "Hi ${name}! ${campaign_message} Reply STOP to opt out."

624

625

ret, info = self.sms.createTemplate(

626

name=f'Campaign-{campaign_name}',

627

template=template_content,

628

type='marketing',

629

description=f'Marketing campaign: {campaign_name}',

630

signature_id=signature_id

631

)

632

633

if info.ok():

634

return ret['id']

635

else:

636

raise Exception(f"Template creation failed: {info.error}")

637

638

def send_campaign(self, template_id, recipients, campaign_message):

639

"""Send campaign to recipients"""

640

campaign_id = f"campaign-{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}"

641

642

self.campaign_stats[campaign_id] = {

643

'total': len(recipients),

644

'sent': 0,

645

'failed': 0,

646

'start_time': datetime.datetime.now()

647

}

648

649

batch_size = 50

650

for i in range(0, len(recipients), batch_size):

651

batch = recipients[i:i + batch_size]

652

653

mobiles = [r['mobile'] for r in batch]

654

655

# Send to batch

656

for recipient in batch:

657

parameters = {

658

'name': recipient['name'],

659

'campaign_message': campaign_message

660

}

661

662

ret, info = self.sms.sendMessage(template_id, [recipient['mobile']], parameters)

663

664

if info.ok():

665

self.campaign_stats[campaign_id]['sent'] += 1

666

else:

667

self.campaign_stats[campaign_id]['failed'] += 1

668

print(f"Failed to send to {recipient['mobile']}: {info.error}")

669

670

time.sleep(2) # Rate limiting between batches

671

672

return campaign_id

673

674

def get_campaign_stats(self, campaign_id):

675

"""Get campaign statistics"""

676

return self.campaign_stats.get(campaign_id, {})

677

678

# Usage

679

campaign_manager = SMSCampaign(sms)

680

681

# Create campaign template

682

template_id = campaign_manager.create_campaign_template('Spring Sale', 'signature-id-123')

683

684

# Define recipients

685

recipients = [

686

{'name': 'Alice', 'mobile': '+86-13812345678'},

687

{'name': 'Bob', 'mobile': '+86-13987654321'},

688

{'name': 'Carol', 'mobile': '+86-13611111111'}

689

]

690

691

# Send campaign

692

campaign_id = campaign_manager.send_campaign(

693

template_id=template_id,

694

recipients=recipients,

695

campaign_message='Save 30% on all items this week! Use code SPRING30'

696

)

697

698

# Check stats

699

stats = campaign_manager.get_campaign_stats(campaign_id)

700

print(f"Campaign {campaign_id} stats:")

701

print(f"Total: {stats['total']}")

702

print(f"Sent: {stats['sent']}")

703

print(f"Failed: {stats['failed']}")

704

print(f"Success rate: {stats['sent']/stats['total']*100:.1f}%")

705

```