0
Read last message sent to a Discord channel
One script reply has been approved by the moderators Verified
Created by henri186 46 days ago Viewed 3331 times
0
Submitted by henri186 Bun
Verified 46 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
  public_key: string,
7
  application_id: string
8
};
9

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

17
  // Preparing the request options, including the authorization header
18
  const requestOptions: RequestInit = {
19
    method: 'GET',
20
    headers: {
21
      'Authorization': `Bot ${discordBotConfiguration.public_key}`,
22
      'Content-Type': 'application/json'
23
    }
24
  };
25

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