updated the provider for multichannel support
This commit is contained in:
parent
1e699f15d4
commit
6da94c4864
6 changed files with 392 additions and 147 deletions
|
|
@ -1,147 +0,0 @@
|
|||
import { AxiosError, AxiosInstance } from "axios";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
// Define helper interfaces for Discord responses
|
||||
export interface DiscordChannel {
|
||||
id: string;
|
||||
name?: string;
|
||||
icon?: string;
|
||||
topic?: string;
|
||||
guild_id?: string; // The ID of the guild (server) that the channel belongs to
|
||||
}
|
||||
|
||||
interface DiscordMessage {
|
||||
id: string;
|
||||
content: string;
|
||||
author: {
|
||||
id: string;
|
||||
username: string;
|
||||
};
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
class DiscordContextProvider extends BaseContextProvider {
|
||||
// Description for the context provider
|
||||
static description: ContextProviderDescription = {
|
||||
title: "discord-messages",
|
||||
displayTitle: "Discord Messages",
|
||||
description: "Reference messages from a Discord channel",
|
||||
type: "normal",
|
||||
};
|
||||
|
||||
// Helper function to get the Axios instance with proper authorization
|
||||
private async getApi(): Promise<AxiosInstance> {
|
||||
const { default: Axios } = await import("axios");
|
||||
const token = this.options.token;
|
||||
if (!token) {
|
||||
throw new Error("Discord Bot Token is required!");
|
||||
}
|
||||
|
||||
return Axios.create({
|
||||
baseURL: "https://discord.com/api/v10",
|
||||
headers: {
|
||||
Authorization: `Bot ${token}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Reusable error handling method
|
||||
private handleApiError(ex: unknown): string {
|
||||
let content = "# Discord API Error\n\nFailed to retrieve data. ";
|
||||
if (ex instanceof AxiosError) {
|
||||
if (ex.response) {
|
||||
const errorMessage = ex.response?.data
|
||||
? (ex.response.data.message ?? JSON.stringify(ex.response?.data))
|
||||
: `${ex.response.status}: ${ex.response.statusText}`;
|
||||
content += `Discord API Error: ${errorMessage}`;
|
||||
} else {
|
||||
content += `Discord API Request Error ${ex.request}`;
|
||||
}
|
||||
} else {
|
||||
content += `Unknown error: ${ex instanceof Error ? ex.message : JSON.stringify(ex)}`;
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
// Fetch Discord channels
|
||||
private async fetchChannels(
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<Array<DiscordChannel>> {
|
||||
const api = await this.getApi();
|
||||
|
||||
try {
|
||||
const response = await api.get<Array<DiscordChannel>>(
|
||||
`/guilds/${this.options.guildId}/channels`,
|
||||
);
|
||||
return response.data;
|
||||
} catch (ex) {
|
||||
throw new Error(this.handleApiError(ex));
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch messages from a specific channel
|
||||
private async fetchMessages(
|
||||
channelId: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<Array<DiscordMessage>> {
|
||||
const api = await this.getApi();
|
||||
try {
|
||||
const response = await api.get<Array<DiscordMessage>>(
|
||||
`/channels/${channelId}/messages`,
|
||||
{ params: { limit: 10 } },
|
||||
);
|
||||
return response.data;
|
||||
} catch (ex) {
|
||||
throw new Error(this.handleApiError(ex));
|
||||
}
|
||||
}
|
||||
|
||||
// Main function to get context items (channels and messages)
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const result = [] as Array<ContextItem>;
|
||||
|
||||
try {
|
||||
// Fetch channels
|
||||
const channels = await this.fetchChannels(extras);
|
||||
|
||||
// Fetch messages for each channel in parallel
|
||||
const channelMessagePromises = channels.map(async (channel) => {
|
||||
const messages = await this.fetchMessages(channel.id, extras);
|
||||
const parts = [
|
||||
`# Discord Channel: ${channel.name}`,
|
||||
...messages.map(
|
||||
(message) =>
|
||||
`- ${message.author.username}: ${message.content} (at ${message.timestamp})`,
|
||||
),
|
||||
];
|
||||
|
||||
return {
|
||||
name: `Messages from ${channel.name}`,
|
||||
content: parts.join("\n"),
|
||||
description: `Latest messages from the channel ${channel.name}`,
|
||||
};
|
||||
});
|
||||
|
||||
const channelMessageItems = await Promise.all(channelMessagePromises);
|
||||
result.push(...channelMessageItems);
|
||||
} catch (ex) {
|
||||
result.push({
|
||||
name: "Discord Error",
|
||||
content: this.handleApiError(ex),
|
||||
description: "Error fetching data from Discord.",
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export default DiscordContextProvider;
|
||||
168
core/context/providers/DiscordContextProvider.ts
Normal file
168
core/context/providers/DiscordContextProvider.ts
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
|
||||
// Define helper interfaces for Discord responses
|
||||
export interface DiscordChannel {
|
||||
id: string;
|
||||
name?: string; // Optional field
|
||||
icon?: string;
|
||||
topic?: string;
|
||||
type?: number;
|
||||
guild_id?: string; // The ID of the guild (server) that the channel belongs to
|
||||
}
|
||||
|
||||
interface DiscordMessage {
|
||||
id: string;
|
||||
content: string;
|
||||
author: {
|
||||
id: string;
|
||||
username: string;
|
||||
};
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
class DiscordContextProvider extends BaseContextProvider {
|
||||
// Description for the context provider
|
||||
static description: ContextProviderDescription = {
|
||||
title: "discord",
|
||||
displayTitle: "Discord",
|
||||
description: "Reference Discord messages from a channel",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
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!");
|
||||
}
|
||||
|
||||
return axios.create({
|
||||
baseURL: this.baseUrl,
|
||||
headers: {
|
||||
Authorization: `Bot ${token}`,
|
||||
"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 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}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
// Determine the channel ID from the selected channel (either from query or the first in the options)
|
||||
let channelId: string;
|
||||
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
|
||||
|
||||
// Prepare parts for rendering the message content
|
||||
const parts = ["# Discord Channel Messages", `Channel ID: ${channelId}`];
|
||||
const messages = await this.fetchMessages(channelId);
|
||||
|
||||
// Check if there are messages
|
||||
if (messages.length > 0) {
|
||||
parts.push("## Messages");
|
||||
|
||||
messages.forEach((message) => {
|
||||
// Log each message and the username to confirm access
|
||||
parts.push(
|
||||
`### ${message.author?.username ?? "Unknown User"} on ${
|
||||
message.timestamp
|
||||
}\n\n${message.content}`,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
parts.push("No messages found.");
|
||||
}
|
||||
|
||||
const content = parts.join("\n\n");
|
||||
|
||||
return [
|
||||
{
|
||||
name: `Messages from Channel ${channelId}`,
|
||||
content,
|
||||
description: "Latest messages from the channel",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// Submenu to load the list of channels
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const channels = await this.fetchChannels();
|
||||
|
||||
// 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
|
||||
description: channel.topic ?? "",
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export default DiscordContextProvider;
|
||||
|
|
@ -22,6 +22,7 @@ import SearchContextProvider from "./SearchContextProvider";
|
|||
import TerminalContextProvider from "./TerminalContextProvider";
|
||||
import URLContextProvider from "./URLContextProvider";
|
||||
import RepoMapContextProvider from "./RepoMapContextProvider";
|
||||
import DiscordContextProvider from "./DiscordContextProvider";
|
||||
|
||||
/**
|
||||
* Note: We are currently omitting the following providers due to bugs:
|
||||
|
|
@ -53,6 +54,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
|
|||
URLContextProvider,
|
||||
ContinueProxyContextProvider,
|
||||
RepoMapContextProvider,
|
||||
DiscordContextProvider,
|
||||
];
|
||||
|
||||
export function contextProviderClassFromName(
|
||||
|
|
|
|||
|
|
@ -1570,6 +1570,72 @@
|
|||
}
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["discord"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"discordKey": {
|
||||
"type": "string",
|
||||
"description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers."
|
||||
},
|
||||
"guildId": {
|
||||
"type": "string",
|
||||
"description": "The ID of the guild (server) from which to fetch channels and messages."
|
||||
},
|
||||
"channels": {
|
||||
"type": "array",
|
||||
"description": "A list of channel objects to search for messages",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "The unique ID of the channel"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "The name of the channel"
|
||||
}
|
||||
},
|
||||
"required": ["id"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["discordKey"]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"required": ["guildId"]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"required": ["channels"]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -2115,6 +2181,13 @@
|
|||
"minimum": 128,
|
||||
"exclusiveMaximum": 2147483647
|
||||
},
|
||||
"maxBatchSize": {
|
||||
"title": "Maximum Batch Size",
|
||||
"description": "The maximum number of chunks that can be sent to the embeddings provider in a single request",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"exclusiveMaximum": 2147483647
|
||||
},
|
||||
"region": {
|
||||
"title": "Region",
|
||||
"description": "The region where the model is hosted",
|
||||
|
|
|
|||
|
|
@ -1570,6 +1570,72 @@
|
|||
}
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["discord"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"discordKey": {
|
||||
"type": "string",
|
||||
"description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers."
|
||||
},
|
||||
"guildId": {
|
||||
"type": "string",
|
||||
"description": "The ID of the guild (server) from which to fetch channels and messages."
|
||||
},
|
||||
"channels": {
|
||||
"type": "array",
|
||||
"description": "A list of channel objects to search for messages",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "The unique ID of the channel"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "The name of the channel"
|
||||
}
|
||||
},
|
||||
"required": ["id"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["discordKey"]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"required": ["guildId"]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"required": ["channels"]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
|
|||
|
|
@ -1741,6 +1741,82 @@
|
|||
}
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"discord"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"discordKey": {
|
||||
"type": "string",
|
||||
"description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers."
|
||||
},
|
||||
"guildId": {
|
||||
"type": "string",
|
||||
"description": "The ID of the guild (server) from which to fetch channels and messages."
|
||||
},
|
||||
"channels": {
|
||||
"type": "array",
|
||||
"description": "A list of channel objects to search for messages",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "The unique ID of the channel"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "The name of the channel"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"discordKey"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"required": [
|
||||
"guildId"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"params": {
|
||||
"required": [
|
||||
"channels"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -2356,6 +2432,13 @@
|
|||
"minimum": 128,
|
||||
"exclusiveMaximum": 2147483647
|
||||
},
|
||||
"maxBatchSize": {
|
||||
"title": "Maximum Batch Size",
|
||||
"description": "The maximum number of chunks that can be sent to the embeddings provider in a single request",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"exclusiveMaximum": 2147483647
|
||||
},
|
||||
"region": {
|
||||
"title": "Region",
|
||||
"description": "The region where the model is hosted",
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue