0

Send message to Discord channel using Discord Bot

by
Published Jul 9, 2024

Send message to Discord channel using apps: https://discord.com/developers/applications

Script discord Verified

The script

Submitted by henri186 Bun
Verified 7 days ago
1
type DiscordBotConfiguration = {
2
  // Bot token, sent as `Authorization: Bot <token>`. Preferred field.
3
  bot_token?: string,
4
  // Ed25519 key for verifying interactions. Legacy: older resources stored the
5
  // bot token here, so we fall back to it for backward compatibility.
6
  public_key?: string,
7
  application_id: string
8
};
9

10
// Note: you can also send messages to channels using Discord webhooks: https://hub.windmill.dev/scripts/discord/1288/
11

12
import { RequestInit } from 'node-fetch';
13

14
export async function main(
15
  config: DiscordBotConfiguration,
16
  channelId: string,
17
  message: string
18
): Promise<any> {
19
  const url = `https://discord.com/api/v9/channels/${channelId}/messages`;
20

21
  const payload = {
22
    content: message
23
  };
24

25
  const requestOptions: RequestInit = {
26
    method: 'POST',
27
    headers: {
28
      'Content-Type': 'application/json',
29
      'Authorization': `Bot ${config.bot_token ?? config.public_key}`
30
    },
31
    body: JSON.stringify(payload)
32
  };
33

34
  const response = await fetch(url, requestOptions);
35

36
  return await response.json();
37
}