@vectorstores/discord 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) vectorstores contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,93 @@
1
+ Object.defineProperty(exports, '__esModule', { value: true });
2
+
3
+ var rest = require('@discordjs/rest');
4
+ var core = require('@vectorstores/core');
5
+ var env = require('@vectorstores/env');
6
+ var v10 = require('discord-api-types/v10');
7
+
8
+ /**
9
+ * Represents a reader for Discord messages using @discordjs/rest
10
+ * See https://github.com/discordjs/discord.js/tree/main/packages/rest
11
+ */ class DiscordReader {
12
+ constructor(discordToken, requestHandler){
13
+ const token = discordToken ?? env.getEnv("DISCORD_TOKEN");
14
+ if (!token) {
15
+ throw new Error("Must specify `discordToken` or set environment variable `DISCORD_TOKEN`.");
16
+ }
17
+ const restOptions = {
18
+ version: "10"
19
+ };
20
+ // Use the provided request handler if specified
21
+ if (requestHandler) {
22
+ restOptions.makeRequest = requestHandler;
23
+ }
24
+ this.client = new rest.REST(restOptions).setToken(token);
25
+ }
26
+ // Read all messages in a channel given a channel ID
27
+ async readChannel(channelId, limit, additionalInfo, oldestFirst) {
28
+ const params = new URLSearchParams();
29
+ if (limit) params.append("limit", limit.toString());
30
+ if (oldestFirst) params.append("after", "0");
31
+ try {
32
+ const endpoint = `${v10.Routes.channelMessages(channelId)}?${params}`;
33
+ const messages = await this.client.get(endpoint);
34
+ return messages.map((msg)=>this.createDocumentFromMessage(msg, additionalInfo));
35
+ } catch (err) {
36
+ console.error(err);
37
+ return [];
38
+ }
39
+ }
40
+ createDocumentFromMessage(msg, additionalInfo) {
41
+ let content = msg.content || "";
42
+ // Include information from embedded messages
43
+ if (additionalInfo && msg.embeds.length > 0) {
44
+ content += "\n" + msg.embeds.map((embed)=>this.embedToString(embed)).join("\n");
45
+ }
46
+ // Include URL from attachments
47
+ if (additionalInfo && msg.attachments.length > 0) {
48
+ content += "\n" + msg.attachments.map((attachment)=>`Attachment: ${attachment.url}`).join("\n");
49
+ }
50
+ return new core.Document({
51
+ text: content,
52
+ id_: msg.id,
53
+ metadata: {
54
+ messageId: msg.id,
55
+ username: msg.author.username,
56
+ createdAt: new Date(msg.timestamp).toISOString(),
57
+ editedAt: msg.edited_timestamp ? new Date(msg.edited_timestamp).toISOString() : undefined
58
+ }
59
+ });
60
+ }
61
+ // Create a string representation of an embedded message
62
+ embedToString(embed) {
63
+ let result = "***Embedded Message***\n";
64
+ if (embed.title) result += `**${embed.title}**\n`;
65
+ if (embed.description) result += `${embed.description}\n`;
66
+ if (embed.url) result += `${embed.url}\n`;
67
+ if (embed.fields) {
68
+ result += embed.fields.map((field)=>`**${field.name}**: ${field.value}`).join("\n");
69
+ }
70
+ return result.trim();
71
+ }
72
+ /**
73
+ * Loads messages from multiple discord channels and returns an array of Document Objects.
74
+ *
75
+ * @param {string[]} channelIds - An array of channel IDs from which to load data.
76
+ * @param {number} [limit] - An optional limit on the number of messages to load per channel.
77
+ * @param {boolean} [additionalInfo] - An optional flag to include content from embedded messages and attachments urls as text.
78
+ * @param {boolean} [oldestFirst] - An optional flag to load oldest messages first.
79
+ * @return {Promise<Document[]>} A promise that resolves to an array of loaded documents.
80
+ */ async loadData(channelIds, limit, additionalInfo, oldestFirst) {
81
+ let results = [];
82
+ for (const channelId of channelIds){
83
+ if (typeof channelId !== "string") {
84
+ throw new Error(`Channel id ${channelId} must be a string.`);
85
+ }
86
+ const channelDocuments = await this.readChannel(channelId, limit, additionalInfo, oldestFirst);
87
+ results = results.concat(channelDocuments);
88
+ }
89
+ return results;
90
+ }
91
+ }
92
+
93
+ exports.DiscordReader = DiscordReader;
@@ -0,0 +1,26 @@
1
+ import { RESTOptions } from '@discordjs/rest';
2
+ import { BaseReader, Document } from '@vectorstores/core';
3
+
4
+ /**
5
+ * Represents a reader for Discord messages using @discordjs/rest
6
+ * See https://github.com/discordjs/discord.js/tree/main/packages/rest
7
+ */
8
+ declare class DiscordReader implements BaseReader {
9
+ private client;
10
+ constructor(discordToken?: string, requestHandler?: RESTOptions["makeRequest"]);
11
+ private readChannel;
12
+ private createDocumentFromMessage;
13
+ private embedToString;
14
+ /**
15
+ * Loads messages from multiple discord channels and returns an array of Document Objects.
16
+ *
17
+ * @param {string[]} channelIds - An array of channel IDs from which to load data.
18
+ * @param {number} [limit] - An optional limit on the number of messages to load per channel.
19
+ * @param {boolean} [additionalInfo] - An optional flag to include content from embedded messages and attachments urls as text.
20
+ * @param {boolean} [oldestFirst] - An optional flag to load oldest messages first.
21
+ * @return {Promise<Document[]>} A promise that resolves to an array of loaded documents.
22
+ */
23
+ loadData(channelIds: string[], limit?: number, additionalInfo?: boolean, oldestFirst?: boolean): Promise<Document[]>;
24
+ }
25
+
26
+ export { DiscordReader };
package/dist/index.js ADDED
@@ -0,0 +1,91 @@
1
+ import { REST } from '@discordjs/rest';
2
+ import { Document } from '@vectorstores/core';
3
+ import { getEnv } from '@vectorstores/env';
4
+ import { Routes } from 'discord-api-types/v10';
5
+
6
+ /**
7
+ * Represents a reader for Discord messages using @discordjs/rest
8
+ * See https://github.com/discordjs/discord.js/tree/main/packages/rest
9
+ */ class DiscordReader {
10
+ constructor(discordToken, requestHandler){
11
+ const token = discordToken ?? getEnv("DISCORD_TOKEN");
12
+ if (!token) {
13
+ throw new Error("Must specify `discordToken` or set environment variable `DISCORD_TOKEN`.");
14
+ }
15
+ const restOptions = {
16
+ version: "10"
17
+ };
18
+ // Use the provided request handler if specified
19
+ if (requestHandler) {
20
+ restOptions.makeRequest = requestHandler;
21
+ }
22
+ this.client = new REST(restOptions).setToken(token);
23
+ }
24
+ // Read all messages in a channel given a channel ID
25
+ async readChannel(channelId, limit, additionalInfo, oldestFirst) {
26
+ const params = new URLSearchParams();
27
+ if (limit) params.append("limit", limit.toString());
28
+ if (oldestFirst) params.append("after", "0");
29
+ try {
30
+ const endpoint = `${Routes.channelMessages(channelId)}?${params}`;
31
+ const messages = await this.client.get(endpoint);
32
+ return messages.map((msg)=>this.createDocumentFromMessage(msg, additionalInfo));
33
+ } catch (err) {
34
+ console.error(err);
35
+ return [];
36
+ }
37
+ }
38
+ createDocumentFromMessage(msg, additionalInfo) {
39
+ let content = msg.content || "";
40
+ // Include information from embedded messages
41
+ if (additionalInfo && msg.embeds.length > 0) {
42
+ content += "\n" + msg.embeds.map((embed)=>this.embedToString(embed)).join("\n");
43
+ }
44
+ // Include URL from attachments
45
+ if (additionalInfo && msg.attachments.length > 0) {
46
+ content += "\n" + msg.attachments.map((attachment)=>`Attachment: ${attachment.url}`).join("\n");
47
+ }
48
+ return new Document({
49
+ text: content,
50
+ id_: msg.id,
51
+ metadata: {
52
+ messageId: msg.id,
53
+ username: msg.author.username,
54
+ createdAt: new Date(msg.timestamp).toISOString(),
55
+ editedAt: msg.edited_timestamp ? new Date(msg.edited_timestamp).toISOString() : undefined
56
+ }
57
+ });
58
+ }
59
+ // Create a string representation of an embedded message
60
+ embedToString(embed) {
61
+ let result = "***Embedded Message***\n";
62
+ if (embed.title) result += `**${embed.title}**\n`;
63
+ if (embed.description) result += `${embed.description}\n`;
64
+ if (embed.url) result += `${embed.url}\n`;
65
+ if (embed.fields) {
66
+ result += embed.fields.map((field)=>`**${field.name}**: ${field.value}`).join("\n");
67
+ }
68
+ return result.trim();
69
+ }
70
+ /**
71
+ * Loads messages from multiple discord channels and returns an array of Document Objects.
72
+ *
73
+ * @param {string[]} channelIds - An array of channel IDs from which to load data.
74
+ * @param {number} [limit] - An optional limit on the number of messages to load per channel.
75
+ * @param {boolean} [additionalInfo] - An optional flag to include content from embedded messages and attachments urls as text.
76
+ * @param {boolean} [oldestFirst] - An optional flag to load oldest messages first.
77
+ * @return {Promise<Document[]>} A promise that resolves to an array of loaded documents.
78
+ */ async loadData(channelIds, limit, additionalInfo, oldestFirst) {
79
+ let results = [];
80
+ for (const channelId of channelIds){
81
+ if (typeof channelId !== "string") {
82
+ throw new Error(`Channel id ${channelId} must be a string.`);
83
+ }
84
+ const channelDocuments = await this.readChannel(channelId, limit, additionalInfo, oldestFirst);
85
+ results = results.concat(channelDocuments);
86
+ }
87
+ return results;
88
+ }
89
+ }
90
+
91
+ export { DiscordReader };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@vectorstores/discord",
3
+ "description": "Discord Reader for vectorstores",
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "types": "dist/index.d.ts",
7
+ "main": "dist/index.cjs",
8
+ "module": "dist/index.js",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/schiesser/vectorstores.git",
21
+ "directory": "packages/providers/discord"
22
+ },
23
+ "devDependencies": {
24
+ "@vectorstores/core": "0.1.0",
25
+ "@vectorstores/env": "0.1.0"
26
+ },
27
+ "peerDependencies": {
28
+ "@vectorstores/core": "0.1.0",
29
+ "@vectorstores/env": "0.1.0"
30
+ },
31
+ "dependencies": {
32
+ "@discordjs/rest": "^2.3.0",
33
+ "discord-api-types": "^0.37.105"
34
+ },
35
+ "scripts": {
36
+ "build": "bunchee",
37
+ "dev": "bunchee --watch"
38
+ }
39
+ }