or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application-commands.mdautomod.mdchannels-messaging.mdclient-bot.mdcommand-framework.mderror-handling.mdevents-gateway.mdguild-management.mdindex.mdinteractions-ui.mdlocalization-i18n.mdpermissions-security.mdpolls.mdusers-members.mdvoice-audio.md

client-bot.mddocs/

0

# Client and Bot Classes

1

2

Core client and bot classes for establishing Discord connections and managing bot functionality. The Client class provides basic Discord API connectivity, while Bot classes extend this with command handling capabilities.

3

4

## Capabilities

5

6

### Basic Client

7

8

The foundational client class for Discord API connections with essential connection management and event handling.

9

10

```python { .api }

11

class Client:

12

def __init__(

13

self,

14

*,

15

asyncio_debug: bool = False,

16

loop: Optional[AbstractEventLoop] = None,

17

shard_id: Optional[int] = None,

18

shard_count: Optional[int] = None,

19

enable_debug_events: bool = False,

20

enable_gateway_error_handler: bool = True,

21

localization_provider: Optional[LocalizationProtocol] = None,

22

strict_localization: bool = False,

23

gateway_params: Optional[GatewayParams] = None,

24

connector: Optional[BaseConnector] = None,

25

proxy: Optional[str] = None,

26

proxy_auth: Optional[BasicAuth] = None,

27

assume_unsync_clock: bool = True,

28

max_messages: Optional[int] = 1000,

29

application_id: Optional[int] = None,

30

heartbeat_timeout: float = 60.0,

31

guild_ready_timeout: float = 2.0,

32

allowed_mentions: Optional[AllowedMentions] = None,

33

activity: Optional[BaseActivity] = None,

34

status: Optional[Union[Status, str]] = None,

35

intents: Optional[Intents] = None,

36

chunk_guilds_at_startup: Optional[bool] = None,

37

member_cache_flags: Optional[MemberCacheFlags] = None

38

):

39

"""

40

Initialize a Discord client.

41

42

Parameters:

43

- asyncio_debug: Whether to enable asyncio debugging

44

- loop: Event loop to use (optional)

45

- shard_id: Shard ID for sharded bots (optional)

46

- shard_count: Total number of shards (optional)

47

- enable_debug_events: Whether to enable debug events for gateway data

48

- enable_gateway_error_handler: Whether to enable gateway error handling

49

- localization_provider: Custom localization provider for commands

50

- strict_localization: Whether to raise errors for missing localizations

51

- gateway_params: Gateway connection parameters

52

- connector: HTTP connector for requests (optional)

53

- proxy: Proxy URL for connections (optional)

54

- proxy_auth: Basic auth for proxy connections

55

- assume_unsync_clock: Whether to assume system clock is unsynced

56

- max_messages: Maximum messages to store in cache

57

- application_id: Application ID for the bot (optional)

58

- heartbeat_timeout: Gateway heartbeat timeout in seconds

59

- guild_ready_timeout: Guild ready timeout in seconds

60

- allowed_mentions: Default allowed mentions configuration

61

- activity: Default activity/presence

62

- status: Default status (online, idle, dnd, invisible)

63

- intents: Gateway intents to request (optional)

64

- chunk_guilds_at_startup: Whether to chunk guild members at startup

65

- member_cache_flags: Member cache configuration flags

66

"""

67

68

async def login(self, token: str) -> None:

69

"""

70

Login to Discord with a bot token.

71

72

Parameters:

73

- token: Bot token from Discord Developer Portal

74

"""

75

76

async def connect(self, *, reconnect: bool = True) -> None:

77

"""

78

Connect to Discord gateway.

79

80

Parameters:

81

- reconnect: Whether to reconnect on connection loss

82

"""

83

84

def run(self, token: str, **kwargs) -> None:

85

"""

86

Run the client with automatic connection management.

87

88

Parameters:

89

- token: Bot token

90

- log_handler: Custom log handler (optional)

91

- log_formatter: Custom log formatter (optional)

92

- log_level: Logging level (optional)

93

- root_logger: Whether to configure root logger (optional)

94

"""

95

96

async def close(self) -> None:

97

"""Close the client connection and cleanup resources."""

98

99

async def wait_until_ready(self) -> None:

100

"""Wait until the client is fully ready."""

101

102

def wait_for(

103

self,

104

event: str,

105

*,

106

check: Optional[Callable[..., bool]] = None,

107

timeout: Optional[float] = None

108

) -> Any:

109

"""

110

Wait for a specific event.

111

112

Parameters:

113

- event: Event name to wait for

114

- check: Optional check function

115

- timeout: Maximum time to wait

116

117

Returns:

118

Event data when the event occurs

119

"""

120

121

def dispatch(self, event: str, *args, **kwargs) -> None:

122

"""

123

Dispatch an event to registered listeners.

124

125

Parameters:

126

- event: Event name

127

- args: Event arguments

128

- kwargs: Event keyword arguments

129

"""

130

131

async def fetch_user(self, user_id: int) -> User:

132

"""

133

Fetch a user by ID from Discord API.

134

135

Parameters:

136

- user_id: Discord user ID

137

138

Returns:

139

User object

140

"""

141

142

def get_user(self, user_id: int) -> Optional[User]:

143

"""

144

Get a user from cache by ID.

145

146

Parameters:

147

- user_id: Discord user ID

148

149

Returns:

150

User object if cached, None otherwise

151

"""

152

153

async def fetch_channel(self, channel_id: int) -> Union[GuildChannel, PrivateChannel]:

154

"""

155

Fetch a channel by ID from Discord API.

156

157

Parameters:

158

- channel_id: Discord channel ID

159

160

Returns:

161

Channel object

162

"""

163

164

def get_channel(self, channel_id: int) -> Optional[Union[GuildChannel, PrivateChannel]]:

165

"""

166

Get a channel from cache by ID.

167

168

Parameters:

169

- channel_id: Discord channel ID

170

171

Returns:

172

Channel object if cached, None otherwise

173

"""

174

175

async def sync_commands(

176

self,

177

*,

178

commands: Optional[Sequence[APIApplicationCommand]] = None,

179

guild_id: Optional[int] = None,

180

delete_existing: bool = True,

181

sync_on_cog_actions: Optional[bool] = None

182

) -> None:

183

"""

184

Sync application commands with Discord.

185

186

Parameters:

187

- commands: Commands to sync (optional)

188

- guild_id: Guild ID for guild-specific sync (optional)

189

- delete_existing: Whether to delete commands not in the list

190

- sync_on_cog_actions: Override sync_on_cog_actions setting

191

"""

192

193

@property

194

def user(self) -> Optional[ClientUser]:

195

"""The bot's user object."""

196

197

@property

198

def guilds(self) -> List[Guild]:

199

"""All guilds the bot is in."""

200

201

@property

202

def users(self) -> List[User]:

203

"""All users in the bot's cache."""

204

205

@property

206

def emojis(self) -> List[Emoji]:

207

"""All emojis the client has access to."""

208

209

@property

210

def stickers(self) -> List[GuildSticker]:

211

"""All guild stickers the client has access to."""

212

213

@property

214

def latency(self) -> float:

215

"""WebSocket latency in seconds."""

216

217

@property

218

def is_ready(self) -> bool:

219

"""Whether the client is ready."""

220

221

def is_ws_ratelimited(self) -> bool:

222

"""Whether the websocket is currently rate limited."""

223

224

async def get_or_fetch_user(self, user_id: int, *, strict: bool = False) -> Optional[User]:

225

"""

226

Get a user from cache or fetch from API.

227

228

Parameters:

229

- user_id: Discord user ID

230

- strict: Whether to raise error if user not found

231

232

Returns:

233

User object if found, None otherwise (unless strict=True)

234

"""

235

```

236

237

### Message Command Bot

238

239

Bot class with traditional text-based command support extending the basic client functionality.

240

241

```python { .api }

242

class Bot(commands.BotBase, Client):

243

def __init__(

244

self,

245

command_prefix: Union[str, Iterable[str], Callable[[Bot, Message], Union[str, Iterable[str]]]],

246

*,

247

help_command: Optional[commands.HelpCommand] = ...,

248

description: Optional[str] = None,

249

**options

250

):

251

"""

252

Initialize a bot with message command support.

253

254

Parameters:

255

- command_prefix: Command prefix(es) or callable returning prefix(es)

256

- help_command: Custom help command implementation

257

- description: Bot description for help command

258

- options: Additional client options

259

"""

260

261

@property

262

def commands(self) -> Set[commands.Command]:

263

"""All registered commands."""

264

265

def add_command(self, command: commands.Command) -> None:

266

"""

267

Add a command to the bot.

268

269

Parameters:

270

- command: Command to add

271

"""

272

273

def remove_command(self, name: str) -> Optional[commands.Command]:

274

"""

275

Remove a command by name.

276

277

Parameters:

278

- name: Command name

279

280

Returns:

281

Removed command if found

282

"""

283

284

def get_command(self, name: str) -> Optional[commands.Command]:

285

"""

286

Get a command by name.

287

288

Parameters:

289

- name: Command name

290

291

Returns:

292

Command if found

293

"""

294

295

async def process_commands(self, message: Message) -> None:

296

"""

297

Process a message for commands.

298

299

Parameters:

300

- message: Message to process

301

"""

302

303

async def invoke(self, ctx: commands.Context) -> None:

304

"""

305

Invoke a command from context.

306

307

Parameters:

308

- ctx: Command context

309

"""

310

311

def command(self, name: str = None, **kwargs):

312

"""

313

Decorator for registering commands.

314

315

Parameters:

316

- name: Command name (optional)

317

- kwargs: Command options

318

"""

319

320

def group(self, name: str = None, **kwargs):

321

"""

322

Decorator for registering command groups.

323

324

Parameters:

325

- name: Group name (optional)

326

- kwargs: Group options

327

"""

328

```

329

330

### Auto-Sharded Bot

331

332

Bot with automatic sharding for large bot deployments across multiple processes.

333

334

```python { .api }

335

class AutoShardedBot(commands.AutoShardedBotBase, Bot):

336

def __init__(self, command_prefix, **options):

337

"""

338

Initialize an auto-sharded bot.

339

340

Parameters:

341

- command_prefix: Command prefix(es)

342

- options: Bot options including shard configuration

343

"""

344

```

345

346

### Interaction Bot

347

348

Specialized bot focused on application commands (slash commands, context menus) with streamlined interaction handling.

349

350

```python { .api }

351

class InteractionBot(commands.InteractionBotBase, Client):

352

def __init__(self, **options):

353

"""

354

Initialize an interaction-focused bot.

355

356

Parameters:

357

- options: Client options

358

"""

359

360

@property

361

def slash_commands(self) -> Set[SlashCommand]:

362

"""All registered slash commands."""

363

364

@property

365

def user_commands(self) -> Set[UserCommand]:

366

"""All registered user commands."""

367

368

@property

369

def message_commands(self) -> Set[MessageCommand]:

370

"""All registered message commands."""

371

372

def add_slash_command(self, command: SlashCommand) -> None:

373

"""

374

Add a slash command.

375

376

Parameters:

377

- command: Slash command to add

378

"""

379

380

def slash_command(self, name: str = None, **kwargs):

381

"""

382

Decorator for slash commands.

383

384

Parameters:

385

- name: Command name (optional)

386

- kwargs: Command options

387

"""

388

389

def user_command(self, name: str = None, **kwargs):

390

"""

391

Decorator for user context menu commands.

392

393

Parameters:

394

- name: Command name (optional)

395

- kwargs: Command options

396

"""

397

398

def message_command(self, name: str = None, **kwargs):

399

"""

400

Decorator for message context menu commands.

401

402

Parameters:

403

- name: Command name (optional)

404

- kwargs: Command options

405

"""

406

```

407

408

### Auto-Sharded Interaction Bot

409

410

Interaction bot with automatic sharding capabilities for large-scale deployments.

411

412

```python { .api }

413

class AutoShardedInteractionBot(commands.AutoShardedBotBase, InteractionBot):

414

def __init__(self, **options):

415

"""

416

Initialize an auto-sharded interaction bot.

417

418

Parameters:

419

- options: Bot options including shard configuration

420

"""

421

```

422

423

## Usage Examples

424

425

### Basic Client Setup

426

427

```python

428

import disnake

429

430

intents = disnake.Intents.default()

431

intents.message_content = True

432

433

client = disnake.Client(intents=intents)

434

435

@client.event

436

async def on_ready():

437

print(f'Logged in as {client.user}')

438

439

@client.event

440

async def on_message(message):

441

if message.author == client.user:

442

return

443

444

if message.content.startswith('!hello'):

445

await message.channel.send('Hello!')

446

447

client.run('YOUR_BOT_TOKEN')

448

```

449

450

### Bot with Commands

451

452

```python

453

from disnake.ext import commands

454

455

bot = commands.Bot(command_prefix='!', intents=disnake.Intents.all())

456

457

@bot.event

458

async def on_ready():

459

print(f'Bot ready: {bot.user}')

460

461

@bot.command()

462

async def ping(ctx):

463

latency = round(bot.latency * 1000)

464

await ctx.send(f'Pong! Latency: {latency}ms')

465

466

@bot.group()

467

async def admin(ctx):

468

if ctx.invoked_subcommand is None:

469

await ctx.send('Invalid admin command.')

470

471

@admin.command()

472

async def kick(ctx, member: disnake.Member, *, reason="No reason provided"):

473

await member.kick(reason=reason)

474

await ctx.send(f'Kicked {member}')

475

476

bot.run('YOUR_BOT_TOKEN')

477

```

478

479

### Interaction Bot with Slash Commands

480

481

```python

482

import disnake

483

484

bot = disnake.InteractionBot(intents=disnake.Intents.default())

485

486

@bot.slash_command(description="Get bot latency")

487

async def ping(inter: disnake.ApplicationCommandInteraction):

488

latency = round(bot.latency * 1000)

489

await inter.response.send_message(f'Pong! Latency: {latency}ms')

490

491

@bot.slash_command(description="Say something")

492

async def say(

493

inter: disnake.ApplicationCommandInteraction,

494

message: str = disnake.Param(description="Message to say")

495

):

496

await inter.response.send_message(message)

497

498

bot.run('YOUR_BOT_TOKEN')

499

```