bump: sern version 3 (#39)

This commit is contained in:
Jacob Nguyen
2024-01-13 18:06:23 -06:00
committed by GitHub
10 changed files with 155 additions and 70 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "sern-community",
"version": "2.0.0",
"version": "3.0.0",
"description": "",
"main": "dist/src/index.js",
"type": "module",
@@ -28,7 +28,7 @@
"license": "MIT",
"dependencies": {
"@octokit/rest": "19.0.7",
"@sern/handler": "2.6.2",
"@sern/handler": "^3.3.2",
"discord.js": "14.9.0",
"dotenv": "16.0.3",
"jsdoc-parse-plus": "1.3.0",

View File

@@ -1,11 +1,10 @@
import { publish } from "#plugins";
import { CommandType, commandModule } from "@sern/handler";
import { CommandType, Service, commandModule } from "@sern/handler";
import { ApplicationCommandOptionType } from "discord.js";
import { Timestamp } from "#utils";
import { Emojis } from "#constants";
import { useContainer } from "../index.js";
const prefix = (t: unknown) => (t ? "$" : "#");
const octokit = Service('octokit');
export default commandModule({
type: CommandType.Slash,
description: "Get info about a PR or issue",
@@ -20,8 +19,6 @@ export default commandModule({
command: {
onEvent: [],
async execute(ctx) {
const [octokit] = useContainer("octokit");
const text = ctx.options.getFocused();
const org = await octokit.repos.listForOrg({
org: "sern-handler",
@@ -62,7 +59,6 @@ export default commandModule({
command: {
onEvent: [],
async execute(ctx) {
const [octokit] = useContainer("octokit");
const text = ctx.options.getFocused();
const repo = ctx.options.getString("repo");
@@ -120,7 +116,6 @@ export default commandModule({
},
],
async execute(ctx, [, options]) {
const [octokit] = useContainer("octokit");
const repo = options.getString("repo", true);
const number = options.getInteger("number", true);

20
src/dependencies.d.ts vendored Normal file
View File

@@ -0,0 +1,20 @@
/**
* This file serves as intellisense for sern projects.
* Types are declared here for dependencies to function properly
* Service(s) api rely on this file to provide a better developer experience.
*/
import type { SernEmitter, Logging, CoreModuleStore, ModuleManager, ErrorHandling, CoreDependencies, Singleton } from '@sern/handler'
import type { Client } from 'discord.js'
import type { SernLogger } from './utils/Logger';
import type { Octokit } from '@octokit/rest'
declare global {
interface Dependencies extends Dependencies {
"@sern/client": Singleton<Client>;
"@sern/logger": Singleton<SernLogger>;
octokit: Singleton<Octokit>;
}
}
export {}

View File

@@ -1,6 +1,5 @@
import { eventModule, EventType } from "@sern/handler";
import { eventModule, EventType, Service } from "@sern/handler";
import type { GuildMember } from "discord.js";
import { useContainer } from "../index.js";
export default eventModule({
type: EventType.Discord,
@@ -8,7 +7,7 @@ export default eventModule({
async execute(member: GuildMember) {
// TODO: This should be inferred
if (member.pending) return;
const [logger] = useContainer("@sern/logger");
const logger = Service("@sern/logger");
logger.info({ message: `${member.user.username} joined` });
const requiredRoles = ["980118655738212407"];
await member.roles.add(requiredRoles);

View File

@@ -5,15 +5,15 @@ import {
EventType,
Payload,
PayloadType,
Service,
} from "@sern/handler";
import { useContainer } from "../index.js";
export default eventModule({
name: "module.activate",
type: EventType.Sern,
plugins: [filterFailedActivation()],
execute(payload: Payload & { type: PayloadType.Failure }) {
const [logger] = useContainer("@sern/logger");
const logger = Service("@sern/logger");
logger.warning({
message: `A module (${payload.module?.name} failed to execute: ${payload.reason}`,
});

View File

@@ -1,7 +1,7 @@
import { Client, GatewayIntentBits, Partials } from "discord.js";
import { Dependencies, Sern, single, Singleton } from "@sern/handler";
import "dotenv/config";
import { randomStatus, SernLogger /*CommandSyncer*/ } from "#utils";
import { Client, GatewayIntentBits, Partials } from "discord.js";
import { Sern, single, makeDependencies, Service } from "@sern/handler";
import { SernLogger } from "#utils";
import { Octokit } from "@octokit/rest";
import { cp } from "./commands/refresh.js";
@@ -21,39 +21,25 @@ const client = new Client({
},
});
export interface BotDependencies extends Dependencies {
"@sern/client": Singleton<Client>;
"@sern/logger": Singleton<SernLogger>;
octokit: Singleton<Octokit>;
}
export const useContainer = Sern.makeDependencies<BotDependencies>({
build: (root) =>
root
.add({ "@sern/client": single(() => client) })
.upsert({ "@sern/logger": single(() => new SernLogger("info")) })
.add({ process: single(() => process) })
.add({
octokit: single(() => new Octokit({ auth: process.env.GITHUB_TOKEN })),
}),
// .add(ctx =>
// ({'sync' : single(() => new CommandSyncer(ctx['@sern/logger'], ctx['@sern/client'], ["941002690211766332"]))}
// ))
});
await makeDependencies({
build: (root) =>
root.add({ "@sern/client": () => client })
.upsert({ "@sern/logger": () => new SernLogger("info") })
.add({ process: () => process,
octokit: () => new Octokit({ auth: process.env.GITHUB_TOKEN }) })
});
Sern.init({
defaultPrefix: "sern",
commands: "dist/src/commands",
events: "dist/src/events",
containerConfig: {
get: useContainer,
},
defaultPrefix: "sern",
commands: "dist/src/commands",
events: "dist/src/events",
});
client.once("ready", async (client) => {
randomStatus(client);
const [logger] = useContainer("@sern/logger");
logger.info({ message: `[✅]: Logged in as ${client.user.username}` });
await cp();
const logger = Service("@sern/logger");
logger.info({ message: `[✅]: Logged in as ${client.user.username}` });
await cp();
});
await client.login();
await client.login(process.env.DISCORD_TOKEN);

View File

@@ -1,6 +1,7 @@
// @ts-nocheck
/**
* This is publish plugin, it allows you to publish your application commands using the discord.js library with ease.
* @plugin
* [DEPRECATED] It allows you to publish your application commands using the discord.js library with ease.
*
* @author @EvolutionX-10 [<@697795666373640213>]
* @version 2.0.0
@@ -16,6 +17,7 @@
* }
* })
* ```
* @end
*/
import {
CommandInitPlugin,
@@ -23,9 +25,14 @@ import {
controller,
SernOptionsData,
SlashCommand,
Service,
} from "@sern/handler";
import { ApplicationCommandData, ApplicationCommandType, PermissionResolvable } from "discord.js";
import { useContainer } from "../index.js";
import {
ApplicationCommandData,
ApplicationCommandType,
ApplicationCommandOptionType,
PermissionResolvable,
} from "discord.js";
export const CommandTypeRaw = {
[CommandType.Both]: ApplicationCommandType.ChatInput,
@@ -35,18 +42,29 @@ export const CommandTypeRaw = {
} as const;
export function publish<
T extends CommandType.Both | CommandType.Slash | CommandType.CtxMsg | CommandType.CtxUser
T extends
| CommandType.Both
| CommandType.Slash
| CommandType.CtxMsg
| CommandType.CtxUser,
>(options?: PublishOptions) {
return CommandInitPlugin<T>(async ({ module }) => {
// Users need to provide their own useContainer function.
const [client] = useContainer("@sern/client");
let client;
try {
client = (await import("@sern/handler")).Service("@sern/client");
} catch {
const { useContainer } = await import("../index.js");
client = useContainer("@sern/client")[0];
}
const defaultOptions = {
guildIds: [],
dmPermission: undefined,
defaultMemberPermissions: null,
};
options = { ...defaultOptions, ...options } as PublishOptions & ValidPublishOptions;
options = { ...defaultOptions, ...options } as PublishOptions &
ValidPublishOptions;
let { defaultMemberPermissions, dmPermission, guildIds } =
options as unknown as ValidPublishOptions;
@@ -78,7 +96,10 @@ export function publish<
name: module.name,
type: curAppType,
description: cmd(module.description, ""),
options: cmd(optionsTransformer((module as SlashCommand).options ?? []), []),
options: cmd(
optionsTransformer((module as SlashCommand).options ?? []),
[],
),
defaultMemberPermissions,
dmPermission,
} as ApplicationCommandData;
@@ -89,12 +110,18 @@ export function publish<
if (!guildIds.length) {
const cmd = (await client.application!.commands.fetch()).find(
(c) => c.name === module.name && c.type === curAppType
(c) => c.name === module.name && c.type === curAppType,
);
if (cmd) {
if (!cmd.equals(commandData, true)) {
logged(`Found differences in global command ${module.name}`);
cmd.edit(commandData).then(log(`${module.name} updated with new data successfully!`));
logged(
`Found differences in global command ${module.name}`,
);
cmd.edit(commandData).then(
log(
`${module.name} updated with new data successfully!`,
),
);
}
return controller.next();
}
@@ -109,14 +136,18 @@ export function publish<
const guild = await client.guilds.fetch(id).catch(c);
if (!guild) continue;
const guildCmd = (await guild.commands.fetch()).find(
(c) => c.name === module.name && c.type === curAppType
(c) => c.name === module.name && c.type === curAppType,
);
if (guildCmd) {
if (!guildCmd.equals(commandData, true)) {
logged(`Found differences in command ${module.name}`);
guildCmd
.edit(commandData)
.then(log(`${module.name} updated with new data successfully!`))
.then(
log(
`${module.name} updated with new data successfully!`,
),
)
.catch(c);
continue;
}
@@ -137,7 +168,19 @@ export function publish<
}
export function optionsTransformer(ops: Array<SernOptionsData>) {
return ops.map((el) => (el.autocomplete ? (({ command, ...el }) => el)(el) : el));
return ops.map((el) => {
switch (el.type) {
case ApplicationCommandOptionType.String:
case ApplicationCommandOptionType.Number:
case ApplicationCommandOptionType.Integer: {
return el.autocomplete && "command" in el
? (({ command, ...el }) => el)(el)
: el;
}
default:
return el;
}
});
}
export type NonEmptyArray<T extends `${number}` = `${number}`> = [T, ...T[]];

34
src/presence.ts Normal file
View File

@@ -0,0 +1,34 @@
import { Presence } from '@sern/handler'
import { ActivityType, ClientPresenceStatus } from 'discord.js';
function shuffleArray<T>(array: T[]) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return [...array];
}
const statuses =[[ActivityType.Watching, "the sern community", "online"],
[ActivityType.Listening, "Evo", "dnd"],
[ActivityType.Playing, "with @sern/cli", "idle"],
[ActivityType.Watching, "sern bots", "dnd"],
[ActivityType.Watching, "github stars go brrr", "online"],
[ActivityType.Listening, "Spotify", "dnd"],
[ActivityType.Listening, "what's bofa", "idle"]] satisfies
[ActivityType, string, ClientPresenceStatus][];
export default Presence.module({
execute: () => {
const [type, name, status] = statuses.at(0)!;
return Presence
.of({ activities: [ { type, name } ], status }) //start your presence with this.
.repeated(() => {
const [type, name, status] = [...shuffleArray(statuses)].shift()!;
return {
status,
activities: [{ type, name }]
};
}, 60_000); //repeat and setPresence with returned result every minute
}
})

View File

@@ -6,7 +6,7 @@
},
{
"name": "Outdated Node",
"content": "Your nodejs version is outdated, update it to 16.9 or higher",
"content": "Your nodejs version is outdated, update it to 18.0 or higher",
"keywords": ["'node:events'", "upgrade your node", "your node is outdated"]
},
{

View File

@@ -440,14 +440,15 @@ __metadata:
languageName: node
linkType: hard
"@sern/handler@npm:2.6.2":
version: 2.6.2
resolution: "@sern/handler@npm:2.6.2"
"@sern/handler@npm:^3.3.2":
version: 3.3.2
resolution: "@sern/handler@npm:3.3.2"
dependencies:
callsites: ^3.1.0
iti: ^0.6.0
rxjs: ^7.8.0
ts-results-es: ^3.6.0
checksum: 3c86047f09dc0e77044371e8964977e59521966a5ad080f8459dc9d0c02027c11c4ef86245b29a9b6e0122d665e508446f3daa30a2b81e426495b30d1b5e555e
ts-results-es: ^4.0.0
checksum: a405f9f4e914245dc0c0a9091508871a2cdbb50947a71797ec4faa64ba0ec775dc8b9aa0f116c4699752520ca4b5f54b624898d7da0f53375e4534a698d0c3d4
languageName: node
linkType: hard
@@ -689,6 +690,13 @@ __metadata:
languageName: node
linkType: hard
"callsites@npm:^3.1.0":
version: 3.1.0
resolution: "callsites@npm:3.1.0"
checksum: 072d17b6abb459c2ba96598918b55868af677154bec7e73d222ef95a8fdb9bbf7dae96a8421085cdad8cd190d86653b5b6dc55a4484f2e5b2e27d5e0c3fc15b3
languageName: node
linkType: hard
"chokidar@npm:^3.5.1":
version: 3.5.3
resolution: "chokidar@npm:3.5.3"
@@ -2047,7 +2055,7 @@ __metadata:
resolution: "sern-community@workspace:."
dependencies:
"@octokit/rest": 19.0.7
"@sern/handler": 2.6.2
"@sern/handler": ^3.3.2
"@types/node": 18.16.3
"@types/string-similarity": 4.0.0
discord.js: 14.9.0
@@ -2351,10 +2359,10 @@ __metadata:
languageName: node
linkType: hard
"ts-results-es@npm:^3.6.0":
version: 3.6.0
resolution: "ts-results-es@npm:3.6.0"
checksum: 28593545cad764efce2de64b09037f855c3bbd499e3f5e2683863c86abc9b4453e5aa7d651edff93d42340a2c24f8bbabcf92467fcec767e09bbeeac01e97396
"ts-results-es@npm:^4.0.0":
version: 4.0.0
resolution: "ts-results-es@npm:4.0.0"
checksum: 32a7059491e36d06c5a1084fe9be8021a0beb2d94a94b0c3fa85dc3e96561bf34fb8fd60ebe661064c9fc2bafcf437b6b65f119e8d7497af7f76cda9d9a2a945
languageName: node
linkType: hard