0

Read last message sent to a Discord channel

by
Published Mar 12, 2024

Configure app & bot in https://discord.com/developers/applications/

Script discord Verified

The script

Submitted by henri186 Bun
Verified 18 days ago
1
// Importing the required types for fetch
2
import { RequestInit, Response } from 'node-fetch';
3

4
// Defining the resource type as per the instructions
5
type DiscordBotConfiguration = {
6
  // Bot token, sent as `Authorization: Bot <token>`. Preferred field.
7
  bot_token?: string,
8
  // Ed25519 key for verifying interactions. Legacy: older resources stored the
9
  // bot token here, so we fall back to it for backward compatibility.
10
  public_key?: string,
11
  application_id: string
12
};
13

14
// The main function to fetch the last message sent to a Discord channel
15
export async function main(discordBotConfiguration: DiscordBotConfiguration, channel_id: string): Promise<any> {
16
  // Constructing the URL to fetch the last message from a Discord channel
17
  // Note: The channel ID needs to be known beforehand and is hardcoded here for demonstration.
18
  // Replace 'YOUR_CHANNEL_ID' with the actual channel ID.
19
  const url = `https://discord.com/api/v9/channels/${channel_id}/messages?limit=1`;
20

21
  // Preparing the request options, including the authorization header
22
  const requestOptions: RequestInit = {
23
    method: 'GET',
24
    headers: {
25
      'Authorization': `Bot ${discordBotConfiguration.bot_token ?? discordBotConfiguration.public_key}`,
26
      'Content-Type': 'application/json'
27
    }
28
  };
29

30
  // Performing the fetch request to get the last message
31
  try {
32
    const response: Response = await fetch(url, requestOptions);
33
    if (!response.ok) {
34
      throw new Error(`Failed to fetch messages: ${response.statusText}`);
35
    }
36
    const messages = await response.json();
37
    // Assuming the response is an array of messages, return the first one which is the latest
38
    return messages.length > 0 ? messages[0] : null;
39
  } catch (error) {
40
    console.error('Error fetching the last message:', error);
41
    throw error;
42
  }
43
}