Skip to content

Commit

Permalink
feat: update
Browse files Browse the repository at this point in the history
  • Loading branch information
supersonictw committed May 14, 2024
1 parent 75ba9b4 commit 527fd94
Show file tree
Hide file tree
Showing 29 changed files with 429 additions and 147 deletions.
9 changes: 9 additions & 0 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM mcr.microsoft.com/devcontainers/javascript-node:0-18
ARG MONGO_TOOLS_VERSION=6.0
RUN . /etc/os-release \
&& curl -sSL "https://www.mongodb.org/static/pgp/server-${MONGO_TOOLS_VERSION}.asc" | gpg --dearmor > /usr/share/keyrings/mongodb-archive-keyring.gpg \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/mongodb-archive-keyring.gpg] http://repo.mongodb.org/apt/debian ${VERSION_CODENAME}/mongodb-org/${MONGO_TOOLS_VERSION} main" | tee /etc/apt/sources.list.d/mongodb-org-${MONGO_TOOLS_VERSION}.list \
&& apt-get update && export DEBIAN_FRONTEND=noninteractive \
&& apt-get install -y mongodb-mongosh \
&& if [ "$(dpkg --print-architecture)" = "amd64" ]; then apt-get install -y mongodb-database-tools; fi \
&& apt-get clean -y && rm -rf /var/lib/apt/lists/*
15 changes: 15 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "Node.js & Mongo DB",
"dockerComposeFile": "docker-compose.yml",
"service": "app",
"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
"customizations": {
"vscode": {
"extensions": [
"mongodb.mongodb-vscode"
]
}
},
"forwardPorts": [3000, 3500, 8081],
"postCreateCommand": "npm install"
}
27 changes: 27 additions & 0 deletions .devcontainer/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
version: '3.8'

services:
app:
build:
context: .
dockerfile: Dockerfile
container_name: local-app
volumes:
- ../..:/workspaces:cached
command: sleep infinity
network_mode: service:mongo

mongo:
image: mongo:latest
container_name: local-mongo
restart: unless-stopped

express:
image: mongo-express:latest
container_name: local-express
restart: unless-stopped
environment:
ME_CONFIG_BASICAUTH_USERNAME: developer
ME_CONFIG_BASICAUTH_PASSWORD: developer
ME_CONFIG_MONGODB_SERVER: local-mongo
network_mode: service:mongo
16 changes: 11 additions & 5 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
# node env ('production' or 'development')
NODE_ENV="development"

# general
MONGODB_URI="mongodb://local-mongo:27017/app"
GOOGLE_AI_API_KEY="your_google_ai_api_key"

# discord integration
DISCORD_APP_ID="00000"
DISCORD_BOT_TOKEN="your_discord_bot_token"

DISCORD_GUILD_ID="00000"
DISCORD_ROLE_ID_ADMIN="00000"
DISCORD_CHANNEL_ID_TERMINAL="00000"
DISCORD_GUILD_ROLE_ID_ADMIN="00000"
DISCORD_GUILD_CHANNEL_ID_TERMINAL="00000"

# matrix integration
MATRIX_HOMESERVER="https://matrix.org"
MATRIX_USERNAME="your_matrix_username" # e.g. @nymph57021218:matrix.org
MATRIX_PASSWORD="your_matrix_password"
MATRIX_ACCESS_TOKEN="your_matrix_access_token"

GOOGLE_AI_API_KEY="your_google_ai_api_key"
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ prompts.json
relay.json
roles.json

# App data files
data/

# Finder config file
.DS_Store

Expand Down
32 changes: 21 additions & 11 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
"use strict";

require("dotenv").config();
const {
runLoader,
getMust,
} = require("./src/config");
const {
prepare,
} = require("./src/clients/database");

const runners = [];
runLoader();

if (process.env.MATRIX_ACCESS_TOKEN) {
const runners = [];
if (getMust("MATRIX_ACCESS_TOKEN")) {
runners.push(require("./src/matrix"));
}
if (process.env.DISCORD_BOT_TOKEN) {
if (getMust("DISCORD_BOT_TOKEN")) {
runners.push(require("./src/discord"));
}

Promise.all(runners.map(
(runner) => runner(),
)).then(() => {
console.info("Nymph 系統 成功啟動");
}).catch((e) => {
console.error("Nymph 系統 啟動失敗:", e);
});
(async () => {
await prepare();
await Promise.all(runners.map(
(runner) => runner(),
)).then(() => {
console.info("Nymph 系統 成功啟動");
}).catch((e) => {
console.error("Nymph 系統 啟動失敗:", e);
});
})();
33 changes: 0 additions & 33 deletions matrix_access.js
Original file line number Diff line number Diff line change
@@ -1,33 +0,0 @@
"use strict";

require("dotenv").config();

const {
createClient,
} = require("matrix-js-sdk");

const {
MATRIX_HOMESERVER: homeserverUrl,
MATRIX_USERNAME: username,
MATRIX_PASSWORD: password,
} = process.env;

console.info(
"Get the AccessToken from Matrix",
`(homeserver: ${homeserverUrl || "undefined"})`,
"\n",
);

const client = createClient({baseUrl: homeserverUrl});
client.login("m.login.password", {
identifier: {
type: "m.id.user",
user: username,
},
password,
}).then((response) => {
console.info("UserId:", response.user_id);
console.info("AccessToken:", response.access_token);
}).catch((e) => {
console.error("Unauthorized", e);
});
5 changes: 5 additions & 0 deletions nodemon.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"ignore": [
"data"
]
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@
"dependencies": {
"@discordjs/rest": "^2.2.0",
"@google/generative-ai": "^0.2.1",
"@matrix-org/matrix-sdk-crypto-nodejs": "^0.1.0-beta.12",
"discord-api-types": "^0.37.65",
"discord.js": "^14.14.1",
"discordjs-reaction-role": "^3.1.0",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"matrix-js-sdk": "^32.1.0"
"matrix-bot-sdk": "^0.7.1",
"mongoose": "^8.3.4"
},
"devDependencies": {
"@commitlint/cli": "^17.6.5",
Expand Down
8 changes: 5 additions & 3 deletions register_commands.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"use strict";

require("dotenv").config();
const {
getMust,
} = require("./src/config");

const {useRestClient} = require("./src/clients/discord");
const {Routes} = require("discord-api-types/v9");
Expand Down Expand Up @@ -30,8 +32,8 @@ console.info(commands);

await client.put(
Routes.applicationGuildCommands(
process.env.DISCORD_APP_ID,
process.env.GUILD_ID,
getMust("DISCORD_APP_ID"),
getMust("DISCORD_GUILD_ID"),
),
{body: commands},
);
Expand Down
2 changes: 1 addition & 1 deletion relay.sample.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
{
"name": "Arona",
"discordChannelId": "996069746514612235",
"matrixRoomId": "#line:matrix.org"
"matrixRoomId": "!yTRzUDNyviBhrMwYGG:matrix.org"
}
]
10 changes: 3 additions & 7 deletions src/bridges/discord_matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@

const discord = require("discord.js");

const {
MsgType,
} = require("matrix-js-sdk");

const {
useClient,
} = require("../clients/matrix");
Expand All @@ -15,15 +11,15 @@ const {
find,
} = require("./utils");

const client = useClient();

/**
* This function is called when a message is created in Discord.
*
* @param {discord.Message} message
* @return {void}
*/
module.exports = async (message) => {
const client = await useClient();

const {channelId} = message;

const relayTarget = find("discordChannelId", channelId);
Expand All @@ -38,7 +34,7 @@ module.exports = async (message) => {
const {content: text} = message;

await client.sendMessage(roomId, {
msgtype: MsgType.Text,
msgtype: "m.text",
format: "plain/text",
body: `${username} ⬗ Discord\n${text}`,
});
Expand Down
20 changes: 6 additions & 14 deletions src/bridges/matrix_discord.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
"use strict";
// Trasnfer messages from Discord to Matrix.

const {
RoomEvent,
Room,
} = require("matrix-js-sdk");

const {
useClient,
} = require("../clients/discord");
Expand All @@ -14,18 +9,15 @@ const {
find,
} = require("./utils");

const client = useClient();

/**
* This function is called when a new event is added to the timeline of a room.
*
* @param {RoomEvent} roomEvent - The event that triggered this function.
* @param {Room} room - The room that the event was sent in.
* @param {Date} _toStartOfTimeline - The date of the first event.
* @param {string} roomId - The room that the event was sent in.
* @param {any} event - The event that triggered this function.
* @return {void}
*/
module.exports = async (roomEvent, room, _toStartOfTimeline) => {
const {roomId} = room;
module.exports = async (roomId, event) => {
const client = await useClient();

const relayTarget = find("matrixRoomId", roomId);
if (!relayTarget) {
Expand All @@ -35,8 +27,8 @@ module.exports = async (roomEvent, room, _toStartOfTimeline) => {
discordChannelId: channelId,
} = relayTarget;

const {sender: username} = roomEvent.event;
const {body: text} = roomEvent.event.content;
const {sender: username, content} = event;
const {body: text} = content;

const channel = await client.channels.fetch(channelId);
await channel.send(`\`${username}\` ⬗ Matrix\n${text}`);
Expand Down
18 changes: 18 additions & 0 deletions src/clients/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"use strict";
// mongoose is an ODM library for MongoDB.

// Import config
const {getMust} = require("../config");

// Import mongoose
const database = require("mongoose");

// Configure mongose
database.set("strictQuery", true);

// Connect to MongoDB
exports.prepare = () =>
database.connect(getMust("MONGODB_URI"));

// Export as useFunction
exports.useDatabase = () => database;
20 changes: 15 additions & 5 deletions src/clients/discord.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
"use strict";
// Discord is a proprietary instant messaging platform.

const {
getMust,
} = require("../config");

const {
REST,
} = require("@discordjs/rest");
Expand All @@ -11,7 +15,9 @@ const {
GatewayIntentBits,
} = require("discord.js");

const newClient = () => {
const botToken = getMust("DISCORD_BOT_TOKEN");

const newClient = async () => {
const client = new Client({
partials: [
Partials.Channel,
Expand All @@ -28,28 +34,32 @@ const newClient = () => {
GatewayIntentBits.MessageContent,
],
});
client.login(process.env.DISCORD_BOT_TOKEN);
client.login(botToken);
return client;
};

/**
* The cached client.
* @type {Client|undefined}
*/
let client;
/**
* Use Discord client
*
* @param {boolean} cached - Use the cached client
* @return {Client} - The client
*/
exports.useClient = (cached = true) => {
exports.useClient = async (cached = true) => {
if (cached && client) {
return client;
}
client = newClient();
client = await newClient();
return client;
};

exports.useRestClient = () => {
const restClient = new REST({version: "10"});
restClient.setToken(process.env.DISCORD_BOT_TOKEN);
restClient.setToken(botToken);
return restClient;
};

Expand Down
3 changes: 2 additions & 1 deletion src/clients/gemini.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"use strict";
// Gemini is a generative AI model developed by Google.

const {getMust} = require("../config");
const {GoogleGenerativeAI} = require("@google/generative-ai");

const client = new GoogleGenerativeAI(process.env.GOOGLE_AI_API_KEY);
const client = new GoogleGenerativeAI(getMust("GOOGLE_AI_API_KEY"));
const model = client.getGenerativeModel({model: "gemini-pro"});

const chatSessions = {};
Expand Down
Loading

0 comments on commit 527fd94

Please sign in to comment.