SDKs overview

Software Development Kits (SDKs) and libraries for Discord provide programmatic interfaces to interact with the Discord API. These tools abstract the underlying RESTful API and WebSocket Gateway, allowing developers to focus on application logic rather than low-level protocol details. The Discord API facilitates the creation of bots, custom clients, and other integrations that can automate tasks, manage server content, and enhance user experience within the Discord platform. Developers can access features such as sending and receiving messages, managing channels, roles, and users, and responding to various events in real-time. While Discord provides extensive documentation for its API, SDKs streamline the development process significantly by offering language-specific methods and structures that map directly to API endpoints and data models.

The Discord API operates on two primary components: the Discord REST API for stateless operations like fetching user data or sending a single message, and the Discord Gateway for real-time, event-driven interactions such as receiving message updates or user presence changes. SDKs typically encapsulate both, handling authentication, rate limits, and WebSocket connections automatically. This dual approach ensures that applications can perform both synchronous administrative tasks and dynamic, interactive functions efficiently. The choice of SDK often depends on the developer's preferred programming language and the specific features required for their integration.

Official SDKs by language

While Discord provides comprehensive API documentation, the most widely adopted SDKs are community-maintained, benefiting from active development and extensive community support. These libraries are often considered de facto standards within their respective language ecosystems due to their stability, feature completeness, and ease of use. The primary languages with robust SDK support are JavaScript (Node.js), Python, and Go, reflecting their popularity in web development and backend services.

Widely Adopted Discord SDKs
Language Package Name Maturity Maintainer
JavaScript (Node.js) discord.js Stable, actively developed Community
Python discord.py Stable, actively developed Community
Go DiscordGo Stable, actively developed Community

Installation

Installing Discord SDKs typically involves using the package manager specific to the programming language. These commands retrieve the library and its dependencies, making them available for use in your project. Before installation, developers usually need to have the appropriate language runtime (e.g., Node.js, Python, Go) installed on their system.

discord.js (JavaScript/Node.js)

For Node.js projects, discord.js is installed via npm. Ensure Node.js and npm are installed on your system. The library requires a relatively recent version of Node.js to function correctly, typically Node.js 16.9.0 or higher, as noted in the discord.js documentation. Developers also need to initialize a Node.js project using npm init -y before installing the library.

npm install discord.js

discord.py (Python)

For Python projects, discord.py is installed using pip, Python's package installer. It is recommended to use a Python virtual environment to manage dependencies, preventing conflicts with other projects. Python 3.8 or newer is typically required for the latest versions of discord.py.

pip install discord.py

To include voice support, which allows bots to join voice channels and play audio, an additional component can be installed:

pip install discord.py[voice]

DiscordGo (Go)

For Go projects, DiscordGo is installed using the Go module system. Go 1.13 or newer is generally required. Initialize a Go module in your project directory before adding the dependency.

go get github.com/bwmarrin/discordgo

After running this command, Go will download the necessary packages and update your go.mod and go.sum files, managing the project's dependencies.

Quickstart example

This quickstart demonstrates how to create a basic Discord bot using discord.js that responds to a specific command. This example requires a Discord bot token, which can be obtained from the Discord Developer Portal by creating a new application and adding a bot user.

Basic 'ping-pong' bot with discord.js

First, create a file named bot.js:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });

const TOKEN = 'YOUR_BOT_TOKEN'; // Replace with your actual bot token

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', message => {
    if (message.author.bot) return; // Ignore messages from other bots

    if (message.content === '!ping') {
        message.reply('Pong!');
    }
});

client.login(TOKEN);

To run this bot, execute the file using Node.js:

node bot.js

Ensure your bot has the necessary permissions (intents) enabled in the Discord Developer Portal, specifically 'Message Content Intent' for recent versions of discord.js to read message content.

Basic 'hello' bot with discord.py

Create a file named bot.py:

import discord

TOKEN = 'YOUR_BOT_TOKEN' # Replace with your actual bot token

intents = discord.Intents.default()
intents.message_content = True # Enable message content intent

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'Logged in as {client.user}!')

@client.event
async def on_message(message):
    if message.author == client.user:
        return # Ignore messages from self

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run(TOKEN)

To run this bot, execute the file using Python:

python bot.py

Similar to discord.js, ensure 'Message Content Intent' is enabled in your bot's settings on the Discord Developer Portal for the bot to process message content.

Basic 'greet' bot with DiscordGo

Create a file named main.go:

package main

import (
	"fmt"
	"os"

	"github.com/bwmarrin/discordgo"
)

var ( 
	Token string
)

func init() {
	Token = os.Getenv("DISCORD_TOKEN") // It's best practice to use environment variables for tokens
	// Alternatively, you can hardcode it for a quick test: Token = "YOUR_BOT_TOKEN"
}

func main() {
	selfbot, err := discordgo.New("Bot " + Token)
	if err != nil {
		fmt.Println("error creating Discord session,", err)
		return
	}

	selfbot.AddHandler(messageCreate)

	selfbot.Identify.Intents = discordgo.IntentsGuildMessages

	err = selfbot.Open()
	if err != nil {
		fmt.Println("error opening connection,", err)
		return
	}

	fmt.Println("Bot is now running. Press CTRL-C to exit.")
	<-make(chan struct{})
}

func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
	if m.Author.ID == s.State.User.ID {
		return // Ignore messages from self
	}

	if m.Content == "!greet" {
		s_, err := s.ChannelMessageSend(m.ChannelID, "Greetings, traveler!")
		if err != nil {
			fmt.Println("Error sending message:", err)
			return
		}
		fmt.Println("Sent message:", s_)
	}
}

Before running, set your bot token as an environment variable or replace os.Getenv("DISCORD_TOKEN") with your token directly. Then, run the Go program:

go run main.go

This example demonstrates basic event handling and message sending, essential for any Discord bot. Further development would involve handling more complex commands, interacting with external APIs, and managing state.

Community libraries

Beyond the primary SDKs, the Discord developer ecosystem includes numerous community-contributed libraries and frameworks in various languages. These often cater to specific use cases, offer alternative paradigms, or provide utilities for niche features. While not as universally adopted as discord.js, discord.py, or DiscordGo, they demonstrate the flexibility and extensibility of the Discord API and the active nature of its developer community.

For example, in Rust, developers can find libraries like serenity and dco, which provide asynchronous, type-safe interfaces to the Discord API, aligning with Rust's focus on performance and memory safety. In C#, libraries such as Discord.Net offer a feature-rich and actively maintained option for .NET developers. These libraries often include advanced features like command handling frameworks, database integrations, and support for Discord's newer features such as slash commands and interaction components.

The existence of multiple community libraries highlights the open nature of Discord's API, allowing developers to choose tools that best fit their project requirements and technical stack. When selecting a community library, it is advisable to consider its active maintenance, documentation quality, and community support, as these factors contribute significantly to long-term project viability. Resources like GitHub and language-specific package repositories are good places to discover these alternatives. For instance, the Mozilla Developer Network's JavaScript documentation provides context for understanding asynchronous operations common in JavaScript-based Discord bots, which many community libraries build upon.