// Importing the required types for fetch
import { RequestInit, Response } from 'node-fetch';
// Defining the resource type as per the instructions
type DiscordBotConfiguration = {
public_key: string,
application_id: string
};
// The main function to fetch the last message sent to a Discord channel
export async function main(discordBotConfiguration: DiscordBotConfiguration, channel_id: string): Promise<any> {
// Constructing the URL to fetch the last message from a Discord channel
// Note: The channel ID needs to be known beforehand and is hardcoded here for demonstration.
// Replace 'YOUR_CHANNEL_ID' with the actual channel ID.
const url = `https://discord.com/api/v9/channels/${channel_id}/messages?limit=1`;
// Preparing the request options, including the authorization header
const requestOptions: RequestInit = {
method: 'GET',
headers: {
'Authorization': `Bot ${discordBotConfiguration.public_key}`,
'Content-Type': 'application/json'
}
};
// Performing the fetch request to get the last message
try {
const response: Response = await fetch(url, requestOptions);
if (!response.ok) {
throw new Error(`Failed to fetch messages: ${response.statusText}`);
}
const messages = await response.json();
// Assuming the response is an array of messages, return the first one which is the latest
return messages.length > 0 ? messages[0] : null;
} catch (error) {
console.error('Error fetching the last message:', error);
throw error;
}
}
Submitted by henri186 285 days ago