Integrated fetch. Made clearer comments
This commit is contained in:
parent
986f2d2204
commit
550c4b4508
1 changed files with 44 additions and 73 deletions
|
|
@ -4,18 +4,18 @@ import {
|
|||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
|
||||
// Define helper interfaces for Discord responses
|
||||
//Define helper interfaces for Discord responses
|
||||
export interface DiscordChannel {
|
||||
id: string;
|
||||
name?: string; // Optional field
|
||||
name?: string;
|
||||
icon?: string;
|
||||
topic?: string;
|
||||
type?: number;
|
||||
guild_id?: string; // The ID of the guild (server) that the channel belongs to
|
||||
guild_id?: string;
|
||||
}
|
||||
|
||||
interface DiscordMessage {
|
||||
|
|
@ -29,7 +29,6 @@ interface DiscordMessage {
|
|||
}
|
||||
|
||||
class DiscordContextProvider extends BaseContextProvider {
|
||||
// Description for the context provider
|
||||
static description: ContextProviderDescription = {
|
||||
title: "discord",
|
||||
displayTitle: "Discord",
|
||||
|
|
@ -39,96 +38,70 @@ class DiscordContextProvider extends BaseContextProvider {
|
|||
|
||||
private baseUrl = "https://discord.com/api/v10";
|
||||
|
||||
// Helper function to get the Axios instance with proper authorization
|
||||
private getApi(): AxiosInstance {
|
||||
const token = this.options.discordKey;
|
||||
if (!token) {
|
||||
throw new Error("Discord Bot Token is required!");
|
||||
}
|
||||
// Helper function to get the full fetch URL
|
||||
private getUrl(path: string): string {
|
||||
return `${this.baseUrl}${path}`;
|
||||
}
|
||||
|
||||
return axios.create({
|
||||
baseURL: this.baseUrl,
|
||||
async fetchMessages(
|
||||
channelId: string,
|
||||
fetch: FetchFunction,
|
||||
): Promise<Array<DiscordMessage>> {
|
||||
const url = this.getUrl(`/channels/${channelId}/messages`);
|
||||
// Fetch messages from the specified channel using the provided fetch function
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
Authorization: `Bot ${token}`,
|
||||
Authorization: `Bot ${this.options.discordKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch Discord messages from a specific channel using Axios
|
||||
async fetchMessages(channelId: string): Promise<Array<DiscordMessage>> {
|
||||
const api = this.getApi();
|
||||
|
||||
try {
|
||||
const response = await api.get<Array<DiscordMessage>>(
|
||||
`/channels/${channelId}/messages`,
|
||||
);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Error fetching messages:", error);
|
||||
throw new Error(`Failed to fetch messages: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch Discord channels using Axios
|
||||
async fetchChannels(): Promise<Array<DiscordChannel>> {
|
||||
// If channels (with id and optional name) are already provided, skip the API call
|
||||
if (this.options.channels && this.options.channels.length > 0) {
|
||||
// Return the channel details using the provided channel objects
|
||||
return this.options.channels.map(
|
||||
(channel: { id: string; name?: string }) => ({
|
||||
id: channel.id,
|
||||
name: channel.name ?? `Channel ${channel.id}`, // Fall back to "Channel {id}" if name is not provided
|
||||
}),
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch messages: ${response.statusText}`);
|
||||
}
|
||||
|
||||
// If no channels are provided, fetch them from the API using guildId
|
||||
const api = this.getApi();
|
||||
|
||||
try {
|
||||
const response = await api.get<Array<DiscordChannel>>(
|
||||
`/guilds/${this.options.guildId}/channels`,
|
||||
);
|
||||
|
||||
// Filter for text channels (type 0 represents text channels)
|
||||
const filteredChannels = response.data.filter(
|
||||
(channel) => channel.type === 0,
|
||||
);
|
||||
|
||||
return filteredChannels;
|
||||
} catch (error) {
|
||||
console.error("Error fetching channels:", error);
|
||||
throw new Error(`Failed to fetch channels: ${error}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async fetchChannels(fetch: FetchFunction): Promise<Array<DiscordChannel>> {
|
||||
const url = this.getUrl(`/guilds/${this.options.guildId}/channels`);
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
Authorization: `Bot ${this.options.discordKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch channels: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const channels = await response.json();
|
||||
// Filter channels to only include text channels (type 0)
|
||||
return channels.filter((channel: DiscordChannel) => channel.type === 0);
|
||||
}
|
||||
|
||||
// Main function to get context items (messages)
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
// Ensure channels are fetched if only guildId is provided
|
||||
const channels = await this.fetchChannels();
|
||||
const channels = await this.fetchChannels(extras.fetch);
|
||||
|
||||
// Determine the channel ID from the selected channel (either from query or the first in the options)
|
||||
let channelId: string;
|
||||
// Find the channel by ID or name in the query string. If not found, use the first channel
|
||||
const selectedChannel = channels.find(
|
||||
(channel) => channel.id === query || channel.name === query,
|
||||
);
|
||||
|
||||
channelId = selectedChannel ? selectedChannel.id : channels[0].id; // Use the first channel if no match is found
|
||||
channelId = selectedChannel ? selectedChannel.id : channels[0].id;
|
||||
|
||||
// Prepare parts for rendering the message content
|
||||
const parts = ["# Discord Channel Messages", `Channel ID: ${channelId}`];
|
||||
const messages = await this.fetchMessages(channelId);
|
||||
const messages = await this.fetchMessages(channelId, extras.fetch);
|
||||
|
||||
// Check if there are messages
|
||||
if (messages.length > 0) {
|
||||
parts.push("## Messages");
|
||||
|
||||
// Format each message into a markdown string
|
||||
messages.forEach((message) => {
|
||||
// Log each message and the username to confirm access
|
||||
parts.push(
|
||||
`### ${message.author?.username ?? "Unknown User"} on ${
|
||||
message.timestamp
|
||||
|
|
@ -150,16 +123,14 @@ class DiscordContextProvider extends BaseContextProvider {
|
|||
];
|
||||
}
|
||||
|
||||
// Submenu to load the list of channels
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const channels = await this.fetchChannels();
|
||||
const channels = await this.fetchChannels(args.fetch);
|
||||
|
||||
// Map over the channels and return them as submenu items
|
||||
return channels.map((channel) => ({
|
||||
id: channel.id,
|
||||
title: channel.name || `Channel ${channel.id}`, // Fallback to ID if name is missing
|
||||
title: channel.name || `Channel ${channel.id}`,
|
||||
description: channel.topic ?? "",
|
||||
}));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue