style: format (#2925)

This commit is contained in:
ITOH
2023-04-01 02:46:46 +02:00
committed by GitHub
parent 4d3a2f7665
commit 05fc3fbeba
85 changed files with 670 additions and 828 deletions

View File

@@ -1,36 +1,32 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.245.0/containers/typescript-node // https://github.com/microsoft/vscode-dev-containers/tree/v0.245.0/containers/typescript-node
{ {
"name": "Node.js & TypeScript", "name": "Node.js & TypeScript",
"build": { "build": {
"dockerfile": "Dockerfile", "dockerfile": "Dockerfile",
// Update 'VARIANT' to pick a Node version: 18, 16, 14. // Update 'VARIANT' to pick a Node version: 18, 16, 14.
// Append -bullseye or -buster to pin to an OS version. // Append -bullseye or -buster to pin to an OS version.
// Use -bullseye variants on local on arm64/Apple Silicon. // Use -bullseye variants on local on arm64/Apple Silicon.
"args": { "args": {
"VARIANT": "18-bullseye" "VARIANT": "18-bullseye"
} }
}, },
// Configure tool-specific properties. // Configure tool-specific properties.
"customizations": { "customizations": {
// Configure properties specific to VS Code. // Configure properties specific to VS Code.
"vscode": { "vscode": {
// Add the IDs of extensions you want installed when the container is created. // Add the IDs of extensions you want installed when the container is created.
"extensions": [ "extensions": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode", "TabNine.tabnine-vscode"]
"dbaeumer.vscode-eslint", }
"esbenp.prettier-vscode", },
"TabNine.tabnine-vscode"
]
}
},
// Use 'forwardPorts' to make a list of ports inside the container available locally. // Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [], // "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created. // Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "yarn install", // "postCreateCommand": "yarn install",
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "node", "remoteUser": "node"
} }

View File

@@ -1,7 +1,5 @@
{ {
"root": true, "root": true,
// This tells ESLint to load the config from the package `eslint-config-custom` // This tells ESLint to load the config from the package `eslint-config-custom`
"extends": [ "extends": ["discordeno"]
"discordeno" }
]
}

View File

@@ -18,7 +18,7 @@ jobs:
node-version: 18 node-version: 18
- uses: denoland/setup-deno@main - uses: denoland/setup-deno@main
with: with:
deno-version: "v1.29" deno-version: 'v1.29'
- name: Get yarn cache directory path - name: Get yarn cache directory path
id: yarn-cache-dir-path id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT

View File

@@ -18,14 +18,14 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
package: ["gateway", "rest", "types", "utils", "bot"] package: ['gateway', 'rest', 'types', 'utils', 'bot']
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: 18 node-version: 18
registry-url: "https://registry.npmjs.org" registry-url: 'https://registry.npmjs.org'
scope: "@discordeno" scope: '@discordeno'
- name: Get yarn cache directory path - name: Get yarn cache directory path
id: yarn-cache-dir-path id: yarn-cache-dir-path
run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT

View File

@@ -6,23 +6,23 @@ name: Deploy Docs Site
on: on:
# Triggers the workflow on push or pull request events but only for the "main" branch # Triggers the workflow on push or pull request events but only for the "main" branch
push: push:
branches: ["main"] branches: ['main']
paths: paths:
- "website/**" - 'website/**'
- ".github/workflows/site.yml" - '.github/workflows/site.yml'
- "jsdoc2md.json" - 'jsdoc2md.json'
- "typedoc.json" - 'typedoc.json'
- "package.json" - 'package.json'
- "packages/**" - 'packages/**'
pull_request: pull_request:
branches: ["main"] branches: ['main']
paths: paths:
- "website/**" - 'website/**'
- ".github/workflows/site.yml" - '.github/workflows/site.yml'
- "jsdoc2md.json" - 'jsdoc2md.json'
- "typedoc.json" - 'typedoc.json'
- "package.json" - 'package.json'
- "packages/**" - 'packages/**'
# Allows you to run this workflow manually from the Actions tab # Allows you to run this workflow manually from the Actions tab
workflow_dispatch: workflow_dispatch:

View File

@@ -5,8 +5,8 @@ on:
branches: branches:
- main - main
paths: paths:
- "website/**" - 'website/**'
# - "template/**" # - "template/**"
jobs: jobs:
sync: sync:

2
.gitignore vendored
View File

@@ -3,6 +3,8 @@
# Test file for testing dd changes # Test file for testing dd changes
debug.ts debug.ts
testing
# dependencies # dependencies
node_modules node_modules

View File

@@ -7,5 +7,3 @@
tasks: tasks:
- init: yarn install && yarn run build && yarn run lint && yarn run build:doc - init: yarn install && yarn run build && yarn run lint && yarn run build:doc
command: yarn run dev command: yarn run dev

4
.helix/languages.toml Normal file
View File

@@ -0,0 +1,4 @@
[[language]]
name = "typescript"
formatter = { command = "npx" , args = ["prettier", "--write", "."] }

View File

@@ -12,4 +12,4 @@
"yaml.schemas": { "yaml.schemas": {
"https://json.schemastore.org/github-workflow.json": "file:///c%3A/Users/Heihe/Downloads/discordeno/discordeno/.github/workflows/site.yml" "https://json.schemastore.org/github-workflow.json": "file:///c%3A/Users/Heihe/Downloads/discordeno/discordeno/.github/workflows/site.yml"
} }
} }

View File

@@ -2,8 +2,8 @@ nodeLinker: node-modules
plugins: plugins:
- path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs - path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs
spec: "@yarnpkg/plugin-typescript" spec: '@yarnpkg/plugin-typescript'
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools" spec: '@yarnpkg/plugin-interactive-tools'
yarnPath: .yarn/releases/yarn-3.3.0.cjs yarnPath: .yarn/releases/yarn-3.3.0.cjs

View File

@@ -19,4 +19,4 @@
"@discordeno/gateway": "./packages/gateway/dist/index.js", "@discordeno/gateway": "./packages/gateway/dist/index.js",
"@discordeno/bot": "./packages/bot/dist/index.js" "@discordeno/bot": "./packages/bot/dist/index.js"
} }
} }

View File

@@ -11,15 +11,7 @@
"https://deno.land": true "https://deno.land": true
}, },
"discord.enabled": true, "discord.enabled": true,
"cSpell.words": [ "cSpell.words": ["denoland", "Discordeno", "Kwik", "Loglevels", "msgpack", "Slowmode", "upsert"],
"denoland",
"Discordeno",
"Kwik",
"Loglevels",
"msgpack",
"Slowmode",
"upsert"
],
"deno.unstable": true, "deno.unstable": true,
"deno.inlayHints.enumMemberValues.enabled": true, "deno.inlayHints.enumMemberValues.enabled": true,
"deno.inlayHints.functionLikeReturnTypes.enabled": true, "deno.inlayHints.functionLikeReturnTypes.enabled": true,

View File

@@ -1,7 +1,7 @@
version: '3.8' version: '3.8'
services: services:
influxdb: influxdb:
image: "influxdb:2.4.0-alpine" image: 'influxdb:2.4.0-alpine'
ports: ports:
- 127.0.0.1:8086:8086 - 127.0.0.1:8086:8086
env_file: env_file:
@@ -41,4 +41,4 @@ services:
deploy: deploy:
replicas: 2 replicas: 2
env_file: env_file:
- .env - .env

View File

@@ -1,6 +1,6 @@
{ {
"watch": "./src/**/*.ts", "watch": "./src/**/*.ts",
"ext ": "env,ts", "ext ": "env,ts",
"signal": "SIGKILL", "signal": "SIGKILL",
"exec": "npm run build && node" "exec": "npm run build && node"
} }

View File

@@ -1,51 +1,51 @@
{ {
"name": "dd-big-bot", "name": "dd-big-bot",
"version": "1.0.0", "version": "1.0.0",
"main": "index.js", "main": "index.js",
"type": "module", "type": "module",
"scripts": { "scripts": {
"devbg": "npx prisma generate && tsc --watch", "devbg": "npx prisma generate && tsc --watch",
"fmt": "eslint --fix \"src/**/*.ts*\"", "fmt": "eslint --fix \"src/**/*.ts*\"",
"devg": "nodemon --ignore ./src/bot/**/* --ignore ./src/rest/**/* --ignore ./dist/**/* -e ts dist/gateway/index.js", "devg": "nodemon --ignore ./src/bot/**/* --ignore ./src/rest/**/* --ignore ./dist/**/* -e ts dist/gateway/index.js",
"devr": "nodemon --ignore ./src/bot/**/* --ignore ./src/gateway/**/* --ignore ./dist/**/* -e ts dist/rest/index.js", "devr": "nodemon --ignore ./src/bot/**/* --ignore ./src/gateway/**/* --ignore ./dist/**/* -e ts dist/rest/index.js",
"devb": "nodemon --ignore ./src/rest/**/* --ignore ./src/gateway/**/* --ignore ./dist/**/* -e ts dist/bot/index.js", "devb": "nodemon --ignore ./src/rest/**/* --ignore ./src/gateway/**/* --ignore ./dist/**/* -e ts dist/bot/index.js",
"type": "tsc --noEmit", "type": "tsc --noEmit",
"build": "swc --delete-dir-on-start src --out-dir dist", "build": "swc --delete-dir-on-start src --out-dir dist",
"startr": "node dist/rest/index.js", "startr": "node dist/rest/index.js",
"startg": "node dist/gateway/index.js", "startg": "node dist/gateway/index.js",
"startb": "node dist/bot/index.js" "startb": "node dist/bot/index.js"
}, },
"dependencies": { "dependencies": {
"@influxdata/influxdb-client": "^1.29.0", "@influxdata/influxdb-client": "^1.29.0",
"@prisma/client": "^3.15.2", "@prisma/client": "^3.15.2",
"amqplib": "^0.10.3", "amqplib": "^0.10.3",
"colorette": "^2.0.19", "colorette": "^2.0.19",
"discordeno": "^16.0.1", "discordeno": "^16.0.1",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"express": "^4.18.1", "express": "^4.18.1",
"fastify": "^4.10.2", "fastify": "^4.10.2",
"nanoid": "^4.0.0", "nanoid": "^4.0.0",
"node-fetch": "^3.2.10", "node-fetch": "^3.2.10",
"web-worker": "^1.2.0" "web-worker": "^1.2.0"
}, },
"devDependencies": { "devDependencies": {
"@swc/cli": "^0.1.57", "@swc/cli": "^0.1.57",
"@swc/core": "^1.3.9", "@swc/core": "^1.3.9",
"@types/amqplib": "^0.8.2", "@types/amqplib": "^0.8.2",
"@types/express": "^4.17.13", "@types/express": "^4.17.13",
"@types/node": "^17.0.23", "@types/node": "^17.0.23",
"@types/ws": "^8.5.3", "@types/ws": "^8.5.3",
"nodemon": "^2.0.15", "nodemon": "^2.0.15",
"prettier": "2.6.2", "prettier": "2.6.2",
"prisma": "^4.2.1", "prisma": "^4.2.1",
"typescript": "^4.6.3" "typescript": "^4.6.3"
}, },
"prettier": { "prettier": {
"trailingComma": "all", "trailingComma": "all",
"useTabs": true, "useTabs": true,
"tabWidth": 2, "tabWidth": 2,
"singleQuote": true, "singleQuote": true,
"semi": true, "semi": true,
"printWidth": 120 "printWidth": 120
} }
} }

View File

@@ -79,6 +79,6 @@ export async function missingTranslation(language: keyof typeof languages, key:
// type translationKeys = keyof typeof english | string // type translationKeys = keyof typeof english | string
export type translationKeys = keyof typeof english; export type translationKeys = keyof typeof english;
type getArgs<K extends translationKeys> = typeof english[K] extends (...any: any[]) => unknown type getArgs<K extends translationKeys> = (typeof english)[K] extends (...any: any[]) => unknown
? Parameters<typeof english[K]> ? Parameters<(typeof english)[K]>
: []; : [];

View File

@@ -150,7 +150,7 @@ export type ArgumentDefinition =
| SubcommandArgumentDefinition | SubcommandArgumentDefinition
| SubcommandGroupArgumentDefinition; | SubcommandGroupArgumentDefinition;
type getName<K extends translationKeys> = typeof english[K] extends string ? typeof english[K] : never; type getName<K extends translationKeys> = (typeof english)[K] extends string ? (typeof english)[K] : never;
// OPTIONALS MUST BE FIRST!!! // OPTIONALS MUST BE FIRST!!!
export type ConvertArgumentDefinitionsToArgs<T extends readonly ArgumentDefinition[]> = Identity< export type ConvertArgumentDefinitionsToArgs<T extends readonly ArgumentDefinition[]> = Identity<

View File

@@ -1,91 +1,91 @@
const resolveFolder = (folderName) => path.resolve(__dirname, ".", folderName); const resolveFolder = (folderName) => path.resolve(__dirname, '.', folderName)
const fs = require("fs"); const fs = require('fs')
const path = require("path"); const path = require('path')
class CommandManager { class CommandManager {
constructor(client) { constructor(client) {
this.client = client; this.client = client
this.cache = new Map(); this.cache = new Map()
this.aliases = new Map(); this.aliases = new Map()
} }
load(options = {}) { load(options = {}) {
const commandFolderPath = options.path || "../Plugins"; const commandFolderPath = options.path || '../Plugins'
const commandFolder = resolveFolder(commandFolderPath); const commandFolder = resolveFolder(commandFolderPath)
if (options.category === undefined) options.category = true; if (options.category === undefined) options.category = true
if (options.plugins === undefined) options.plugins = true; if (options.plugins === undefined) options.plugins = true
// PluginMode will iterate through all SubFolders // PluginMode will iterate through all SubFolders
fs.readdirSync(commandFolder).map(async (dir) => { fs.readdirSync(commandFolder).map(async (dir) => {
if (dir.endsWith(".txt")) return; if (dir.endsWith('.txt')) return
if (!options.category && dir.endsWith(".js")) { if (!options.category && dir.endsWith('.js')) {
const commandPath = path.join(commandFolder, dir); const commandPath = path.join(commandFolder, dir)
this.loadCommand(commandPath); this.loadCommand(commandPath)
} else { } else {
fs.readdirSync(path.join(commandFolder, dir)).map((cmd) => { fs.readdirSync(path.join(commandFolder, dir)).map((cmd) => {
if (cmd.endsWith(".js") && !options.plugins) { if (cmd.endsWith('.js') && !options.plugins) {
const commandPath = path.join(commandFolder, dir, cmd); const commandPath = path.join(commandFolder, dir, cmd)
this.loadCommand(commandPath); this.loadCommand(commandPath)
} else if (commandFolderPath === "../Plugins") { } else if (commandFolderPath === '../Plugins') {
if (cmd !== "commands") return; if (cmd !== 'commands') return
fs.readdirSync(path.join(commandFolder, dir, cmd)).map((cmdfile) => { fs.readdirSync(path.join(commandFolder, dir, cmd)).map((cmdfile) => {
if (!cmdfile.endsWith(".js")) return; if (!cmdfile.endsWith('.js')) return
const commandPath = path.join(commandFolder, dir, cmd, cmdfile); const commandPath = path.join(commandFolder, dir, cmd, cmdfile)
this.loadCommand(commandPath); this.loadCommand(commandPath)
}); })
} }
}); })
} }
}); })
} }
loadCommand(commandPath) { loadCommand(commandPath) {
const pull = require(path.join(commandPath)); const pull = require(path.join(commandPath))
if (pull.name) { if (pull.name) {
pull.path = commandPath; pull.path = commandPath
this.cache.set(pull.name, pull); this.cache.set(pull.name, pull)
} }
if (pull.aliases) { if (pull.aliases) {
pull.aliases.map((p) => this.aliases.set(p, pull)); pull.aliases.map((p) => this.aliases.set(p, pull))
} }
return pull; return pull
} }
reloadCommand(commandName) { reloadCommand(commandName) {
const command = this.cache.get(commandName); const command = this.cache.get(commandName)
if (!command) return; if (!command) return
const commandPath = path.join(command.path); const commandPath = path.join(command.path)
delete require.cache[require.resolve(commandPath)]; delete require.cache[require.resolve(commandPath)]
return this.loadCommand(commandPath); return this.loadCommand(commandPath)
} }
isCommand(message) { isCommand(message) {
if (message.isFromBot) return false; if (message.isFromBot) return false
const prefix = "!"; const prefix = '!'
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const prefixRegex = new RegExp(`^(<@!?${this.client.id}>|${escapeRegex(prefix)})\\s*`); const prefixRegex = new RegExp(`^(<@!?${this.client.id}>|${escapeRegex(prefix)})\\s*`)
if (!prefixRegex.test(message.content)) return false; if (!prefixRegex.test(message.content)) return false
const [, matchedPrefix] = message.content.match(prefixRegex); const [, matchedPrefix] = message.content.match(prefixRegex)
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/); const args = message.content.slice(matchedPrefix.length).trim().split(/ +/)
this.onMessage(message, prefix, args); this.onMessage(message, prefix, args)
return true; return true
} }
isInteraction(interaction) { isInteraction(interaction) {
if (interaction.type !== 2) return; if (interaction.type !== 2) return
this.onInteraction(interaction); this.onInteraction(interaction)
} }
async onMessage(message, guild, args) { async onMessage(message, guild, args) {
const commandName = args.shift().toLowerCase(); const commandName = args.shift().toLowerCase()
const command = this.cache.get(commandName); // || this.cache.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)); const command = this.cache.get(commandName) // || this.cache.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command && message.content.includes(this.client.id)) { if (!command && message.content.includes(this.client.id)) {
// Handle, when Command has not been found // Handle, when Command has not been found
const options = { content: "I did not found the Command!" }; const options = { content: 'I did not found the Command!' }
this.client.helpers.sendMessage(message.channelId, options); this.client.helpers.sendMessage(message.channelId, options)
} }
if (!command) return; if (!command) return
const messagecommand = new command({ const messagecommand = new command({
manager: this, manager: this,
@@ -94,30 +94,30 @@ class CommandManager {
args, args,
settings: {}, settings: {},
commandName: command.name, commandName: command.name,
}); })
messagecommand.execute()?.catch?.((error) => { messagecommand.execute()?.catch?.((error) => {
console.log(error); console.log(error)
// Call Function on CommandResponse.js, handle the error // Call Function on CommandResponse.js, handle the error
return messagecommand.onError(error ?? "custom"); return messagecommand.onError(error ?? 'custom')
}); })
} }
async onInteraction(interaction) { async onInteraction(interaction) {
const command = this.cache.get(interaction.data.name); const command = this.cache.get(interaction.data.name)
if (!command) return; if (!command) return
const args = []; const args = []
// Map all Values and Args // Map all Values and Args
interaction.data.options?.map((o) => { interaction.data.options?.map((o) => {
if (o.name) args.push(o.name); if (o.name) args.push(o.name)
if (o.options) { if (o.options) {
o.options.map((o2) => { o.options.map((o2) => {
if (o2.value) return args.push(o2.value); if (o2.value) return args.push(o2.value)
if (o2.name) args.push(o2.name); if (o2.name) args.push(o2.name)
if (o2.options) o2.options.map((v) => args.push(v.value)); if (o2.options) o2.options.map((v) => args.push(v.value))
}); })
} }
}); })
const messagecommand = new command({ const messagecommand = new command({
manager: this, manager: this,
@@ -126,12 +126,12 @@ class CommandManager {
args, args,
settings: {}, settings: {},
commandName: command.name, commandName: command.name,
}); })
messagecommand.execute()?.catch?.((error) => { messagecommand.execute()?.catch?.((error) => {
console.log(error); console.log(error)
// Call Function on CommandResponse.js, handle the error // Call Function on CommandResponse.js, handle the error
return messagecommand.onError(error ?? "custom"); return messagecommand.onError(error ?? 'custom')
}); })
} }
} }
module.exports = CommandManager; module.exports = CommandManager

View File

@@ -1,32 +1,32 @@
const fs = require("fs"); const fs = require('fs')
const path = require("path"); const path = require('path')
const resolveFolder = (folderName) => path.resolve(__dirname, ".", folderName); const resolveFolder = (folderName) => path.resolve(__dirname, '.', folderName)
const EventEmitter = require("events"); const EventEmitter = require('events')
class EventManager extends EventEmitter { class EventManager extends EventEmitter {
constructor() { constructor() {
super(); super()
this.cache = new Map(); this.cache = new Map()
this.allEvents = {}; this.allEvents = {}
} }
load(options = {}) { load(options = {}) {
const eventsFolder = resolveFolder("../events"); const eventsFolder = resolveFolder('../events')
let i = 0; let i = 0
fs.readdirSync(eventsFolder).map(async (file) => { fs.readdirSync(eventsFolder).map(async (file) => {
if (!file.endsWith(".js")) return; if (!file.endsWith('.js')) return
i++; i++
const fileName = path.join(eventsFolder, file); const fileName = path.join(eventsFolder, file)
const event = require(fileName); const event = require(fileName)
const eventName = file.split(".")[0]; const eventName = file.split('.')[0]
this.allEvents[`${eventName}`] = (...args) => { this.allEvents[`${eventName}`] = (...args) => {
this.emit(eventName, ...args); this.emit(eventName, ...args)
return event(...args); return event(...args)
}; }
}); })
return this.allEvents; return this.allEvents
} }
} }
module.exports = EventManager; module.exports = EventManager

View File

@@ -1,51 +1,56 @@
const Discord = require("discordeno.js"); const Discord = require('discordeno.js')
const BaseCommand = require("../../../Structures/BaseCommand.js"); const BaseCommand = require('../../../Structures/BaseCommand.js')
class evalcommand extends BaseCommand { class evalcommand extends BaseCommand {
static name = "eval"; static name = 'eval'
static description = "danger !!!"; static description = 'danger !!!'
static category = "Developer"; static category = 'Developer'
static slash = { name: "eval", category: "dev" }; static slash = { name: 'eval', category: 'dev' }
constructor(data) { constructor(data) {
super(data); super(data)
} }
async execute() { async execute() {
if (!this.client.config.owners.includes(String(this.user.id))) return; if (!this.client.config.owners.includes(String(this.user.id))) return
if (!(this.args.length > 0)) return this.reply({ content: "**You must provide something to eval!**" }); if (!(this.args.length > 0)) return this.reply({ content: '**You must provide something to eval!**' })
const inputOfEval = this.args.join(" "); const inputOfEval = this.args.join(' ')
let outputOfEval; let outputOfEval
let typeOfEval; let typeOfEval
try { try {
if (this.args.includes("await")) { if (this.args.includes('await')) {
outputOfEval = await eval("(async () => {" + inputOfEval + "})()"); outputOfEval = await eval('(async () => {' + inputOfEval + '})()')
} else { } else {
outputOfEval = await eval(inputOfEval); outputOfEval = await eval(inputOfEval)
} }
} catch (e) { } catch (e) {
outputOfEval = e.message; outputOfEval = e.message
typeOfEval = e.name; typeOfEval = e.name
} }
const seen = []; const seen = []
outputOfEval = typeof outputOfEval === "object" outputOfEval =
? JSON.stringify(outputOfEval, (_, value) => { typeof outputOfEval === 'object'
if (value == `Bot ${this.client.config.token}`) return `BOT_TOKEN`; ? JSON.stringify(
if (typeof value === "bigint") value = value.toString(); outputOfEval,
if (typeof value === "object" && value !== null) { (_, value) => {
if (seen.indexOf(value) !== -1) return; if (value == `Bot ${this.client.config.token}`) return `BOT_TOKEN`
else seen.push(value); if (typeof value === 'bigint') value = value.toString()
} if (typeof value === 'object' && value !== null) {
return value; if (seen.indexOf(value) !== -1) return
}, 1) else seen.push(value)
: outputOfEval; }
return value
},
1,
)
: outputOfEval
const embed = new Discord.Embed() const embed = new Discord.Embed()
.addField({ name: "Input", value: "```js\n" + inputOfEval + "```" }) .addField({ name: 'Input', value: '```js\n' + inputOfEval + '```' })
.addField({ name: "Output", value: "```json\n" + `${outputOfEval}`.slice(0, 1000) + "```" }); .addField({ name: 'Output', value: '```json\n' + `${outputOfEval}`.slice(0, 1000) + '```' })
this.reply({ embeds: [embed] }); this.reply({ embeds: [embed] })
} }
} }
module.exports = evalcommand; module.exports = evalcommand

View File

@@ -1,19 +1,19 @@
const BaseCommand = require("../../../Structures/BaseCommand.js"); const BaseCommand = require('../../../Structures/BaseCommand.js')
class reloadcommand extends BaseCommand { class reloadcommand extends BaseCommand {
static name = "reload"; static name = 'reload'
static description = "Reloads a Command"; static description = 'Reloads a Command'
static category = "Developer"; static category = 'Developer'
static slash = { name: "reload", category: "dev" }; static slash = { name: 'reload', category: 'dev' }
constructor(data) { constructor(data) {
super(data); super(data)
} }
async execute() { async execute() {
if (!this.client.config.owners.includes(String(this.user.id))) return; if (!this.client.config.owners.includes(String(this.user.id))) return
if (!this.args[0]) return this.reply({ content: "**You must provide a command to reload!**" }); if (!this.args[0]) return this.reply({ content: '**You must provide a command to reload!**' })
const op = this.client.commands.reloadCommand(this.args[0]); const op = this.client.commands.reloadCommand(this.args[0])
if (!op) return this.reply({ content: "**That command doesn't exist!**" }); if (!op) return this.reply({ content: "**That command doesn't exist!**" })
return this.reply({ content: "**Reloaded Command: `" + this.args[0] + "`**" }); return this.reply({ content: '**Reloaded Command: `' + this.args[0] + '`**' })
} }
} }
module.exports = reloadcommand; module.exports = reloadcommand

View File

@@ -1,25 +1,23 @@
const BaseCommand = require("../../../Structures/BaseCommand.js"); const BaseCommand = require('../../../Structures/BaseCommand.js')
const Discord = require("discordeno.js"); const Discord = require('discordeno.js')
class pingcommand extends BaseCommand { class pingcommand extends BaseCommand {
static name = "ping"; static name = 'ping'
static description = "See if the bot latency is okay"; static description = 'See if the bot latency is okay'
static usage = ""; static usage = ''
static category = "General"; static category = 'General'
static slash = { name: "ping", category: "info" }; static slash = { name: 'ping', category: 'info' }
constructor(data) { constructor(data) {
super(data); super(data)
} }
async execute() { async execute() {
const msg = await this.channel.send({ content: `Pinging...` }); const msg = await this.channel.send({ content: `Pinging...` })
// Assign properties to the response // Assign properties to the response
const ping = msg.timestamp - (this.message ? this.message.timestamp : this.interaction.timestamp); const ping = msg.timestamp - (this.message ? this.message.timestamp : this.interaction.timestamp)
const embed = new Discord.Embed() const embed = new Discord.Embed().setTitle(`The Bots ping is ${ping} ms`).toJSON()
.setTitle(`The Bots ping is ${ping} ms`)
.toJSON();
// Edit Message with the Embed // Edit Message with the Embed
return this.reply({ embeds: [embed] }); return this.reply({ embeds: [embed] })
} }
} }
module.exports = pingcommand; module.exports = pingcommand

View File

@@ -1,41 +1,47 @@
const BaseCommand = require("../../../Structures/BaseCommand.js"); const BaseCommand = require('../../../Structures/BaseCommand.js')
const Discord = require("discordeno.js"); const Discord = require('discordeno.js')
class bancommand extends BaseCommand { class bancommand extends BaseCommand {
static name = "ban"; static name = 'ban'
static description = "Ban a user from the server"; static description = 'Ban a user from the server'
static usage = ""; static usage = ''
static category = "Moderation"; static category = 'Moderation'
static slash = { name: "ban", category: "mod" }; static slash = { name: 'ban', category: 'mod' }
constructor(data) { constructor(data) {
super(data); super(data)
} }
async execute() { async execute() {
// Show Case Modal // Show Case Modal
// Because no permission system has not been added // Because no permission system has not been added
if (!this.client.config.owners.includes(String(this.user.id))) return; if (!this.client.config.owners.includes(String(this.user.id))) return
const textinput = new Discord.Component() const textinput = new Discord.Component()
.setType("TEXT_INPUT") .setType('TEXT_INPUT')
.setStyle("SHORT") .setStyle('SHORT')
.setCustomId("t1") .setCustomId('t1')
.setLabel("User ID") .setLabel('User ID')
.setPlaceholder("User ID") .setPlaceholder('User ID')
.setRequired(true) .setRequired(true)
.setMaxLength(20) .setMaxLength(20)
.setMinLength(1) .setMinLength(1)
.setValue(this.args[0]) .setValue(this.args[0])
.toJSON(); .toJSON()
const textinput2 = new Discord.Component().setType("TEXT_INPUT").setStyle("PARAGRAPH").setCustomId("t2") const textinput2 = new Discord.Component()
.setLabel("Reason").setPlaceholder("Reason for Ban").setRequired(false) .setType('TEXT_INPUT')
.setMaxLength(300).toJSON(); .setStyle('PARAGRAPH')
.setCustomId('t2')
.setLabel('Reason')
.setPlaceholder('Reason for Ban')
.setRequired(false)
.setMaxLength(300)
.toJSON()
const actionrow = new Discord.Component().setType(1).setComponents(textinput).toJSON(); const actionrow = new Discord.Component().setType(1).setComponents(textinput).toJSON()
const actionrow2 = new Discord.Component().setType(1).setComponents(textinput2).toJSON(); const actionrow2 = new Discord.Component().setType(1).setComponents(textinput2).toJSON()
this.interaction.popupModal({ customId: "ban_modal", title: "Ban User", components: [actionrow, actionrow2] }); this.interaction.popupModal({ customId: 'ban_modal', title: 'Ban User', components: [actionrow, actionrow2] })
} }
} }
module.exports = bancommand; module.exports = bancommand

View File

@@ -1,82 +1,89 @@
const BaseCommand = require("../../../Structures/BaseCommand.js"); const BaseCommand = require('../../../Structures/BaseCommand.js')
const { Interaction, Collector, ComponentOptions, Embed, Component } = require("discordeno.js"); const { Interaction, Collector, ComponentOptions, Embed, Component } = require('discordeno.js')
class warncommand extends BaseCommand { class warncommand extends BaseCommand {
static name = "warn"; static name = 'warn'
static description = "Warn a user from the server"; static description = 'Warn a user from the server'
static usage = ""; static usage = ''
static category = "Moderation"; static category = 'Moderation'
static slash = { name: "warn", category: "mod" }; static slash = { name: 'warn', category: 'mod' }
constructor(data) { constructor(data) {
super(data); super(data)
} }
async execute() { async execute() {
// Show Case Modal // Show Case Modal
if (!this.interaction) return this.reply("You currently can just use this command as slash command."); if (!this.interaction) return this.reply('You currently can just use this command as slash command.')
if (!this.interaction.member.permissions.has("KICK_MEMBERS")) { if (!this.interaction.member.permissions.has('KICK_MEMBERS')) {
return this.reply("You need the permission `KICK_MEMBERS` to use this command."); return this.reply('You need the permission `KICK_MEMBERS` to use this command.')
} }
const textinput = new Component() const textinput = new Component()
.setType("TEXT_INPUT") .setType('TEXT_INPUT')
.setStyle("SHORT") .setStyle('SHORT')
.setCustomId("t1") .setCustomId('t1')
.setLabel("User ID") .setLabel('User ID')
.setPlaceholder("User ID") .setPlaceholder('User ID')
.setRequired(true) .setRequired(true)
.setMaxLength(20) .setMaxLength(20)
.setMinLength(1) .setMinLength(1)
.setValue(this.args[0]) .setValue(this.args[0])
.toJSON(); .toJSON()
const textinput2 = new Component().setType("TEXT_INPUT").setStyle("PARAGRAPH").setCustomId("t2") const textinput2 = new Component()
.setLabel("Reason").setPlaceholder("Reason for Warning").setRequired(false) .setType('TEXT_INPUT')
.setMaxLength(300).toJSON(); .setStyle('PARAGRAPH')
.setCustomId('t2')
.setLabel('Reason')
.setPlaceholder('Reason for Warning')
.setRequired(false)
.setMaxLength(300)
.toJSON()
const actionrow = new Component().setType(1).setComponents(textinput).toJSON(); const actionrow = new Component().setType(1).setComponents(textinput).toJSON()
const actionrow2 = new Component().setType(1).setComponents(textinput2).toJSON(); const actionrow2 = new Component().setType(1).setComponents(textinput2).toJSON()
this.interaction.popupModal({ customId: "warn_modal", title: "Warn User", components: [actionrow, actionrow2] }); this.interaction.popupModal({ customId: 'warn_modal', title: 'Warn User', components: [actionrow, actionrow2] })
const filter = (m) => m.data?.customId === "warn_modal"; const filter = (m) => m.data?.customId === 'warn_modal'
const collector = new Collector("interactionCreate", { client: this.client, timeout: 60000, filter }); const collector = new Collector('interactionCreate', { client: this.client, timeout: 60000, filter })
collector.on("collect", (m) => { collector.on('collect', (m) => {
const options = new ComponentOptions(m.data.components); const options = new ComponentOptions(m.data.components)
const i = new Interaction(this.client, m); const i = new Interaction(this.client, m)
collector.stop(); collector.stop()
const memberId = options.get("t1").value; const memberId = options.get('t1').value
const reason = options.get("t2").value; const reason = options.get('t2').value
const embed = new Embed() const embed = new Embed().setTitle('Warned User:').setDescription(`User ID: <@${memberId}> \n Reason: ${reason}`).setColor(0x00ff00).toJSON()
.setTitle("Warned User:")
.setDescription(`User ID: <@${memberId}> \n Reason: ${reason}`)
.setColor(0x00ff00)
.toJSON();
const warnMessage = new Embed() const warnMessage = new Embed()
.setTitle("Warning:") .setTitle('Warning:')
.setDescription(`You have been warned in **${this.guild.name}** for ${"`" + reason + "`"}`) .setDescription(`You have been warned in **${this.guild.name}** for ${'`' + reason + '`'}`)
.toJSON(); .toJSON()
this.guild.members.fetch(memberId).then((m) => { this.guild.members
m.send({ embeds: [warnMessage] }).then(() => { .fetch(memberId)
i.reply({ embeds: [embed] }); .then((m) => {
}).catch((e) => { m.send({ embeds: [warnMessage] })
console.log(e); .then(() => {
i.reply({ content: `Could not warn user ${"<@" + m.id + ">"} | They likely do not have their DMs open.` }); i.reply({ embeds: [embed] })
}); })
}).catch((e) => { .catch((e) => {
const embed = new Embed() console.log(e)
.setTitle("Member not found") i.reply({ content: `Could not warn user ${'<@' + m.id + '>'} | They likely do not have their DMs open.` })
.setDescription(`The member with the ID of ${"`" + memberId + "`"} has not been found in this Server.`) })
.setColor(0xff0000) })
.toJSON(); .catch((e) => {
i.reply({ embeds: [embed] }); const embed = new Embed()
}); .setTitle('Member not found')
}); .setDescription(`The member with the ID of ${'`' + memberId + '`'} has not been found in this Server.`)
.setColor(0xff0000)
.toJSON()
i.reply({ embeds: [embed] })
})
})
} }
} }
module.exports = warncommand; module.exports = warncommand

View File

@@ -1,15 +1,15 @@
const UtilCommand = require("./CommandResponse.js"); const UtilCommand = require('./CommandResponse.js')
class BaseCommand extends UtilCommand { class BaseCommand extends UtilCommand {
constructor(data) { constructor(data) {
super(data); super(data)
this.message = data.message; this.message = data.message
this.interaction = data.interaction; this.interaction = data.interaction
this.user = this.message ? this.message.author : this.interaction.user; this.user = this.message ? this.message.author : this.interaction.user
this.guild = this.message ? this.message.guild : this.interaction.guild; this.guild = this.message ? this.message.guild : this.interaction.guild
this.member = this.message ? this.message.member : this.interaction.member; this.member = this.message ? this.message.member : this.interaction.member
this.channel = this.message ? this.message.channel : this.interaction.channel; this.channel = this.message ? this.message.channel : this.interaction.channel
this.client = data.client; this.client = data.client
this.settings = data.settings ?? {}; this.settings = data.settings ?? {}
} }
} }
module.exports = BaseCommand; module.exports = BaseCommand

View File

@@ -1,50 +1,50 @@
class Responses { class Responses {
constructor(data) { constructor(data) {
this.manager = data.manager; this.manager = data.manager
this.args = this._validateArguments(data.args); this.args = this._validateArguments(data.args)
this.replied = false; this.replied = false
} }
async reply(content) { async reply(content) {
// When just a string is passed, we assume it's the content -> transform to correct formatted payload // When just a string is passed, we assume it's the content -> transform to correct formatted payload
if (typeof content === "string") content = { content }; if (typeof content === 'string') content = { content }
if (this.interaction) { if (this.interaction) {
if (this.replied) return this.followUp(content); if (this.replied) return this.followUp(content)
const reply = await this.interaction.reply(content); const reply = await this.interaction.reply(content)
this.replied = true; this.replied = true
return {}; return {}
} }
if (this.message) { if (this.message) {
if (this.replied) return this.followUp(content); if (this.replied) return this.followUp(content)
const msg = await this.message.channel.send(content); const msg = await this.message.channel.send(content)
// Assign properties to the response // Assign properties to the response
const response = this.client.messages.forge(msg); const response = this.client.messages.forge(msg)
this.replied = true; this.replied = true
return response; return response
} }
} }
async followUp(content) { async followUp(content) {
if (this.interaction) { if (this.interaction) {
const reply = await this.interaction.followUp(content); const reply = await this.interaction.followUp(content)
return {}; return {}
} }
if (this.message) { if (this.message) {
const msg = await this.message.channel.send(content); const msg = await this.message.channel.send(content)
const response = this.client.messages.forge(msg); const response = this.client.messages.forge(msg)
return response; return response
} }
} }
onError(error) { onError(error) {
return this.reply({ content: `A unknown Error happend: \n> ${error}` }); return this.reply({ content: `A unknown Error happend: \n> ${error}` })
} }
_validateArguments(args) { _validateArguments(args) {
this.args = args; this.args = args
return args; return args
} }
} }
module.exports = Responses; module.exports = Responses

View File

@@ -1,4 +1,4 @@
module.exports = async (client, interaction) => { module.exports = async (client, interaction) => {
interaction = client.interactions.forge(interaction); interaction = client.interactions.forge(interaction)
client.commands.isInteraction(interaction); client.commands.isInteraction(interaction)
}; }

View File

@@ -1,4 +1,4 @@
module.exports = async (client, message) => { module.exports = async (client, message) => {
message = client.messages.forge(message); message = client.messages.forge(message)
client.commands.isCommand(message); client.commands.isCommand(message)
}; }

View File

@@ -1,7 +1,7 @@
module.exports = async (client, payload) => { module.exports = async (client, payload) => {
client.user = client.users.forge(payload.user); client.user = client.users.forge(payload.user)
if (payload.shardId === client.gateway.lastShardId) { if (payload.shardId === client.gateway.lastShardId) {
// All Shards are ready // All Shards are ready
console.log("Successfully connected to the gateway as " + client.user.tag); console.log('Successfully connected to the gateway as ' + client.user.tag)
} }
}; }

View File

@@ -1,32 +1,32 @@
require("dotenv").config(); require('dotenv').config()
const Discord = require("discordeno.js"); const Discord = require('discordeno.js')
// Ideally you should switch this to .env but for a template a config json is enough // Ideally you should switch this to .env but for a template a config json is enough
const config = require("./config.json"); const config = require('./config.json')
const EventManager = require("./Managers/EventManager.js"); const EventManager = require('./Managers/EventManager.js')
// looping through all events and registering them // looping through all events and registering them
const events = new EventManager({}); const events = new EventManager({})
const baseBot = Discord.createBot({ const baseBot = Discord.createBot({
events: events.load({}), events: events.load({}),
intents: Discord.Intents.Guilds | Discord.Intents.GuildMessages | Discord.Intents.MessageContent, intents: Discord.Intents.Guilds | Discord.Intents.GuildMessages | Discord.Intents.MessageContent,
token: process.env.TOKEN, token: process.env.TOKEN,
}); })
const client = Discord.enableCachePlugin(baseBot, {}); const client = Discord.enableCachePlugin(baseBot, {})
client.config = config; client.config = config
// looping through all commands and registering them in .cache of the class // looping through all commands and registering them in .cache of the class
const CommandManager = require("./Managers/CommandManager.js"); const CommandManager = require('./Managers/CommandManager.js')
client.commands = new CommandManager(client); client.commands = new CommandManager(client)
client.commands.load({}); client.commands.load({})
// Starts your Bot // Starts your Bot
Discord.startBot(client); Discord.startBot(client)
/* /*
* You should handle all errors and fix the issues in your codes... * You should handle all errors and fix the issues in your codes...
* process.on('unhandledRejection', (reason, p) => {console.log(reason, p)}) * process.on('unhandledRejection', (reason, p) => {console.log(reason, p)})
*/ */

View File

@@ -3,10 +3,7 @@
"babelrc": false, "babelrc": false,
"extensions": ["ts", "tsx"], "extensions": ["ts", "tsx"],
"ignore": ["**/*.(test|spec).ts"], "ignore": ["**/*.(test|spec).ts"],
"plugins": [ "plugins": ["@babel/proposal-class-properties", "@babel/proposal-object-rest-spread"],
"@babel/proposal-class-properties",
"@babel/proposal-object-rest-spread"
],
"presets": [ "presets": [
[ [
"@babel/preset-env", "@babel/preset-env",

View File

@@ -1,16 +1,8 @@
{ {
"extends": "tsconfig/base.json", "extends": "tsconfig/base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
}, },
"include": [ "include": ["./src/**/*.ts", "./src/**/*.tsx"],
"./src/**/*.ts", "exclude": ["node_modules", "dist", "test", "tests"]
"./src/**/*.tsx" }
],
"exclude": [
"node_modules",
"dist",
"test",
"tests"
]
}

View File

@@ -1,12 +1,12 @@
export * from "./CHANNEL_CREATE.js"; export * from './CHANNEL_CREATE.js'
export * from "./CHANNEL_DELETE.js"; export * from './CHANNEL_DELETE.js'
export * from "./CHANNEL_PINS_UPDATE.js"; export * from './CHANNEL_PINS_UPDATE.js'
export * from "./CHANNEL_UPDATE.js"; export * from './CHANNEL_UPDATE.js'
export * from "./STAGE_INSTANCE_CREATE.js"; export * from './STAGE_INSTANCE_CREATE.js'
export * from "./STAGE_INSTANCE_DELETE.js"; export * from './STAGE_INSTANCE_DELETE.js'
export * from "./STAGE_INSTANCE_UPDATE.js"; export * from './STAGE_INSTANCE_UPDATE.js'
export * from "./THREAD_CREATE.js"; export * from './THREAD_CREATE.js'
export * from "./THREAD_DELETE.js"; export * from './THREAD_DELETE.js'
export * from "./THREAD_LIST_SYNC.js"; export * from './THREAD_LIST_SYNC.js'
export * from "./THREAD_MEMBERS_UPDATE.js"; export * from './THREAD_MEMBERS_UPDATE.js'
export * from "./THREAD_UPDATE.js"; export * from './THREAD_UPDATE.js'

View File

@@ -1 +1 @@
export * from "./GUILD_EMOJIS_UPDATE.js"; export * from './GUILD_EMOJIS_UPDATE.js'

View File

@@ -5,8 +5,8 @@ export async function handleGuildStickersUpdate(bot: Bot, data: DiscordGatewayPa
bot.events.guildStickersUpdate?.( bot.events.guildStickersUpdate?.(
payload.stickers.map((sticker) => { payload.stickers.map((sticker) => {
sticker.guild_id = payload.guild_id sticker.guild_id = payload.guild_id
return bot.transformers.sticker(bot, sticker) return bot.transformers.sticker(bot, sticker)
}) }),
) )
} }

View File

@@ -1,11 +1,11 @@
export * from "./automod/index.js"; export * from './automod/index.js'
export * from "./scheduledEvents/index.js"; export * from './scheduledEvents/index.js'
export * from "./GUILD_AUDIT_LOG_ENTRY_CREATE.js"; export * from './GUILD_AUDIT_LOG_ENTRY_CREATE.js'
export * from "./GUILD_BAN_ADD.js"; export * from './GUILD_BAN_ADD.js'
export * from "./GUILD_BAN_REMOVE.js"; export * from './GUILD_BAN_REMOVE.js'
export * from "./GUILD_CREATE.js"; export * from './GUILD_CREATE.js'
export * from "./GUILD_DELETE.js"; export * from './GUILD_DELETE.js'
export * from "./GUILD_INTEGRATIONS_UPDATE.js"; export * from './GUILD_INTEGRATIONS_UPDATE.js'
export * from "./GUILD_STICKERS_UPDATE.js"; export * from './GUILD_STICKERS_UPDATE.js'
export * from "./GUILD_UPDATE.js"; export * from './GUILD_UPDATE.js'

View File

@@ -1,5 +1,5 @@
export * from "./GUILD_SCHEDULED_EVENT_CREATE.js"; export * from './GUILD_SCHEDULED_EVENT_CREATE.js'
export * from "./GUILD_SCHEDULED_EVENT_DELETE.js"; export * from './GUILD_SCHEDULED_EVENT_DELETE.js'
export * from "./GUILD_SCHEDULED_EVENT_UPDATE.js"; export * from './GUILD_SCHEDULED_EVENT_UPDATE.js'
export * from "./GUILD_SCHEDULED_EVENT_USER_ADD.js"; export * from './GUILD_SCHEDULED_EVENT_USER_ADD.js'
export * from "./GUILD_SCHEDULED_EVENT_USER_REMOVE.js"; export * from './GUILD_SCHEDULED_EVENT_USER_REMOVE.js'

View File

@@ -1,3 +1,3 @@
export * from "./INTEGRATION_CREATE.js"; export * from './INTEGRATION_CREATE.js'
export * from "./INTEGRATION_DELETE.js"; export * from './INTEGRATION_DELETE.js'
export * from "./INTEGRATION_UPDATE.js"; export * from './INTEGRATION_UPDATE.js'

View File

@@ -1,6 +1,6 @@
import type { Bot, DiscordGatewayPayload, DiscordGuildApplicationCommandPermissions } from "../.."; import type { Bot, DiscordGatewayPayload, DiscordGuildApplicationCommandPermissions } from '../..'
export async function handleApplicationCommandPermissionsUpdate(bot: Bot, data: DiscordGatewayPayload, shardId: number): Promise<void> { export async function handleApplicationCommandPermissionsUpdate(bot: Bot, data: DiscordGatewayPayload, shardId: number): Promise<void> {
const payload = data.d as DiscordGuildApplicationCommandPermissions const payload = data.d as DiscordGuildApplicationCommandPermissions
bot.events.applicationCommandPermissionsUpdate?.(bot.transformers.applicationCommandPermission(bot, payload)) bot.events.applicationCommandPermissionsUpdate?.(bot.transformers.applicationCommandPermission(bot, payload))
} }

View File

@@ -1,2 +1,2 @@
export * from "./INVITE_CREATE.js"; export * from './INVITE_CREATE.js'
export * from "./INVITE_DELETE.js"; export * from './INVITE_DELETE.js'

View File

@@ -1,4 +1,4 @@
export * from "./GUILD_MEMBER_ADD.js"; export * from './GUILD_MEMBER_ADD.js'
export * from "./GUILD_MEMBER_REMOVE.js"; export * from './GUILD_MEMBER_REMOVE.js'
export * from "./GUILD_MEMBER_UPDATE.js"; export * from './GUILD_MEMBER_UPDATE.js'
export * from "./GUILD_MEMBERS_CHUNK.js"; export * from './GUILD_MEMBERS_CHUNK.js'

View File

@@ -1,8 +1,8 @@
export * from "./MESSAGE_CREATE.js"; export * from './MESSAGE_CREATE.js'
export * from "./MESSAGE_DELETE_BULK.js"; export * from './MESSAGE_DELETE_BULK.js'
export * from "./MESSAGE_DELETE.js"; export * from './MESSAGE_DELETE.js'
export * from "./MESSAGE_REACTION_ADD.js"; export * from './MESSAGE_REACTION_ADD.js'
export * from "./MESSAGE_REACTION_REMOVE_ALL.js"; export * from './MESSAGE_REACTION_REMOVE_ALL.js'
export * from "./MESSAGE_REACTION_REMOVE_EMOJI.js"; export * from './MESSAGE_REACTION_REMOVE_EMOJI.js'
export * from "./MESSAGE_REACTION_REMOVE.js"; export * from './MESSAGE_REACTION_REMOVE.js'
export * from "./MESSAGE_UPDATE.js"; export * from './MESSAGE_UPDATE.js'

View File

@@ -1,4 +1,4 @@
export * from "./PRESENCE_UPDATE.js"; export * from './PRESENCE_UPDATE.js'
export * from "./READY.js"; export * from './READY.js'
export * from "./TYPING_START.js"; export * from './TYPING_START.js'
export * from "./USER_UPDATE.js"; export * from './USER_UPDATE.js'

View File

@@ -1,3 +1,3 @@
export * from "./GUILD_ROLE_CREATE.js"; export * from './GUILD_ROLE_CREATE.js'
export * from "./GUILD_ROLE_DELETE.js"; export * from './GUILD_ROLE_DELETE.js'
export * from "./GUILD_ROLE_UPDATE.js"; export * from './GUILD_ROLE_UPDATE.js'

View File

@@ -1,2 +1,2 @@
export * from "./VOICE_SERVER_UPDATE.js"; export * from './VOICE_SERVER_UPDATE.js'
export * from "./VOICE_STATE_UPDATE.js"; export * from './VOICE_STATE_UPDATE.js'

View File

@@ -1,7 +1,7 @@
import type { DiscordGatewayPayload, DiscordWebhookUpdate } from '@discordeno/types' import type { DiscordGatewayPayload, DiscordWebhookUpdate } from '@discordeno/types'
import type { Bot } from '../../index.js' import type { Bot } from '../../index.js'
export async function handleWebhooksUpdate(bot: Bot, data: DiscordGatewayPayload, shardId: number) : Promise<void> { export async function handleWebhooksUpdate(bot: Bot, data: DiscordGatewayPayload, shardId: number): Promise<void> {
const payload = data.d as DiscordWebhookUpdate const payload = data.d as DiscordWebhookUpdate
bot.events.webhooksUpdate?.({ bot.events.webhooksUpdate?.({
channelId: bot.transformers.snowflake(payload.channel_id), channelId: bot.transformers.snowflake(payload.channel_id),

View File

@@ -1 +1 @@
export * from "./WEBHOOKS_UPDATE.js"; export * from './WEBHOOKS_UPDATE.js'

View File

@@ -1,16 +1,16 @@
export * from "./activity.js"; export * from './activity.js'
export * from "./application.js"; export * from './application.js'
export * from "./applicationCommand.js"; export * from './applicationCommand.js'
export * from "./applicationCommandOption.js"; export * from './applicationCommandOption.js'
export * from "./applicationCommandOptionChoice.js"; export * from './applicationCommandOptionChoice.js'
export * from "./applicationCommandPermission.js"; export * from './applicationCommandPermission.js'
export * from "./attachment.js"; export * from './attachment.js'
export * from "./auditLogEntry.js"; export * from './auditLogEntry.js'
export * from "./component.js"; export * from './component.js'
export * from "./embed.js"; export * from './embed.js'
export * from "./emoji.js"; export * from './emoji.js'
export * from "./gatewayBot.js"; export * from './gatewayBot.js'
export * from "./member.js"; export * from './member.js'
export * from "./presence.js"; export * from './presence.js'
export * from "./team.js"; export * from './team.js'
export * from "./widgetSettings.js"; export * from './widgetSettings.js'

View File

@@ -1,49 +1,49 @@
export class ToggleBitfield { export class ToggleBitfield {
bitfield = 0; bitfield = 0
constructor(bitfield?: number) { constructor(bitfield?: number) {
if (bitfield) this.bitfield = bitfield; if (bitfield) this.bitfield = bitfield
} }
/** Tests whether or not this bitfield has the permission requested. */ /** Tests whether or not this bitfield has the permission requested. */
contains(bits: number): boolean { contains(bits: number): boolean {
return Boolean(this.bitfield & bits); return Boolean(this.bitfield & bits)
} }
/** Adds some bits to the bitfield. */ /** Adds some bits to the bitfield. */
add(bits: number): this { add(bits: number): this {
this.bitfield |= bits; this.bitfield |= bits
return this; return this
} }
/** Removes some bits from the bitfield. */ /** Removes some bits from the bitfield. */
remove(bits: number): this { remove(bits: number): this {
this.bitfield &= ~bits; this.bitfield &= ~bits
return this; return this
} }
} }
export class ToggleBitfieldBigint { export class ToggleBitfieldBigint {
bitfield = 0n; bitfield = 0n
constructor(bitfield?: bigint) { constructor(bitfield?: bigint) {
if (bitfield) this.bitfield = bitfield; if (bitfield) this.bitfield = bitfield
} }
/** Tests whether or not this bitfield has the permission requested. */ /** Tests whether or not this bitfield has the permission requested. */
contains(bits: bigint): boolean { contains(bits: bigint): boolean {
return Boolean(this.bitfield & bits); return Boolean(this.bitfield & bits)
} }
/** Adds some bits to the bitfield. */ /** Adds some bits to the bitfield. */
add(bits: bigint): this { add(bits: bigint): this {
this.bitfield |= bits; this.bitfield |= bits
return this; return this
} }
/** Removes some bits from the bitfield. */ /** Removes some bits from the bitfield. */
remove(bits: bigint): this { remove(bits: bigint): this {
this.bitfield &= ~bits; this.bitfield &= ~bits
return this; return this
} }
} }

View File

@@ -1,7 +1,7 @@
export * from "./emoji.js"; export * from './emoji.js'
export * from "./guild.js"; export * from './guild.js'
export * from "./member.js"; export * from './member.js'
export * from "./role.js"; export * from './role.js'
export * from "./ToggleBitfield.js"; export * from './ToggleBitfield.js'
export * from "./user.js"; export * from './user.js'
export * from "./voice.js"; export * from './voice.js'

View File

@@ -1,16 +1,8 @@
{ {
"extends": "tsconfig/base.json", "extends": "tsconfig/base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
}, },
"include": [ "include": ["./src/**/*.ts", "./src/**/*.tsx"],
"./src/**/*.ts", "exclude": ["node_modules", "dist", "test", "tests"]
"./src/**/*.tsx" }
],
"exclude": [
"node_modules",
"dist",
"test",
"tests"
]
}

View File

@@ -1,11 +1,5 @@
{ {
"extends": "tsconfig/test.json", "extends": "tsconfig/test.json",
"include": [ "include": ["tests"],
"tests", "exclude": ["node_modules", "dist", "src"]
], }
"exclude": [
"node_modules",
"dist",
"src"
]
}

View File

@@ -1,16 +1,8 @@
{ {
"extends": "tsconfig/base.json", "extends": "tsconfig/base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
}, },
"include": [ "include": ["./src/**/*.ts", "./src/**/*.tsx"],
"./src/**/*.ts", "exclude": ["node_modules", "dist", "test", "tests"]
"./src/**/*.tsx" }
],
"exclude": [
"node_modules",
"dist",
"test",
"tests"
]
}

View File

@@ -1,11 +1,5 @@
{ {
"extends": "tsconfig/test.json", "extends": "tsconfig/test.json",
"include": [ "include": ["tests"],
"tests", "exclude": ["node_modules", "dist", "src"]
], }
"exclude": [
"node_modules",
"dist",
"src"
]
}

View File

@@ -467,7 +467,7 @@ export class DiscordenoShard {
this.previousSequenceNumber = packet.s this.previousSequenceNumber = packet.s
} }
this.forwardToBot(packet); this.forwardToBot(packet)
} }
forwardToBot(packet: DiscordGatewayPayload): void { forwardToBot(packet: DiscordGatewayPayload): void {

View File

@@ -1,16 +1,8 @@
{ {
"extends": "tsconfig/base.json", "extends": "tsconfig/base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
}, },
"include": [ "include": ["./src/**/*.ts", "./src/**/*.tsx"],
"./src/**/*.ts", "exclude": ["node_modules", "dist", "test", "tests"]
"./src/**/*.tsx" }
],
"exclude": [
"node_modules",
"dist",
"test",
"tests"
]
}

View File

@@ -1,11 +1,5 @@
{ {
"extends": "tsconfig/test.json", "extends": "tsconfig/test.json",
"include": [ "include": ["tests"],
"tests", "exclude": ["node_modules", "dist", "src"]
], }
"exclude": [
"node_modules",
"dist",
"src"
]
}

View File

@@ -984,7 +984,7 @@ export function createRestManager(options: CreateRestManagerOptions): RestManage
}) })
if (!result.ok) { if (!result.ok) {
const err = (await result.json().catch(() => { })) as Record<string, any> const err = (await result.json().catch(() => {})) as Record<string, any>
// Legacy Handling to not break old code or when body is missing // Legacy Handling to not break old code or when body is missing
if (!err?.body) throw new Error(`Error: ${err.message ?? result.statusText}`) if (!err?.body) throw new Error(`Error: ${err.message ?? result.statusText}`)
throw new Error(JSON.stringify(err)) throw new Error(JSON.stringify(err))
@@ -999,7 +999,7 @@ export function createRestManager(options: CreateRestManagerOptions): RestManage
method, method,
requestBodyOptions: options, requestBodyOptions: options,
retryCount: 0, retryCount: 0,
retryRequest: async function(payload: SendRequestOptions) { retryRequest: async function (payload: SendRequestOptions) {
rest.processRequest(payload) rest.processRequest(payload)
}, },
resolve: (data) => { resolve: (data) => {
@@ -1690,10 +1690,10 @@ export function createRestManager(options: CreateRestManagerOptions): RestManage
return await new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
rest.sendRequest({ rest.sendRequest({
url: rest.routes.webhooks.webhook(rest.applicationId, token), url: rest.routes.webhooks.webhook(rest.applicationId, token),
method: 'POST', method: 'POST',
requestBodyOptions: { body: options, files: options.files }, requestBodyOptions: { body: options, files: options.files },
retryCount: 0, retryCount: 0,
retryRequest: async function(options: SendRequestOptions) { retryRequest: async function (options: SendRequestOptions) {
// TODO: should change to reprocess queue item // TODO: should change to reprocess queue item
await rest.sendRequest(options) await rest.sendRequest(options)
}, },
@@ -1713,7 +1713,7 @@ export function createRestManager(options: CreateRestManagerOptions): RestManage
method: 'POST', method: 'POST',
requestBodyOptions: { body: options }, requestBodyOptions: { body: options },
retryCount: 0, retryCount: 0,
retryRequest: async function(options: SendRequestOptions) { retryRequest: async function (options: SendRequestOptions) {
// TODO: should change to reprocess queue item // TODO: should change to reprocess queue item
await rest.sendRequest(options) await rest.sendRequest(options)
}, },

View File

@@ -119,6 +119,5 @@ describe('Manage Guilds', async () => {
// description: 'some description', // description: 'some description',
// }) // })
// }) // })
}) })

View File

@@ -11,8 +11,8 @@ export const rest = createRestManager({
}) })
rest.deleteQueueDelay = 10000 rest.deleteQueueDelay = 10000
const guild = await rest.createGuild({ name: 'ddenotester' }); const guild = await rest.createGuild({ name: 'ddenotester' })
const channel = await rest.createChannel(guild.id, { name: "ddenotestchannel" }); const channel = await rest.createChannel(guild.id, { name: 'ddenotestchannel' })
export const e2ecache = { export const e2ecache = {
guild, guild,

View File

@@ -107,5 +107,3 @@ describe('Webhook helpers', async () => {
await expect(rest.getWebhookMessage(webhook.id, webhook.token!, message!.id)).to.eventually.rejected await expect(rest.getWebhookMessage(webhook.id, webhook.token!, message!.id)).to.eventually.rejected
}) })
}) })

View File

@@ -1,16 +1,8 @@
{ {
"extends": "tsconfig/base.json", "extends": "tsconfig/base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
}, },
"include": [ "include": ["./src/**/*.ts", "./src/**/*.tsx"],
"./src/**/*.ts", "exclude": ["node_modules", "dist", "test", "tests"]
"./src/**/*.tsx" }
],
"exclude": [
"node_modules",
"dist",
"test",
"tests"
]
}

View File

@@ -1,11 +1,5 @@
{ {
"extends": "tsconfig/test.json", "extends": "tsconfig/test.json",
"include": [ "include": ["tests"],
"tests", "exclude": ["node_modules", "dist", "src"]
], }
"exclude": [
"node_modules",
"dist",
"src"
]
}

View File

@@ -4,4 +4,4 @@
"noEmit": true, "noEmit": true,
"incremental": false "incremental": false
} }
} }

View File

@@ -1,4 +1,4 @@
export * from './camel.js' export * from './camel.js'
export * from './discord.js' export * from './discord.js'
export * from './discordeno.js' export * from './discordeno.js'
export * from './shared.js' export * from './shared.js'

View File

@@ -1,16 +1,8 @@
{ {
"extends": "tsconfig/base.json", "extends": "tsconfig/base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
}, },
"include": [ "include": ["./src/**/*.ts", "./src/**/*.tsx"],
"./src/**/*.ts", "exclude": ["node_modules", "dist", "test", "tests"]
"./src/**/*.tsx" }
],
"exclude": [
"node_modules",
"dist",
"test",
"tests"
]
}

View File

@@ -1,11 +1,5 @@
{ {
"extends": "tsconfig/test.json", "extends": "tsconfig/test.json",
"include": [ "include": ["tests"],
"tests", "exclude": ["node_modules", "dist", "src"]
], }
"exclude": [
"node_modules",
"dist",
"src"
]
}

View File

@@ -1,6 +1,6 @@
import type { Camelize, Snakelize } from '@discordeno/types' import type { Camelize, Snakelize } from '@discordeno/types'
export function camelize <T>(object: T): Camelize<T> { export function camelize<T>(object: T): Camelize<T> {
if (Array.isArray(object)) { if (Array.isArray(object)) {
return object.map((element) => camelize(element)) as Camelize<T> return object.map((element) => camelize(element)) as Camelize<T>
} }
@@ -16,7 +16,7 @@ export function camelize <T>(object: T): Camelize<T> {
return object as Camelize<T> return object as Camelize<T>
} }
export function snakelize <T>(object: T): Snakelize<T> { export function snakelize<T>(object: T): Snakelize<T> {
if (Array.isArray(object)) { if (Array.isArray(object)) {
return object.map((element) => snakelize(element)) as Snakelize<T> return object.map((element) => snakelize(element)) as Snakelize<T>
} }

View File

@@ -11,7 +11,7 @@ describe('Logger', () => {
loggy.fatal('fatal') loggy.fatal('fatal')
loggy.info('info') loggy.info('info')
loggy.warn('warn') loggy.warn('warn')
loggy.setDepth(LogDepth.Full) loggy.setDepth(LogDepth.Full)
loggy.debug('debugging') loggy.debug('debugging')
@@ -20,7 +20,7 @@ describe('Logger', () => {
loggy.info('info') loggy.info('info')
loggy.warn('warn') loggy.warn('warn')
}) })
it('create logger with a name', () => { it('create logger with a name', () => {
const loggy = createLogger({ name: 'loggy' }) const loggy = createLogger({ name: 'loggy' })
expect(loggy).to.exist expect(loggy).to.exist

View File

@@ -1,16 +1,8 @@
{ {
"extends": "tsconfig/base.json", "extends": "tsconfig/base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
}, },
"include": [ "include": ["./src/**/*.ts", "./src/**/*.tsx"],
"./src/**/*.ts", "exclude": ["node_modules", "dist", "test", "tests"]
"./src/**/*.tsx" }
],
"exclude": [
"node_modules",
"dist",
"test",
"tests"
]
}

View File

@@ -1,11 +1,5 @@
{ {
"extends": "tsconfig/test.json", "extends": "tsconfig/test.json",
"include": [ "include": ["tests"],
"tests", "exclude": ["node_modules", "dist", "src"]
], }
"exclude": [
"node_modules",
"dist",
"src"
]
}

View File

@@ -1,9 +1,4 @@
import fs from 'node:fs' import fs from 'node:fs'
import { argv } from 'node:process' import { argv } from 'node:process'
fs.writeFileSync( fs.writeFileSync('./coverage/lcov.info', fs.readFileSync('./coverage/lcov.info', 'utf-8').replace(/SF:src/g, `SF:packages/${argv[2]}/src`))
'./coverage/lcov.info',
fs
.readFileSync('./coverage/lcov.info', 'utf-8')
.replace(/SF:src/g, `SF:packages/${argv[2]}/src`)
)

View File

@@ -39,11 +39,11 @@ for await (let filepath of walk(typedocOutPath)) {
// Converts ugly names to clean names for example discordeno_types.ActionRow becomes ActionRow // Converts ugly names to clean names for example discordeno_types.ActionRow becomes ActionRow
const cleanForms = [ const cleanForms = [
{ ugly: 'discordeno_bot.md', clean: 'Bot.md'}, { ugly: 'discordeno_bot.md', clean: 'Bot.md' },
{ ugly: 'discordeno_gateway.md', clean: 'Gateway.md'}, { ugly: 'discordeno_gateway.md', clean: 'Gateway.md' },
{ ugly: 'discordeno_rest.md', clean: 'Rest.md'}, { ugly: 'discordeno_rest.md', clean: 'Rest.md' },
{ ugly: 'discordeno_types.md', clean: 'Types.md'}, { ugly: 'discordeno_types.md', clean: 'Types.md' },
{ ugly: 'discordeno_utils.md', clean: 'Utils.md'}, { ugly: 'discordeno_utils.md', clean: 'Utils.md' },
{ ugly: 'discordeno_bot.' }, { ugly: 'discordeno_bot.' },
{ ugly: 'discordeno_gateway.' }, { ugly: 'discordeno_gateway.' },
{ ugly: 'discordeno_rest.' }, { ugly: 'discordeno_rest.' },

View File

@@ -1,14 +1,8 @@
{ {
"extends": "tsconfig/base.json", "extends": "tsconfig/base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
}, },
"include": [ "include": ["."],
"." "exclude": ["dist", "build", "node_modules"]
], }
"exclude": [
"dist",
"build",
"node_modules"
]
}

View File

@@ -2,89 +2,48 @@
"$schema": "https://turbo.build/schema.json", "$schema": "https://turbo.build/schema.json",
"pipeline": { "pipeline": {
"build": { "build": {
"outputs": [ "outputs": ["dist/**/*.js"],
"dist/**/*.js" "inputs": ["src/**/*.ts"]
],
"inputs": [
"src/**/*.ts"
]
}, },
"build:type": { "build:type": {
"dependsOn": [ "dependsOn": ["^build:type"],
"^build:type" "outputs": ["dist/**/*.d.ts", "dist/**/*.d.ts.map", "dist/tsconfig.tsbuildinfo"]
],
"outputs": [
"dist/**/*.d.ts",
"dist/**/*.d.ts.map",
"dist/tsconfig.tsbuildinfo"
]
}, },
"release-build": { "release-build": {
"dependsOn": [ "dependsOn": ["^release-build"],
"^release-build" "outputs": ["dist/**"]
],
"outputs": [
"dist/**"
]
}, },
"test:unit-coverage": { "test:unit-coverage": {
"dependsOn": [ "dependsOn": ["^build"],
"^build" "outputs": ["coverage/**"]
],
"outputs": [
"coverage/**"
]
}, },
"test:unit": { "test:unit": {
"dependsOn": [ "dependsOn": ["^build"],
"^build" "outputs": ["coverage/**"]
],
"outputs": [
"coverage/**"
]
}, },
"test:integration": { "test:integration": {
"dependsOn": [ "dependsOn": ["^build"],
"^build" "outputs": ["coverage/**"]
],
"outputs": [
"coverage/**"
]
}, },
"test:test-type": { "test:test-type": {
"dependsOn": [ "dependsOn": ["^build:type"]
"^build:type"
]
}, },
"test:deno-unit": { "test:deno-unit": {
"dependsOn": [ "dependsOn": ["build", "^build"],
"build", "outputs": ["denoTestsDist/**"]
"^build"
],
"outputs": [
"denoTestsDist/**"
]
}, },
"test:e2e": { "test:e2e": {
"dependsOn": [ "dependsOn": ["^build"],
"^build" "outputs": ["coverage/**"]
],
"outputs": [
"coverage/**"
]
}, },
"lint": { "lint": {
"dependsOn": [ "dependsOn": ["^build:type"]
"^build:type"
]
}, },
"fmt": { "fmt": {
"dependsOn": [ "dependsOn": ["^build:type"]
"^build:type"
]
}, },
"dev": { "dev": {
"cache": false "cache": false
} }
} }
} }

View File

@@ -1,18 +1,10 @@
{ {
"entryPointStrategy": "packages", "entryPointStrategy": "packages",
"entryPoints": [ "entryPoints": ["packages/bot", "packages/gateway", "packages/rest", "packages/types", "packages/utils"],
"packages/bot", "logger": "console",
"packages/gateway", "skipErrorChecking": true,
"packages/rest", "out": "./website/docs/generated/",
"packages/types", "cleanOutputDir": false,
"packages/utils" "plugin": ["typedoc-plugin-markdown"],
], "commentStyle": "all"
"logger": "console",
"skipErrorChecking": true,
"out": "./website/docs/generated/",
"cleanOutputDir": false,
"plugin": [
"typedoc-plugin-markdown"
],
"commentStyle": "all"
} }

View File

@@ -1,6 +1,3 @@
module.exports = { module.exports = {
presets: [ presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
require.resolve('@docusaurus/core/lib/babel/preset'), }
],
};

View File

@@ -24,4 +24,4 @@ With that major rework, we began improving things we always wanted to do for a l
## Tips For Migrating From Previous Version ## Tips For Migrating From Previous Version
1. Find all instances of `bot.helpers.getAvatarURL` and replace with `avatarUrl` 1. Find all instances of `bot.helpers.getAvatarURL` and replace with `avatarUrl`
2. Find and replace all `bot.helpers.xxx` with `rest.xxx` where `xxx` is any method on the helpers. 2. Find and replace all `bot.helpers.xxx` with `rest.xxx` where `xxx` is any method on the helpers.

View File

@@ -16,4 +16,3 @@ This guide will proceed with Node.JS but you should apply the same concepts in y
## Choose A Coding Style ## Choose A Coding Style
Discordeno provides you the option to use a Class based approach or a No-Class based approach. If you are willing to take your time and optimize your bot to the max, I highly recommend you go the No-Class route. However, this guide will use the Class based approach as I believe most users will end up choosing this route. Should you require any help with the functional approach please contact us on Discord. Discordeno provides you the option to use a Class based approach or a No-Class based approach. If you are willing to take your time and optimize your bot to the max, I highly recommend you go the No-Class route. However, this guide will use the Class based approach as I believe most users will end up choosing this route. Should you require any help with the functional approach please contact us on Discord.

View File

@@ -204,10 +204,10 @@ Having multiple bot's sending requests from one source will impact your global r
::: :::
```ts ```ts
const MANAGERS = new Collection<string, RestManager>(); const MANAGERS = new Collection<string, RestManager>()
``` ```
Create this MANAGERS collection at the near the top of the file. Then we can begin implementing this in our request handler. We are going to be changing this line: Create this MANAGERS collection at the near the top of the file. Then we can begin implementing this in our request handler. We are going to be changing this line:
```ts ```ts
try { try {
@@ -228,20 +228,19 @@ try {
const result = await manager.makeRequest(req.method, `${manager.baseUrl}${req.url}`, req.body) const result = await manager.makeRequest(req.method, `${manager.baseUrl}${req.url}`, req.body)
``` ```
### Evals ### Evals
One of the last things we should do, is make it possible to run commands on this process. To do this, we simply create a small bot on this process with an eval command that listens for our messages only on our developer server. This way we can dynamically update any properties we may need to. For example, if discord updates the API version, we can easily switch the api version with a simple command. One of the last things we should do, is make it possible to run commands on this process. To do this, we simply create a small bot on this process with an eval command that listens for our messages only on our developer server. This way we can dynamically update any properties we may need to. For example, if discord updates the API version, we can easily switch the api version with a simple command.
Let's make a small bot on this process. Make a file called `services/rest/bot.ts`. Then paste the code below. Let's make a small bot on this process. Make a file called `services/rest/bot.ts`. Then paste the code below.
```ts ````ts
import { createBot } from '@discordeno/bot' import { createBot } from '@discordeno/bot'
import { logger } from '@discordeno/utils' import { logger } from '@discordeno/utils'
import * as util from 'util' import * as util from 'util'
const inspectOptions = { const inspectOptions = {
depth: 1 depth: 1,
} }
const bot = createBot({ const bot = createBot({
@@ -289,9 +288,9 @@ const bot = createBot({
response.push('```') response.push('```')
await message.channel.createMessage(response.join('\n')) await message.channel.createMessage(response.join('\n'))
} },
} },
}) })
``` ````
Now that you have an eval command available on ur `REST` service, whenever you need to modify something quickly you can easily do so from ur developer server where this bot is. For example, should you want to switch to a newer api version, it is as simple as `.eval REST.version = xxx` where xxx is the new API version. Now that you have an eval command available on ur `REST` service, whenever you need to modify something quickly you can easily do so from ur developer server where this bot is. For example, should you want to switch to a newer api version, it is as simple as `.eval REST.version = xxx` where xxx is the new API version.

View File

@@ -35,7 +35,7 @@ export const REST = createRestManager({
proxy: { proxy: {
baseUrl: process.env.REST_URL, baseUrl: process.env.REST_URL,
authorization: process.env.AUTHORIZATION, authorization: process.env.AUTHORIZATION,
} },
}) })
``` ```
@@ -78,10 +78,10 @@ You can adjust the amount of **shardsPerWorker** and **totalWorkers** to fit you
Let's make a file called `services/gateway/index.ts` and paste the following code: Let's make a file called `services/gateway/index.ts` and paste the following code:
```ts ```ts
import { logger } from '@discordeno/utils'; import { logger } from '@discordeno/utils'
import dotenv from 'dotenv'; import dotenv from 'dotenv'
import express from 'express'; import express from 'express'
dotenv.config(); dotenv.config()
const AUTHORIZATION = process.env.AUTHORIZATION as string const AUTHORIZATION = process.env.AUTHORIZATION as string
@@ -104,7 +104,7 @@ app.all('/*', async (req, res) => {
// Identify A Shard // Identify A Shard
switch (req.body.type) { switch (req.body.type) {
case 'REQUEST_MEMBERS': { case 'REQUEST_MEMBERS': {
return await GATEWAY.requestMembers(req.body.guildId, req.body.options); return await GATEWAY.requestMembers(req.body.guildId, req.body.options)
} }
default: default:
logger.error(`[Shard] Unknown request received. ${JSON.stringify(req.body)}`) logger.error(`[Shard] Unknown request received. ${JSON.stringify(req.body)}`)
@@ -166,13 +166,13 @@ Now, let's go ahead and set up the server where we will receive this and start a
Just like before, we are going to make another http listener to listen for incoming events and delegate them outwords. Make a file called `services/gateway/sharding/index.ts` Just like before, we are going to make another http listener to listen for incoming events and delegate them outwords. Make a file called `services/gateway/sharding/index.ts`
```ts ```ts
import { DiscordenoShard } from '@discordeno/gateway'; import { DiscordenoShard } from '@discordeno/gateway'
import { logger } from '@discordeno/utils'; import { logger } from '@discordeno/utils'
import { Intents } from '@discordeno/types'; import { Intents } from '@discordeno/types'
import events from './events.js'; import events from './events.js'
import dotenv from 'dotenv'; import dotenv from 'dotenv'
import express from 'express'; import express from 'express'
dotenv.config(); dotenv.config()
const AUTHORIZATION = process.env.AUTHORIZATION as string const AUTHORIZATION = process.env.AUTHORIZATION as string
const SHARDS = new Collection<number, DiscordenoShard>() const SHARDS = new Collection<number, DiscordenoShard>()
@@ -188,10 +188,10 @@ app.use(
app.use(express.json()) app.use(express.json())
function getUrlFromShardId(totalShards: number, shardId: number) { function getUrlFromShardId(totalShards: number, shardId: number) {
const urls = process.env.EVENT_HANDLER_URLS?.split(',') ?? []; const urls = process.env.EVENT_HANDLER_URLS?.split(',') ?? []
const index = totalShards % shardId; const index = totalShards % shardId
return urls[index] ?? urls[0]; return urls[index] ?? urls[0]
} }
app.all('/*', async (req, res) => { app.all('/*', async (req, res) => {
@@ -203,21 +203,23 @@ app.all('/*', async (req, res) => {
// Identify A Shard // Identify A Shard
switch (req.body.type) { switch (req.body.type) {
case 'IDENTIFY_SHARD': { case 'IDENTIFY_SHARD': {
logger.info(`[Shard] identifying ${SHARDS.has(req.body.shardId) ? 'existing' : 'new'} shard (${req.body.shardId})`); logger.info(`[Shard] identifying ${SHARDS.has(req.body.shardId) ? 'existing' : 'new'} shard (${req.body.shardId})`)
const shard = SHARDS.get(req.body.shardId) ?? new DiscordenoShard({ const shard =
id: req.body.shardId, SHARDS.get(req.body.shardId) ??
connection: { new DiscordenoShard({
compress: req.body.compress, id: req.body.shardId,
intents: req.body.intents, connection: {
properties: req.body.properties, compress: req.body.compress,
token: req.body.token, intents: req.body.intents,
totalShards: req.body.totalShards, properties: req.body.properties,
url: req.body.url, token: req.body.token,
version: req.body.version, totalShards: req.body.totalShards,
}, url: req.body.url,
// TODO: Enable this in the next portion of the guide. version: req.body.version,
// events, },
}); // TODO: Enable this in the next portion of the guide.
// events,
})
SHARDS.set(shard.id, shard) SHARDS.set(shard.id, shard)
await shard.identify() await shard.identify()
@@ -384,8 +386,6 @@ Now let's enable resharding on our bot so we don't need to deal with it. Remembe
- Manual: You can also trigger this manually should you choose. - Manual: You can also trigger this manually should you choose.
- When discord releases a new API version, updates your gateways to new version with no downtime. - When discord releases a new API version, updates your gateways to new version with no downtime.
### Evals ### Evals
One of the last things we should do, is make it possible to run commands on this process. To do this, we simply create a small bot on this process with an eval command that listens for our messages only on our developer server. This way we can dynamically update any properties we may need to. For example, if discord updates the API version, we can easily switch the api version with a simple command. One of the last things we should do, is make it possible to run commands on this process. To do this, we simply create a small bot on this process with an eval command that listens for our messages only on our developer server. This way we can dynamically update any properties we may need to. For example, if discord updates the API version, we can easily switch the api version with a simple command.

View File

@@ -2,4 +2,4 @@ discordeno-monorepo / [Modules](modules.md)
# Discordeno # Discordeno
Thank you for using Discordeno. These docs are generated automatically. If you see any issues please contact us on [Discord](https://discord.gg/ddeno) Thank you for using Discordeno. These docs are generated automatically. If you see any issues please contact us on [Discord](https://discord.gg/ddeno)

View File

@@ -1,9 +1,8 @@
{ {
"label": "Classes", "label": "Classes",
"position": 2, "position": 2,
"link": { "link": {
"type": "generated-index", "type": "generated-index",
"description": "Automatically generated documentation for modules." "description": "Automatically generated documentation for modules."
}
} }
}

View File

@@ -14,7 +14,7 @@
/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
const sidebars = { const sidebars = {
// By default, Docusaurus generates a sidebar from the docs folder structure // By default, Docusaurus generates a sidebar from the docs folder structure
tutorialSidebar: [{type: 'autogenerated', dirName: '.'}], tutorialSidebar: [{ type: 'autogenerated', dirName: '.' }],
// But you can create a sidebar manually // But you can create a sidebar manually
/* /*
@@ -28,6 +28,6 @@ const sidebars = {
}, },
], ],
*/ */
}; }
module.exports = sidebars; module.exports = sidebars