or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

app-commands.mdcommands-framework.mdcore-objects.mdevent-handling.mdindex.mduser-interface.mdutilities.mdvoice-audio.mdwebhooks.md

index.mddocs/

0

# Discord.py

1

2

A modern, feature-rich, and async-ready API wrapper for Discord written in Python. Discord.py provides a comprehensive interface for building Discord bots and applications with proper rate limiting, optimized performance, and a Pythonic async/await API. The library supports all Discord features including guilds, channels, users, messages, voice connections, slash commands, and UI components.

3

4

## Package Information

5

6

- **Package Name**: discord.py

7

- **Language**: Python

8

- **Installation**: `pip install discord.py`

9

- **Optional Dependencies**:

10

- Voice support: `pip install discord.py[voice]`

11

- Speed optimizations: `pip install discord.py[speed]`

12

13

## Core Imports

14

15

```python

16

import discord

17

```

18

19

For bot applications with commands:

20

21

```python

22

from discord.ext import commands

23

```

24

25

For application commands (slash commands):

26

27

```python

28

from discord import app_commands

29

```

30

31

For UI components:

32

33

```python

34

from discord import ui

35

```

36

37

## Basic Usage

38

39

### Simple Bot Example

40

41

```python

42

import discord

43

from discord.ext import commands

44

45

# Create bot with command prefix

46

bot = commands.Bot(command_prefix='!', intents=discord.Intents.default())

47

48

@bot.event

49

async def on_ready():

50

print(f'{bot.user} has connected to Discord!')

51

52

@bot.command(name='hello')

53

async def hello(ctx):

54

await ctx.send(f'Hello {ctx.author.mention}!')

55

56

# Run the bot

57

bot.run('YOUR_BOT_TOKEN')

58

```

59

60

### Slash Command Example

61

62

```python

63

import discord

64

from discord.ext import commands

65

66

class MyBot(commands.Bot):

67

def __init__(self):

68

intents = discord.Intents.default()

69

intents.message_content = True

70

super().__init__(command_prefix='!', intents=intents)

71

72

async def setup_hook(self):

73

# Sync slash commands

74

await self.tree.sync()

75

76

bot = MyBot()

77

78

@bot.tree.command(name='greet', description='Greet a user')

79

async def greet(interaction: discord.Interaction, user: discord.Member):

80

await interaction.response.send_message(f'Hello {user.mention}!')

81

82

bot.run('YOUR_BOT_TOKEN')

83

```

84

85

## Architecture

86

87

Discord.py is built around an event-driven architecture with several key components:

88

89

- **Client/Bot**: Central connection manager handling WebSocket events and HTTP API calls

90

- **Gateway**: WebSocket connection for real-time events (messages, reactions, presence updates)

91

- **HTTP**: REST API client for Discord operations (sending messages, managing guilds, etc.)

92

- **Commands Framework**: Extension providing prefix-based command parsing and execution

93

- **Application Commands**: Built-in slash command and context menu support

94

- **Cogs**: Modular command organization system for scalable bot architecture

95

- **UI Components**: Interactive elements like buttons, select menus, and modals

96

97

This design enables both simple script-based bots and complex applications with sophisticated command systems, event handling, and user interactions.

98

99

## Capabilities

100

101

### Core Discord Objects

102

103

Essential Discord entities including users, guilds, channels, messages, roles, and permissions. These objects provide the foundation for all Discord bot interactions.

104

105

```python { .api }

106

class Client:

107

def __init__(self, *, intents: Intents): ...

108

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

109

async def close() -> None: ...

110

111

class User:

112

id: int

113

name: str

114

discriminator: str

115

avatar: Optional[Asset]

116

117

class Guild:

118

id: int

119

name: str

120

owner_id: int

121

members: List[Member]

122

channels: List[GuildChannel]

123

124

class TextChannel:

125

id: int

126

name: str

127

guild: Guild

128

async def send(self, content: str = None, **kwargs) -> Message: ...

129

```

130

131

[Core Objects](./core-objects.md)

132

133

### Commands Framework

134

135

Prefix-based command system with argument parsing, checks, cooldowns, and error handling. Supports cogs for modular organization and extensive customization options.

136

137

```python { .api }

138

class Bot(commands.Bot):

139

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

140

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

141

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

142

143

@commands.command()

144

async def example(ctx: commands.Context, arg: str): ...

145

146

@commands.check()

147

async def custom_check(ctx: commands.Context) -> bool: ...

148

```

149

150

[Commands Framework](./commands-framework.md)

151

152

### Application Commands

153

154

Slash commands and context menus with parameter validation, autocomplete, and localization support. Integrates seamlessly with Discord's native UI.

155

156

```python { .api }

157

class CommandTree:

158

async def sync(self, *, guild: Optional[Guild] = None) -> List[AppCommand]: ...

159

def command(self, *, name: str, description: str): ...

160

161

@app_commands.command(name="example", description="Example command")

162

async def example_slash(interaction: Interaction, value: str): ...

163

164

@app_commands.describe(user="The user to greet")

165

async def greet(interaction: Interaction, user: Member): ...

166

```

167

168

[Application Commands](./app-commands.md)

169

170

### User Interface Components

171

172

Interactive UI elements including buttons, select menus, modals, and views. Enables rich user interactions beyond traditional text commands.

173

174

```python { .api }

175

class View:

176

def __init__(self, *, timeout: Optional[float] = 180.0): ...

177

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

178

179

class Button(ui.Item):

180

def __init__(self, *, style: ButtonStyle, label: str = None): ...

181

async def callback(self, interaction: Interaction) -> None: ...

182

183

class Modal:

184

def __init__(self, *, title: str, timeout: Optional[float] = None): ...

185

async def on_submit(self, interaction: Interaction) -> None: ...

186

```

187

188

[User Interface](./user-interface.md)

189

190

### Voice & Audio

191

192

Voice connection management and audio playback with support for various audio sources and real-time voice data processing.

193

194

```python { .api }

195

class VoiceClient:

196

async def connect(self, *, timeout: float = 60.0) -> None: ...

197

async def disconnect(self, *, force: bool = False) -> None: ...

198

def play(self, source: AudioSource, *, after: Callable = None) -> None: ...

199

200

class AudioSource:

201

def read(self) -> bytes: ...

202

def cleanup(self) -> None: ...

203

```

204

205

[Voice & Audio](./voice-audio.md)

206

207

### Event Handling

208

209

Comprehensive event system for responding to Discord activities like messages, reactions, member changes, and guild updates.

210

211

```python { .api }

212

@client.event

213

async def on_ready(): ...

214

215

@client.event

216

async def on_message(message: Message): ...

217

218

@client.event

219

async def on_member_join(member: Member): ...

220

221

@client.event

222

async def on_reaction_add(reaction: Reaction, user: User): ...

223

```

224

225

[Event Handling](./event-handling.md)

226

227

### Webhooks

228

229

Both synchronous and asynchronous webhook clients for sending messages without a bot presence, supporting embeds, files, and thread management.

230

231

```python { .api }

232

class Webhook:

233

@classmethod

234

async def from_url(cls, url: str, *, session: ClientSession = None) -> Webhook: ...

235

async def send(self, content: str = None, **kwargs) -> WebhookMessage: ...

236

async def edit_message(self, message_id: int, **kwargs) -> WebhookMessage: ...

237

```

238

239

[Webhooks](./webhooks.md)

240

241

### Utilities & Helpers

242

243

Helper functions and utilities for common Discord operations including OAuth URLs, snowflake handling, markdown processing, and time formatting.

244

245

```python { .api }

246

def oauth_url(client_id: int, *, permissions: Permissions = None) -> str: ...

247

def snowflake_time(id: int) -> datetime: ...

248

def utcnow() -> datetime: ...

249

def escape_markdown(text: str) -> str: ...

250

```

251

252

[Utilities](./utilities.md)

253

254

### Enums & Constants

255

256

Essential Discord enums for channels, messages, status types, and other Discord-specific values that provide type safety and clear API semantics.

257

258

```python { .api }

259

class Status(Enum):

260

online = 'online'

261

offline = 'offline'

262

idle = 'idle'

263

dnd = 'dnd'

264

do_not_disturb = 'dnd'

265

invisible = 'invisible'

266

267

class ChannelType(Enum):

268

text = 0

269

private = 1

270

voice = 2

271

group = 3

272

category = 4

273

news = 5

274

news_thread = 10

275

public_thread = 11

276

private_thread = 12

277

stage_voice = 13

278

forum = 15

279

280

class MessageType(Enum):

281

default = 0

282

recipient_add = 1

283

recipient_remove = 2

284

call = 3

285

channel_name_change = 4

286

channel_icon_change = 5

287

pins_add = 6

288

guild_member_join = 7

289

290

class ActivityType(Enum):

291

playing = 0

292

streaming = 1

293

listening = 2

294

watching = 3

295

custom = 4

296

competing = 5

297

```

298

299

## Types

300

301

```python { .api }

302

# Core Types

303

Snowflake = int

304

305

# Intent Types

306

class Intents:

307

"""Gateway intent flags controlling which events Discord sends to your bot."""

308

def __init__(self, **kwargs): ...

309

310

@classmethod

311

def all(cls) -> Intents:

312

"""Create Intents with all flags enabled."""

313

314

@classmethod

315

def none(cls) -> Intents:

316

"""Create Intents with no flags enabled."""

317

318

@classmethod

319

def default(cls) -> Intents:

320

"""Create Intents with Discord's default flags."""

321

322

# Core Intent Flags

323

guilds: bool # Guild events (recommended to keep enabled)

324

members: bool # Member events (requires privileged intent)

325

moderation: bool # Ban/unban events

326

emojis_and_stickers: bool # Emoji and sticker events

327

integrations: bool # Integration events

328

webhooks: bool # Webhook events

329

invites: bool # Invite events

330

voice_states: bool # Voice state events

331

presences: bool # Presence events (requires privileged intent)

332

messages: bool # Message events

333

reactions: bool # Reaction events

334

typing: bool # Typing indicator events

335

message_content: bool # Message content access (privileged)

336

337

# Permission Types

338

class Permissions:

339

def __init__(self, permissions: int = 0): ...

340

@classmethod

341

def all(cls) -> Permissions: ...

342

@classmethod

343

def none(cls) -> Permissions: ...

344

345

# Color Types

346

class Colour:

347

def __init__(self, value: int): ...

348

@classmethod

349

def red(cls) -> Colour: ...

350

@classmethod

351

def blue(cls) -> Colour: ...

352

353

# Message Types

354

class Embed:

355

def __init__(self, **kwargs): ...

356

def add_field(self, *, name: str, value: str, inline: bool = True) -> None: ...

357

def set_footer(self, *, text: str, icon_url: str = None) -> None: ...

358

359

class AllowedMentions:

360

def __init__(self, *, everyone: bool = True, users: bool = True, roles: bool = True): ...

361

362

# File Types

363

class File:

364

def __init__(self, fp: Union[str, bytes, os.PathLike], filename: str = None): ...

365

```

366

367

## Exceptions

368

369

```python { .api }

370

# Base Exceptions

371

class DiscordException(Exception):

372

"""Base exception class for discord.py. Catch this to handle any discord.py exception."""

373

374

class ClientException(DiscordException):

375

"""Exception raised when a Client operation fails due to user input."""

376

377

class HTTPException(DiscordException):

378

"""Exception raised when an HTTP request fails."""

379

status: int # HTTP status code

380

code: int # Discord error code

381

text: str # Error message

382

383

# Specific HTTP Exceptions

384

class Forbidden(HTTPException):

385

"""Exception raised when a 403 Forbidden response is received."""

386

387

class NotFound(HTTPException):

388

"""Exception raised when a 404 Not Found response is received."""

389

390

class RateLimited(DiscordException):

391

"""Exception raised when being rate limited by Discord."""

392

retry_after: float # Seconds until retry is allowed

393

394

# Connection Exceptions

395

class ConnectionClosed(ClientException):

396

"""Exception raised when the gateway connection is closed unexpectedly."""

397

398

class LoginFailure(ClientException):

399

"""Exception raised when login fails due to invalid credentials."""

400

401

class PrivilegedIntentsRequired(ClientException):

402

"""Exception raised when privileged intents are required but not enabled."""

403

```