Back to APIs

Create and manage community interactions with bots and webhooks.

Using the Discord API with Trigger.dev

You can use Trigger.dev with any existing Node SDK or even just using fetch. Using io.runTask makes your Discord background job resumable and appear in our dashboard.

Use io.runTask() and the official SDK or fetch.

Use our HTTP endpoint to subscribe to webhooks

Example code using Discord

Below are some working code examples of how you can use Discord with Trigger.dev. These samples are open source and maintained by the community, you can copy and paste them into your own projects.

1
import { REST } from "@discordjs/rest";
2
import { API } from "@discordjs/core";
3
import { TriggerClient, eventTrigger } from "@trigger.dev/sdk";
4
import z from "zod";
5
6
// SDK: https://discord.js.org/docs/packages/core/1.0.1
7
// To get the Discord bot token follow the instructions here:
8
// https://discord.com/developers/docs/getting-started
9
// Bot needs to be added to a server to be able to send messages.
10
// Oauth URL generator to add the bot to a server. Scopes: bot, send messages
11
// Create REST and WebSocket managers directly
12
const rest = new REST({ version: "10" }).setToken(
13
process.env.DISCORD_BOT_TOKEN!
14
);
15
16
// Create a client to emit relevant events.
17
const discordApi = new API(rest);
18
19
client.defineJob({
20
id: "discord-send-message",
21
name: "Discord send message",
22
version: "1.0.0",
23
trigger: eventTrigger({
24
name: "discord-send-message",
25
schema: z.object({
26
// To get the channel ID, right click on the channel and click "Copy ID".
27
// NB: You need to enable developer mode in Discord settings.
28
channelId: z.string(),
29
content: z.string(), // The message content
30
}),
31
}),
32
run: async (payload, io, ctx) => {
33
const { channelId, content } = payload;
34
35
// Wrap an SDK call in io.runTask so it's resumable and displays in logs
36
await io.runTask(
37
"Discord send message",
38
async () => {
39
// See more https://discord.js.org/docs/packages/core/1.0.1/ChannelsAPI:Class
40
const channelsAPI = discordApi.channels;
41
await channelsAPI.createMessage(channelId, { content });
42
},
43
44
// Add metadata to the task to improve how it displays in the logs
45
{ name: "Discord send message", icon: "discord" }
46
);
47
},
48
});