This commit is contained in:
Skillz
2021-05-27 20:43:55 -04:00
481 changed files with 6131 additions and 5360 deletions

View File

@@ -1,30 +1,43 @@
// 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.162.0/containers/deno
{
"name": "Deno",
"dockerFile": "Dockerfile",
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.shell.linux": "/bin/bash",
"terminal.integrated.defaultProfile.linux": "/bin/bash",
"deno.enable": true,
"deno.lint": true,
"editor.defaultFormatter": "denoland.vscode-deno",
"editor.formatOnSave": true,
"editor.minimap.enabled": false,
"editor.wordWrap": "on",
"editor.codeActionsOnSave": {
"source.organizeImports": true,
"source.fixAll": true
}
},
"editor.fontSize": 16,
"workbench.colorTheme": "Material Theme Darker",
"workbench.iconTheme": "eq-material-theme-icons-darker",
"breadcrumbs.enabled": true,
"editor.renderWhitespace": "all",
"editor.suggestSelection": "first",
"editor.formatOnSave": true,
"files.autoSave": "afterDelay",
"editor.fontFamily": "Fira Code, Menlo, Monaco, 'Courier New', monospace",
"typescript.updateImportsOnFileMove.enabled": "always",
"javascript.updateImportsOnFileMove.enabled": "always"
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"denoland.vscode-deno"
]
"denoland.vscode-deno",
"pkief.material-icon-theme",
"coenraads.bracket-pair-colorizer",
"equinusocio.vsc-material-theme",
"tabnine.tabnine-vscode"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Uncomment to use the Docker CLI from inside the container. See https://aka.ms/vscode-remote/samples/docker-from-docker.
// "mounts": [ "source=/var/run/docker.sock,target=/var/run/docker.sock,type=bind" ],
// Uncomment to connect as a non-root user. See https://aka.ms/vscode-remote/containers/non-root.
// "remoteUser": "vscode"
// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode"
}

View File

@@ -1,7 +1,7 @@
# Contributing
- Read the [style guide](#style-guide).
- Ask for help on the [official Discord server](https:)
- Ask for help on the [official Discord server](https://discord.gg/5vBgXk3UcZ)
- If you are going to work on an issue, mention so in the issue comments before
you start working on the issue.
- If you are going to work on a new feature, create an issue and discuss with
@@ -38,29 +38,41 @@
## Types Guide
- Must use snake case (according to Discord API).
- Must use camel case (same property name as in the docs just in camel case).
- Each field or property must be accompanied with a reasonable JSDoc comment
right above its type definition.
- The name of the type must be prefixed with `Discord`.
- Must be placed inside of the types module (in `src/types` directory).
Example:
```ts
/** https://discord.com/developers/docs/resources/user#user-object */
export interface User {
/** The user's id */
id: string;
/** The user's username, not unique across the platform */
username: string;
/** The user's 4-digit discord-tag */
discriminator: string;
/** The user's avatar hash */
avatar: string | null;
/** Whether the user belongs to an OAuth2 application */
bot?: boolean;
/** Whether the user is an Official Discord System user (part of the urgent message system) */
system?: boolean;
/** Whether the user has two factor enabled on their account */
mfaEnabled?: boolean;
/** The user's chosen language option */
locale?: string;
/** Whether the email on this account has been verified */
verified?: boolean;
email?: string;
flags?: number;
premiumType?: number;
/** The user's email */
email?: string | null;
/** The flags on a user's account */
flags?: DiscordUserFlags;
/** The type of Nitro subscription on a user's account */
premiumType?: DiscordPremiumTypes;
/** The public flags on a user's account */
publicFlags?: DiscordUserFlags;
}
export type DiscordUser = SnakeCasedPropertiesDeep<DiscordUserInternal>;
```

View File

@@ -6,9 +6,5 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: denoland/setup-deno@main
- name: Run fmt script
run: deno fmt
- name: Commit formatted files
uses: EndBug/add-and-commit@v7
- name: Run lint script
run: deno lint src/** test/** --unstable --ignore=./src/types
run: deno lint ./src ./tests

18
.github/workflows/local_tests.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: Local Tests Only
on:
push:
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
deno: ["v1.x"]
steps:
- uses: actions/checkout@v2
- uses: denoland/setup-deno@main
with:
deno-version: ${{ matrix.deno }}
- name: Cache dependencies
run: deno cache mod.ts
- name: Run Local tests that don't need Discord's API
run: deno test -A tests/local.ts

29
.github/workflows/pr_tests.yml vendored Normal file
View File

@@ -0,0 +1,29 @@
name: Test Contributor Pull Requests
on: issue_comment
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
deno: ["v1.x"]
steps:
- uses: actions/checkout@v2
- uses: denoland/setup-deno@main
with:
deno-version: ${{ matrix.deno }}
- name: Cache dependencies
run: deno cache mod.ts
- name: Run tests if requested by maintainers
if: ${{ github.event.issue.pull_request && github.event.comment.body == 'run-tests' && (github.actor == 'Skillz4Killz' || github.actor == 'itohatweb') }}
run: DISCORD_TOKEN=${{ env.DISCORD_TOKEN }} deno test --unstable --coverage=coverage -A tests/mod.ts
env:
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}
# TODO: add coverage back when it is stable
# - name: Create coverage report
# run: deno --unstable --exclude=test coverage ./coverage --lcov > coverage.lcov
# - name: Collect and upload the coverage report
# uses: codecov/codecov-action@v1.0.10
# with:
# file: ./coverage.lcov
env:
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}

26
.github/workflows/prettier.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: Prettier
on: [push, pull_request]
jobs:
prettier:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
# Make sure the actual branch is checked out when running on pull requests
ref: ${{ github.head_ref }}
# This is important to fetch the changes to the previous commit
fetch-depth: 0
- name: Prettify code
uses: creyD/prettier_action@v3.3
with:
commit_message: "change: prettier code"
# This part is also where you can pass other options, for example:
prettier_options: --write **/*
only_changed: True
env:
GITHUB_TOKEN: ${{ github.token }}

View File

@@ -1,8 +1,6 @@
name: Test
on:
push:
pull_request:
types: [labeled]
jobs:
test:
runs-on: ubuntu-latest
@@ -19,14 +17,14 @@ jobs:
- name: Run test script for maintainers
if: ${{ github.actor == 'Skillz4Killz' || github.actor == 'itohatweb' }}
run: deno test --unstable --coverage=coverage -A tests/mod.ts
- name: Run test script if label added
if: ${{ github.event_name == 'pull_request' && github.event.action == 'labeled' && github.event.label.name == 'run-tests' }}
run: DISCORD_TOKEN=${{ secrets.DISCORD_TOKEN }} deno test --unstable --coverage=coverage --allow-net tests/mod.ts
- name: Create coverage report
run: deno --unstable coverage ./coverage --lcov > coverage.lcov
- name: Collect and upload the coverage report
uses: codecov/codecov-action@v1.0.10
with:
file: ./coverage.lcov
# TODO: add coverage back when it is stable
# - name: Create coverage report
# if: github.ref == 'refs/heads/main'
# run: deno --unstable coverage --exclude=test ./coverage --lcov > coverage.lcov
# - name: Collect and upload the coverage report
# if: github.ref == 'refs/heads/main'
# uses: codecov/codecov-action@v1.0.10
# with:
# file: ./coverage.lcov
env:
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}

3
.gitignore vendored
View File

@@ -26,3 +26,6 @@ desktop.ini
!.vscode/tasks.json
!.vscode/launch.json
*.code-workspace
# Sublime Text
.sublime-project

3
.prettierrc Normal file
View File

@@ -0,0 +1,3 @@
{
"printWidth": 120
}

View File

@@ -1,7 +1,7 @@
{
"deno.enable": true,
"deno.lint": true,
"editor.defaultFormatter": "denoland.vscode-deno",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true,

214
LICENSE
View File

@@ -1,21 +1,201 @@
MIT License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2020-2021 Discordeno
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021 Discordeno
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -9,7 +9,11 @@ Discordeno follows [Semantic Versioning](https://semver.org/)
[![Discord](https://img.shields.io/discord/785384884197392384?color=7289da&logo=discord&logoColor=dark)](https://discord.com/invite/5vBgXk3UcZ)
![Lint](https://github.com/discordeno/discordeno/workflows/Lint/badge.svg)
![Test](https://github.com/discordeno/discordeno/workflows/Test/badge.svg)
<!--
TODO: add coverage back when it is stable
[![Coverage](https://img.shields.io/codecov/c/gh/discordeno/discordeno)](https://codecov.io/gh/discordeno/discordeno)
-->
## Features
@@ -37,16 +41,14 @@ Here is a minimal example to get started with:
import { startBot } from "https://deno.land/x/discordeno/mod.ts";
startBot({
token: "BOT TOKEN",
intents: ["GUILDS", "GUILD_MESSAGES"],
token: "BOT_TOKEN",
intents: ["Guilds", "GuildMessages"],
eventHandlers: {
ready() {
console.log("Successfully connected to gateway");
},
messageCreate(message) {
if (message.content === "ping") {
message.reply("Pong using Discordeno!");
}
// Process the message with your command handler here
},
},
});

View File

@@ -1 +0,0 @@
export { encode } from "https://deno.land/std@0.90.0/encoding/base64.ts";

10
mod.ts
View File

@@ -3,15 +3,7 @@ export * from "./src/cache.ts";
export * from "./src/handlers/mod.ts";
export * from "./src/helpers/mod.ts";
export * from "./src/rest/mod.ts";
export * from "./src/structures/channel.ts";
export * from "./src/structures/guild.ts";
export * from "./src/structures/member.ts";
export * from "./src/structures/message.ts";
export * from "./src/structures/mod.ts";
export * from "./src/structures/role.ts";
export * from "./src/types/mod.ts";
export * from "./src/util/collection.ts";
export * from "./src/util/constants.ts";
export * from "./src/util/permissions.ts";
export * from "./src/util/utils.ts";
export * from "./src/util/mod.ts";
export * from "./src/ws/mod.ts";

View File

@@ -1,13 +1,15 @@
import { getGatewayBot } from "./helpers/misc/get_gateway_bot.ts";
import { rest } from "./rest/rest.ts";
import { EventHandlers } from "./types/discordeno/eventHandlers.ts";
import type { EventHandlers } from "./types/discordeno/event_handlers.ts";
import { DiscordGatewayIntents } from "./types/gateway/gateway_intents.ts";
import { baseEndpoints, GATEWAY_VERSION } from "./util/constants.ts";
import { snowflakeToBigint } from "./util/bigint.ts";
import { GATEWAY_VERSION } from "./util/constants.ts";
import { ws } from "./ws/ws.ts";
// deno-lint-ignore prefer-const
export let secretKey = "";
export let botId = "";
export let applicationId = "";
export let botId = 0n;
export let applicationId = 0n;
export let eventHandlers: EventHandlers = {};
@@ -18,18 +20,14 @@ export async function startBot(config: BotConfig) {
ws.identifyPayload.token = `Bot ${config.token}`;
rest.token = `Bot ${config.token}`;
ws.identifyPayload.intents = config.intents.reduce(
(
bits,
next,
) => (bits |= typeof next === "string"
? DiscordGatewayIntents[next]
: next),
0,
(bits, next) => (bits |= typeof next === "string" ? DiscordGatewayIntents[next] : next),
0
);
// Initial API connection to get info about bots connection
ws.botGatewayData = await getGatewayBot();
ws.maxShards = ws.maxShards || ws.botGatewayData.shards;
ws.lastShardId = ws.lastShardId === 1 ? ws.botGatewayData.shards - 1 : ws.lastShardId;
// Explicitly append gateway version and encoding
ws.botGatewayData.url += `?v=${GATEWAY_VERSION}&encoding=json`;
@@ -39,69 +37,24 @@ export async function startBot(config: BotConfig) {
ws.spawnShards();
}
export function replaceEventHandlers(newEventHandlers: EventHandlers) {
eventHandlers = newEventHandlers;
}
/** Allows you to dynamically update the event handlers by passing in new eventHandlers */
export function updateEventHandlers(newEventHandlers: EventHandlers) {
eventHandlers = {
...eventHandlers,
...newEventHandlers,
};
// Object.assign instead of ... operator because of the Proxy used
Object.assign(eventHandlers, newEventHandlers);
}
/** INTERNAL LIB function used to set the bot Id once the READY event is sent by Discord. */
export function setBotId(id: string) {
if (botId !== id) botId = id;
botId = snowflakeToBigint(id);
}
/** INTERNAL LIB function used to set the application Id once the READY event is sent by Discord. */
export function setApplicationId(id: string) {
if (applicationId !== id) applicationId = id;
}
// BIG BRAIN BOT STUFF ONLY BELOW THIS
/**
* This function should be used only by bot developers whose bots are in over 25,000 servers.
* Please be aware if you are a beginner developer using this, things will not work as per the guides. This is for advanced developers only!
*
* Advanced Devs: This function will allow you to have an insane amount of customization potential as when you get to large bots you need to be able to optimize every tiny detail to make you bot work the way you need.
*/
export async function startBigBrainBot(options: BigBrainBotConfig) {
rest.token = `Bot ${options.token}`;
if (options.secretKey) secretKey = options.secretKey;
if (options.restURL) baseEndpoints.BASE_URL = options.restURL;
if (options.cdnURL) baseEndpoints.CDN_URL = options.cdnURL;
if (options.eventHandlers) eventHandlers = options.eventHandlers;
// PROXY DOESNT NEED US SPAWNING SHARDS
if (!options.wsPort) {
ws.identifyPayload.token = `Bot ${options.token}`;
if (options.compress) {
ws.identifyPayload.compress = options.compress;
}
ws.identifyPayload.intents = options.intents.reduce(
(
bits,
next,
) => (bits |= typeof next === "string"
? DiscordGatewayIntents[next]
: next),
0,
);
// Initial API connection to get info about bots connection
ws.botGatewayData = await getGatewayBot();
ws.maxShards = ws.maxShards ||
ws.botGatewayData.shards;
ws.lastShardId = options.lastShardId || ws.botGatewayData.shards;
// Explicitly append gateway version and encoding
ws.botGatewayData.url += `?v=${GATEWAY_VERSION}&encoding=json`;
proxyWSURL = ws.botGatewayData.url;
ws.spawnShards(options.firstShardId);
}
applicationId = snowflakeToBigint(id);
}
export interface BotConfig {
@@ -110,20 +63,3 @@ export interface BotConfig {
intents: (DiscordGatewayIntents | keyof typeof DiscordGatewayIntents)[];
eventHandlers?: EventHandlers;
}
export interface BigBrainBotConfig extends BotConfig {
/** The first shard to start at for this worker. Use this to control which shards to run in each worker. */
firstShardId: number;
/** The last shard to start for this worker. By default it will be 25 + the firstShardId. */
lastShardId?: number;
/** The maximum shard Id number. Useful for zero-downtime updates or resharding. */
maxShards?: number;
/** This can be used to forward the ws handling to a proxy. It will disable the sharding done by the bot side. */
wsPort?: number;
/** This can be used to forward the REST handling to a proxy. */
restURL?: string;
/** This can be used to forward the CDN handling to a proxy. */
cdnURL?: string;
/** This is the authorization header that your servers will send. Helpful to prevent DDOS attacks and such. */
secretKey?: string;
}

View File

@@ -1,41 +1,34 @@
// deno-lint-ignore-file require-await no-explicit-any prefer-const
import { DiscordenoChannel } from "./structures/channel.ts";
import { DiscordenoGuild } from "./structures/guild.ts";
import { DiscordenoMember } from "./structures/member.ts";
import { DiscordenoMessage } from "./structures/message.ts";
import { Emoji } from "./types/emojis/emoji.ts";
import { PresenceUpdate } from "./types/misc/presence_update.ts";
import type { DiscordenoChannel } from "./structures/channel.ts";
import type { DiscordenoGuild } from "./structures/guild.ts";
import type { DiscordenoMember } from "./structures/member.ts";
import type { DiscordenoMessage } from "./structures/message.ts";
import type { PresenceUpdate } from "./types/activity/presence_update.ts";
import type { Emoji } from "./types/emojis/emoji.ts";
import { Collection } from "./util/collection.ts";
export const cache = {
isReady: false,
/** All of the guild objects the bot has access to, mapped by their Ids */
guilds: new Collection<string, DiscordenoGuild>(),
guilds: new Collection<bigint, DiscordenoGuild>(),
/** All of the channel objects the bot has access to, mapped by their Ids */
channels: new Collection<string, DiscordenoChannel>(),
channels: new Collection<bigint, DiscordenoChannel>(),
/** All of the message objects the bot has cached since the bot acquired `READY` state, mapped by their Ids */
messages: new Collection<string, DiscordenoMessage>(),
messages: new Collection<bigint, DiscordenoMessage>(),
/** All of the member objects that have been cached since the bot acquired `READY` state, mapped by their Ids */
members: new Collection<string, DiscordenoMember>(),
members: new Collection<bigint, DiscordenoMember>(),
/** All of the unavailable guilds, mapped by their Ids (id, timestamp) */
unavailableGuilds: new Collection<string, number>(),
unavailableGuilds: new Collection<bigint, number>(),
/** All of the presence update objects received in PRESENCE_UPDATE gateway event, mapped by their user Id */
presences: new Collection<string, PresenceUpdate>(),
presences: new Collection<bigint, PresenceUpdate>(),
fetchAllMembersProcessingRequests: new Collection<
string,
(
value:
| Collection<string, DiscordenoMember>
| PromiseLike<Collection<string, DiscordenoMember>>,
) => void
(value: Collection<bigint, DiscordenoMember> | PromiseLike<Collection<bigint, DiscordenoMember>>) => void
>(),
executedSlashCommands: new Collection<string, string>(),
executedSlashCommands: new Set<string>(),
get emojis() {
return new Collection<string, Emoji>(
this.guilds.reduce(
(a, b) => [...a, ...b.emojis.map((e) => [e.id, e])],
[] as any[],
),
return new Collection<bigint, Emoji>(
this.guilds.reduce((a, b) => [...a, ...b.emojis.map((e) => [e.id, e])], [] as any[])
);
},
};
@@ -46,11 +39,11 @@ export let cacheHandlers = {
return cache[table].clear();
},
/** Deletes 1 item from cache using the key */
async delete(table: TableName, key: string) {
async delete(table: TableName, key: bigint) {
return cache[table].delete(key);
},
/** Check if something exists in cache with a key */
async has(table: TableName, key: string) {
async has(table: TableName, key: bigint) {
return cache[table].has(key);
},
@@ -70,142 +63,72 @@ export let cacheHandlers = {
filter,
};
export type TableName =
| "guilds"
| "unavailableGuilds"
| "channels"
| "messages"
| "members"
| "presences";
export type TableName = "guilds" | "unavailableGuilds" | "channels" | "messages" | "members" | "presences";
function set(
table: "guilds",
key: string,
value: DiscordenoGuild,
): Promise<Collection<string, DiscordenoGuild>>;
function set(
table: "channels",
key: string,
value: DiscordenoChannel,
): Promise<Collection<string, DiscordenoChannel>>;
function set(
table: "messages",
key: string,
value: DiscordenoMessage,
): Promise<Collection<string, DiscordenoMessage>>;
function set(
table: "members",
key: string,
value: DiscordenoMember,
): Promise<Collection<string, DiscordenoMember>>;
function set(
table: "presences",
key: string,
value: PresenceUpdate,
): Promise<Collection<string, PresenceUpdate>>;
function set(
table: "unavailableGuilds",
key: string,
value: number,
): Promise<Collection<string, number>>;
async function set(table: TableName, key: string, value: any) {
function set(table: "guilds", key: bigint, value: DiscordenoGuild): Promise<Collection<bigint, DiscordenoGuild>>;
function set(table: "channels", key: bigint, value: DiscordenoChannel): Promise<Collection<bigint, DiscordenoChannel>>;
function set(table: "messages", key: bigint, value: DiscordenoMessage): Promise<Collection<bigint, DiscordenoMessage>>;
function set(table: "members", key: bigint, value: DiscordenoMember): Promise<Collection<bigint, DiscordenoMember>>;
function set(table: "presences", key: bigint, value: PresenceUpdate): Promise<Collection<bigint, PresenceUpdate>>;
function set(table: "unavailableGuilds", key: bigint, value: number): Promise<Collection<bigint, number>>;
async function set(table: TableName, key: bigint, value: any) {
return cache[table].set(key, value);
}
function get(
table: "guilds",
key: string,
): Promise<DiscordenoGuild | undefined>;
function get(
table: "channels",
key: string,
): Promise<DiscordenoChannel | undefined>;
function get(
table: "messages",
key: string,
): Promise<DiscordenoMessage | undefined>;
function get(
table: "members",
key: string,
): Promise<DiscordenoMember | undefined>;
function get(
table: "presences",
key: string,
): Promise<PresenceUpdate | undefined>;
function get(
table: "unavailableGuilds",
key: string,
): Promise<number | undefined>;
async function get(table: TableName, key: string) {
function get(table: "guilds", key: bigint): Promise<DiscordenoGuild | undefined>;
function get(table: "channels", key: bigint): Promise<DiscordenoChannel | undefined>;
function get(table: "messages", key: bigint): Promise<DiscordenoMessage | undefined>;
function get(table: "members", key: bigint): Promise<DiscordenoMember | undefined>;
function get(table: "presences", key: bigint): Promise<PresenceUpdate | undefined>;
function get(table: "unavailableGuilds", key: bigint): Promise<number | undefined>;
async function get(table: TableName, key: bigint) {
return cache[table].get(key);
}
function forEach(
table: "guilds",
callback: (
value: DiscordenoGuild,
key: string,
map: Map<string, DiscordenoGuild>,
) => unknown,
callback: (value: DiscordenoGuild, key: bigint, map: Map<bigint, DiscordenoGuild>) => unknown
): void;
function forEach(
table: "unavailableGuilds",
callback: (value: number, key: string, map: Map<string, number>) => unknown,
callback: (value: number, key: bigint, map: Map<bigint, number>) => unknown
): void;
function forEach(
table: "channels",
callback: (
value: DiscordenoChannel,
key: string,
map: Map<string, DiscordenoChannel>,
) => unknown,
callback: (value: DiscordenoChannel, key: bigint, map: Map<bigint, DiscordenoChannel>) => unknown
): void;
function forEach(
table: "messages",
callback: (
value: DiscordenoMessage,
key: string,
map: Map<string, DiscordenoMessage>,
) => unknown,
callback: (value: DiscordenoMessage, key: bigint, map: Map<bigint, DiscordenoMessage>) => unknown
): void;
function forEach(
table: "members",
callback: (
value: DiscordenoMember,
key: string,
map: Map<string, DiscordenoMember>,
) => unknown,
callback: (value: DiscordenoMember, key: bigint, map: Map<bigint, DiscordenoMember>) => unknown
): void;
function forEach(
table: TableName,
callback: (value: any, key: string, map: Map<string, any>) => unknown,
) {
function forEach(table: TableName, callback: (value: any, key: bigint, map: Map<bigint, any>) => unknown) {
return cache[table].forEach(callback);
}
function filter(
table: "guilds",
callback: (value: DiscordenoGuild, key: string) => boolean,
): Promise<Collection<string, DiscordenoGuild>>;
callback: (value: DiscordenoGuild, key: bigint) => boolean
): Promise<Collection<bigint, DiscordenoGuild>>;
function filter(
table: "unavailableGuilds",
callback: (value: number, key: string) => boolean,
): Promise<Collection<string, number>>;
callback: (value: number, key: bigint) => boolean
): Promise<Collection<bigint, number>>;
function filter(
table: "channels",
callback: (value: DiscordenoChannel, key: string) => boolean,
): Promise<Collection<string, DiscordenoChannel>>;
callback: (value: DiscordenoChannel, key: bigint) => boolean
): Promise<Collection<bigint, DiscordenoChannel>>;
function filter(
table: "messages",
callback: (value: DiscordenoMessage, key: string) => boolean,
): Promise<Collection<string, DiscordenoMessage>>;
callback: (value: DiscordenoMessage, key: bigint) => boolean
): Promise<Collection<bigint, DiscordenoMessage>>;
function filter(
table: "members",
callback: (value: DiscordenoMember, key: string) => boolean,
): Promise<Collection<string, DiscordenoMember>>;
async function filter(
table: TableName,
callback: (value: any, key: string) => boolean,
) {
callback: (value: DiscordenoMember, key: bigint) => boolean
): Promise<Collection<bigint, DiscordenoMember>>;
async function filter(table: TableName, callback: (value: any, key: bigint) => boolean) {
return cache[table].filter(callback);
}

View File

@@ -1,8 +1,8 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { Channel } from "../../types/channels/channel.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Channel } from "../../types/channels/channel.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleChannelCreate(data: DiscordGatewayPayload) {
const payload = data.d as Channel;

View File

@@ -1,44 +1,54 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { Channel } from "../../types/channels/channel.ts";
import type { Channel } from "../../types/channels/channel.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleChannelDelete(data: DiscordGatewayPayload) {
const payload = data.d as Channel;
const cachedChannel = await cacheHandlers.get("channels", payload.id);
const cachedChannel = await cacheHandlers.get("channels", snowflakeToBigint(payload.id));
if (!cachedChannel) return;
if (
cachedChannel.type === DiscordChannelTypes.GUILD_VOICE && payload.guildId
) {
const guild = await cacheHandlers.get("guilds", payload.guildId);
if (cachedChannel.type === DiscordChannelTypes.GuildVoice && payload.guildId) {
const guild = await cacheHandlers.get("guilds", cachedChannel.guildId);
if (guild) {
return Promise.all(guild.voiceStates.map(async (vs, key) => {
if (vs.channelId !== payload.id) return;
return Promise.all(
guild.voiceStates.map(async (vs, key) => {
if (vs.channelId !== cachedChannel.id) return;
// Since this channel was deleted all voice states for this channel should be deleted
guild.voiceStates.delete(key);
// Since this channel was deleted all voice states for this channel should be deleted
guild.voiceStates.delete(key);
const member = await cacheHandlers.get("members", vs.userId);
if (!member) return;
const member = await cacheHandlers.get("members", vs.userId);
if (!member) return;
eventHandlers.voiceChannelLeave?.(member, vs.channelId);
}));
eventHandlers.voiceChannelLeave?.(member, vs.channelId);
})
);
}
}
await cacheHandlers.delete("channels", payload.id);
cacheHandlers.forEach("messages", (message) => {
eventHandlers.debug?.(
"loop",
`Running forEach messages loop in CHANNEL_DELTE file.`,
);
if (message.channelId === payload.id) {
cacheHandlers.delete("messages", message.id);
}
});
if (
[
DiscordChannelTypes.GuildText,
DiscordChannelTypes.DM,
DiscordChannelTypes.GroupDm,
DiscordChannelTypes.GuildNews,
].includes(payload.type)
) {
await cacheHandlers.delete("channels", snowflakeToBigint(payload.id));
cacheHandlers.forEach("messages", (message) => {
eventHandlers.debug?.("loop", `Running forEach messages loop in CHANNEL_DELTE file.`);
if (message.channelId === snowflakeToBigint(payload.id)) {
cacheHandlers.delete("messages", message.id);
}
});
}
await cacheHandlers.delete("channels", snowflakeToBigint(payload.id));
eventHandlers.channelDelete?.(cachedChannel);
}

View File

@@ -1,17 +1,16 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { ChannelPinsUpdate } from "../../types/channels/channel_pins_update.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { ChannelPinsUpdate } from "../../types/channels/channel_pins_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleChannelPinsUpdate(data: DiscordGatewayPayload) {
const payload = data.d as ChannelPinsUpdate;
const channel = await cacheHandlers.get("channels", payload.channelId);
const channel = await cacheHandlers.get("channels", snowflakeToBigint(payload.channelId));
if (!channel) return;
const guild = payload.guildId
? await cacheHandlers.get("guilds", payload.guildId)
: undefined;
const guild = payload.guildId ? await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId)) : undefined;
eventHandlers.channelPinsUpdate?.(channel, guild, payload.lastPinTimestamp);
}

View File

@@ -1,17 +1,17 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { Channel } from "../../types/channels/channel.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Channel } from "../../types/channels/channel.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleChannelUpdate(data: DiscordGatewayPayload) {
const payload = data.d as Channel;
const cachedChannel = await cacheHandlers.get("channels", payload.id);
const cachedChannel = await cacheHandlers.get("channels", snowflakeToBigint(payload.id));
if (!cachedChannel) return;
const discordenoChannel = await structures.createDiscordenoChannel(payload);
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
if (!cachedChannel) return;
eventHandlers.channelUpdate?.(discordenoChannel, cachedChannel);
}

View File

@@ -0,0 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleStageInstanceCreate(data: DiscordGatewayPayload) {
eventHandlers.stageInstanceCreate?.(data.d as StageInstance);
}

View File

@@ -0,0 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleStageInstanceDelete(data: DiscordGatewayPayload) {
eventHandlers.stageInstanceDelete?.(data.d as StageInstance);
}

View File

@@ -0,0 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export function handleStageInstanceUpdate(data: DiscordGatewayPayload) {
eventHandlers.stageInstanceUpdate?.(data.d as StageInstance);
}

View File

@@ -0,0 +1,14 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { Channel } from "../../types/channels/channel.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
export async function handleThreadCreate(data: DiscordGatewayPayload) {
const payload = data.d as Channel;
const discordenoChannel = await structures.createDiscordenoChannel(payload);
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
eventHandlers.threadCreate?.(discordenoChannel);
}

View File

@@ -0,0 +1,22 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { Channel } from "../../types/channels/channel.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleThreadDelete(data: DiscordGatewayPayload) {
const payload = data.d as Channel;
const cachedChannel = await cacheHandlers.get("channels", snowflakeToBigint(payload.id));
if (!cachedChannel) return;
await cacheHandlers.delete("channels", snowflakeToBigint(payload.id));
cacheHandlers.forEach("messages", (message) => {
eventHandlers.debug?.("loop", `Running forEach messages loop in CHANNEL_DELTE file.`);
if (message.channelId === snowflakeToBigint(payload.id)) {
cacheHandlers.delete("messages", message.id);
}
});
eventHandlers.threadDelete?.(cachedChannel);
}

View File

@@ -0,0 +1,26 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordenoChannel } from "../../structures/channel.ts";
import { structures } from "../../structures/mod.ts";
import { ThreadListSync } from "../../types/channels/threads/thread_list_sync.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { Collection } from "../../util/collection.ts";
export async function handleThreadListSync(data: DiscordGatewayPayload) {
const payload = data.d as ThreadListSync;
const discordenoChannels = await Promise.all(
payload.threads.map(async (thread) => {
const discordenoChannel = await structures.createDiscordenoChannel(thread, snowflakeToBigint(payload.guildId));
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
return discordenoChannel;
})
);
const threads = new Collection<bigint, DiscordenoChannel>(discordenoChannels.map((t) => [t.id, t]));
eventHandlers.threadListSync?.(threads, payload.members, snowflakeToBigint(payload.guildId));
}

View File

@@ -0,0 +1,16 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { ThreadMembersUpdate } from "../../types/channels/threads/thread_members_update.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleThreadMembersUpdate(data: DiscordGatewayPayload) {
const payload = data.d as ThreadMembersUpdate;
const thread = await cacheHandlers.get("channels", snowflakeToBigint(payload.id));
if (!thread) return;
thread.memberCount = payload.memberCount;
await cacheHandlers.set("channels", thread.id, thread);
eventHandlers.threadMembersUpdate?.(payload);
}

View File

@@ -0,0 +1,17 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { ThreadMember } from "../../types/channels/threads/thread_member.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleThreadMemberUpdate(data: DiscordGatewayPayload) {
const payload = data.d as ThreadMember;
const thread = await cacheHandlers.get("channels", snowflakeToBigint(payload.id));
if (!thread) return;
thread.member = payload;
await cacheHandlers.set("channels", thread.id, thread);
eventHandlers.threadMemberUpdate?.(payload);
}

View File

@@ -0,0 +1,17 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { Channel } from "../../types/channels/channel.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleThreadUpdate(data: DiscordGatewayPayload) {
const payload = data.d as Channel;
const oldChannel = await cacheHandlers.get("channels", snowflakeToBigint(payload.id));
if (!oldChannel) return;
const discordenoChannel = await structures.createDiscordenoChannel(payload);
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
eventHandlers.threadUpdate?.(discordenoChannel, oldChannel);
}

View File

@@ -1,13 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import {
ApplicationCommandCreateUpdateDelete,
} from "../../types/interactions/application_command_create_update_delete.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { ApplicationCommandCreateUpdateDelete } from "../../types/interactions/commands/application_command_create_update_delete.ts";
export function handleApplicationCommandCreate(
data: DiscordGatewayPayload,
) {
eventHandlers.applicationCommandCreate?.(
data.d as ApplicationCommandCreateUpdateDelete,
);
export function handleApplicationCommandCreate(data: DiscordGatewayPayload) {
eventHandlers.applicationCommandCreate?.(data.d as ApplicationCommandCreateUpdateDelete);
}

View File

@@ -1,11 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import {
ApplicationCommandCreateUpdateDelete,
} from "../../types/interactions/application_command_create_update_delete.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { ApplicationCommandCreateUpdateDelete } from "../../types/interactions/commands/application_command_create_update_delete.ts";
export function handleApplicationCommandDelete(data: DiscordGatewayPayload) {
eventHandlers.applicationCommandDelete?.(
data.d as ApplicationCommandCreateUpdateDelete,
);
eventHandlers.applicationCommandDelete?.(data.d as ApplicationCommandCreateUpdateDelete);
}

View File

@@ -1,11 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import {
ApplicationCommandCreateUpdateDelete,
} from "../../types/interactions/application_command_create_update_delete.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { ApplicationCommandCreateUpdateDelete } from "../../types/interactions/commands/application_command_create_update_delete.ts";
export function handleApplicationCommandUpdate(data: DiscordGatewayPayload) {
eventHandlers.applicationCommandUpdate?.(
data.d as ApplicationCommandCreateUpdateDelete,
);
eventHandlers.applicationCommandUpdate?.(data.d as ApplicationCommandCreateUpdateDelete);
}

View File

@@ -1,24 +1,19 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { GuildEmojisUpdate } from "../../types/emojis/guild_emojis_update.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildEmojisUpdate } from "../../types/emojis/guild_emojis_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { Collection } from "../../util/collection.ts";
export async function handleGuildEmojisUpdate(data: DiscordGatewayPayload) {
const payload = data.d as GuildEmojisUpdate;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
const cachedEmojis = guild.emojis;
guild.emojis = new Collection(
payload.emojis.map((emoji) => [emoji.id!, emoji]),
);
guild.emojis = new Collection(payload.emojis.map((emoji) => [snowflakeToBigint(emoji.id!), emoji]));
await cacheHandlers.set("guilds", payload.guildId, guild);
await cacheHandlers.set("guilds", guild.id, guild);
eventHandlers.guildEmojisUpdate?.(
guild,
guild.emojis,
cachedEmojis,
);
eventHandlers.guildEmojisUpdate?.(guild, guild.emojis, cachedEmojis);
}

View File

@@ -1,13 +1,14 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildBanAddRemove } from "../../types/guilds/guild_ban_add_remove.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildBanAddRemove } from "../../types/guilds/guild_ban_add_remove.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildBanAdd(data: DiscordGatewayPayload) {
const payload = data.d as GuildBanAddRemove;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
const member = await cacheHandlers.get("members", payload.user.id);
const member = await cacheHandlers.get("members", snowflakeToBigint(payload.user.id));
eventHandlers.guildBanAdd?.(guild, payload.user, member);
}

View File

@@ -1,13 +1,14 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildBanAddRemove } from "../../types/guilds/guild_ban_add_remove.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildBanAddRemove } from "../../types/guilds/guild_ban_add_remove.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildBanRemove(data: DiscordGatewayPayload) {
const payload = data.d as GuildBanAddRemove;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
const member = await cacheHandlers.get("members", payload.user.id);
const member = await cacheHandlers.get("members", snowflakeToBigint(payload.user.id));
eventHandlers.guildBanRemove?.(guild, payload.user, member);
}

View File

@@ -1,34 +1,29 @@
import { eventHandlers } from "../../bot.ts";
import { cache, cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { Guild } from "../../types/guilds/guild.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Guild } from "../../types/guilds/guild.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { ws } from "../../ws/ws.ts";
export async function handleGuildCreate(
data: DiscordGatewayPayload,
shardId: number,
) {
export async function handleGuildCreate(data: DiscordGatewayPayload, shardId: number) {
const payload = data.d as Guild;
// When shards resume they emit GUILD_CREATE again.
if (await cacheHandlers.has("guilds", payload.id)) return;
if (await cacheHandlers.has("guilds", snowflakeToBigint(payload.id))) return;
const discordenoGuild = await structures.createDiscordenoGuild(
payload,
shardId,
);
await cacheHandlers.set("guilds", discordenoGuild.id, discordenoGuild);
const guild = await structures.createDiscordenoGuild(payload, shardId);
await cacheHandlers.set("guilds", guild.id, guild);
const shard = ws.shards.get(shardId);
if (shard?.unavailableGuildIds.has(payload.id)) {
await cacheHandlers.delete("unavailableGuilds", payload.id);
if (shard?.unavailableGuildIds.has(guild.id)) {
await cacheHandlers.delete("unavailableGuilds", guild.id);
shard.unavailableGuildIds.delete(guild.id);
shard.lastAvailable = Date.now();
shard.unavailableGuildIds.delete(payload.id);
return eventHandlers.guildAvailable?.(discordenoGuild);
return eventHandlers.guildAvailable?.(guild);
}
if (!cache.isReady) return eventHandlers.guildLoaded?.(discordenoGuild);
eventHandlers.guildCreate?.(discordenoGuild);
if (!cache.isReady) return eventHandlers.guildLoaded?.(guild);
eventHandlers.guildCreate?.(guild);
}

View File

@@ -1,25 +1,22 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { UnavailableGuild } from "../../types/guilds/unavailable_guild.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { UnavailableGuild } from "../../types/guilds/unavailable_guild.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { ws } from "../../ws/ws.ts";
export async function handleGuildDelete(
data: DiscordGatewayPayload,
shardId: number,
) {
export async function handleGuildDelete(data: DiscordGatewayPayload, shardId: number) {
const payload = data.d as UnavailableGuild;
const guild = await cacheHandlers.get("guilds", payload.id);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.id));
if (!guild) return;
await cacheHandlers.delete("guilds", payload.id);
await cacheHandlers.delete("guilds", guild.id);
if (payload.unavailable) {
const shard = ws.shards.get(shardId);
if (shard) shard.unavailableGuildIds.add(payload.id);
await cacheHandlers.set("unavailableGuilds", payload.id, Date.now());
if (shard) shard.unavailableGuildIds.add(guild.id);
await cacheHandlers.set("unavailableGuilds", guild.id, Date.now());
eventHandlers.guildUnavailable?.(guild);
} else {
@@ -27,33 +24,24 @@ export async function handleGuildDelete(
}
cacheHandlers.forEach("messages", (message) => {
eventHandlers.debug?.(
"loop",
`1. Running forEach messages loop in CHANNEL_DELTE file.`,
);
if (message.guildId === payload.id) {
eventHandlers.debug?.("loop", `1. Running forEach messages loop in CHANNEL_DELTE file.`);
if (message.guildId === guild.id) {
cacheHandlers.delete("messages", message.id);
}
});
cacheHandlers.forEach("channels", (channel) => {
eventHandlers.debug?.(
"loop",
`2. Running forEach channels loop in CHANNEL_DELTE file.`,
);
if (channel.guildId === payload.id) {
eventHandlers.debug?.("loop", `2. Running forEach channels loop in CHANNEL_DELTE file.`);
if (channel.guildId === guild.id) {
cacheHandlers.delete("channels", channel.id);
}
});
cacheHandlers.forEach("members", (member) => {
eventHandlers.debug?.(
"loop",
`3. Running forEach members loop in CHANNEL_DELTE file.`,
);
if (!member.guilds.has(payload.id)) return;
eventHandlers.debug?.("loop", `3. Running forEach members loop in CHANNEL_DELTE file.`);
if (!member.guilds.has(guild.id)) return;
member.guilds.delete(payload.id);
member.guilds.delete(guild.id);
if (!member.guilds.size) {
return cacheHandlers.delete("members", member.id);

View File

@@ -1,14 +1,13 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildIntegrationsUpdate } from "../../types/integration/guild_integrations_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildIntegrationsUpdate } from "../../types/integrations/guild_integrations_update.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildIntegrationsUpdate(
data: DiscordGatewayPayload,
) {
export async function handleGuildIntegrationsUpdate(data: DiscordGatewayPayload) {
const payload = data.d as GuildIntegrationsUpdate;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
eventHandlers.guildIntegrationsUpdate?.(guild);

View File

@@ -1,46 +1,44 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { GuildUpdateChange } from "../../types/discordeno/guild_update_change.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { Guild } from "../../types/guilds/guild.ts";
import { structures } from "../../structures/mod.ts";
import type { GuildUpdateChange } from "../../types/discordeno/guild_update_change.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Guild } from "../../types/guilds/guild.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildUpdate(data: DiscordGatewayPayload) {
export async function handleGuildUpdate(data: DiscordGatewayPayload, shardId: number) {
const payload = data.d as Guild;
const newGuild = await cacheHandlers.get("guilds", payload.id);
if (!newGuild) return;
const oldGuild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.id));
if (!oldGuild) return;
const keysToSkip = [
"roles",
"guildHashes",
"guildId",
"maxMembers",
"emojis",
];
const keysToSkip = ["id", "roles", "guildHashes", "guildId", "maxMembers", "emojis"];
const changes = Object.entries(payload)
const newGuild = await structures.createDiscordenoGuild(payload, shardId);
const changes = Object.entries(newGuild)
.map(([key, value]) => {
if (keysToSkip.includes(key)) return;
// @ts-ignore index signature
const cachedValue = newGuild[key];
if (cachedValue !== value) {
// Guild create sends undefined and update sends false.
if (!cachedValue && !value) return;
const cachedValue = oldGuild[key];
if (Array.isArray(cachedValue) && Array.isArray(value)) {
const different = (cachedValue.length !== value.length) ||
cachedValue.find((val) => !value.includes(val)) ||
value.find((val) => !cachedValue.includes(val));
if (!different) return;
}
if (cachedValue === value) return;
// Guild create sends undefined and update sends false.
if (!cachedValue && !value) return;
// @ts-ignore index signature
newGuild[key] = value;
return { key, oldValue: cachedValue, value };
if (Array.isArray(cachedValue) && Array.isArray(value)) {
const different =
cachedValue.length !== value.length ||
cachedValue.find((val) => !value.includes(val)) ||
value.find((val) => !cachedValue.includes(val));
if (!different) return;
}
}).filter((change) => change) as GuildUpdateChange[];
await cacheHandlers.set("guilds", payload.id, newGuild);
return { key, oldValue: cachedValue, value };
})
.filter((change) => change) as GuildUpdateChange[];
await cacheHandlers.set("guilds", newGuild.id, newGuild);
eventHandlers.guildUpdate?.(newGuild, changes);
}

View File

@@ -1,13 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import {
IntegrationCreateUpdate,
} from "../../types/integration/integration_create_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { IntegrationCreateUpdate } from "../../types/integrations/integration_create_update.ts";
export function handleIntegrationCreate(
data: DiscordGatewayPayload,
) {
eventHandlers.integrationCreate?.(
data.d as IntegrationCreateUpdate,
);
export function handleIntegrationCreate(data: DiscordGatewayPayload) {
eventHandlers.integrationCreate?.(data.d as IntegrationCreateUpdate);
}

View File

@@ -1,9 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { IntegrationDelete } from "../../types/integration/integration_delete.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { IntegrationDelete } from "../../types/integrations/integration_delete.ts";
export function handleIntegrationDelete(data: DiscordGatewayPayload) {
eventHandlers.integrationDelete?.(
data.d as IntegrationDelete,
);
eventHandlers.integrationDelete?.(data.d as IntegrationDelete);
}

View File

@@ -1,11 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import {
IntegrationCreateUpdate,
} from "../../types/integration/integration_create_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { IntegrationCreateUpdate } from "../../types/integrations/integration_create_update.ts";
export function handleIntegrationUpdate(data: DiscordGatewayPayload) {
eventHandlers.integrationUpdate?.(
data.d as IntegrationCreateUpdate,
);
eventHandlers.integrationUpdate?.(data.d as IntegrationCreateUpdate);
}

View File

@@ -1,17 +1,15 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildMemberWithUser } from "../../types/guilds/guild_member.ts";
import { Interaction } from "../../types/interactions/interaction.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Interaction } from "../../types/interactions/interaction.ts";
import type { GuildMemberWithUser } from "../../types/members/guild_member.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleInteractionCreate(data: DiscordGatewayPayload) {
const payload = data.d as Interaction;
const discordenoMember = payload.guildId
? await structures.createDiscordenoMember(
payload.member as GuildMemberWithUser,
payload.guildId,
)
? await structures.createDiscordenoMember(payload.member as GuildMemberWithUser, snowflakeToBigint(payload.guildId))
: undefined;
if (discordenoMember) {
await cacheHandlers.set("members", discordenoMember.id, discordenoMember);

View File

@@ -1,9 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { InviteCreate } from "../../types/invites/invite_create.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { InviteCreate } from "../../types/invites/invite_create.ts";
export function handleInviteCreate(data: DiscordGatewayPayload) {
eventHandlers.inviteCreate?.(
data.d as InviteCreate,
);
eventHandlers.inviteCreate?.(data.d as InviteCreate);
}

View File

@@ -1,9 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { InviteDelete } from "../../types/invites/invite_delete.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { InviteDelete } from "../../types/invites/invite_delete.ts";
export function handleInviteDelete(data: DiscordGatewayPayload) {
eventHandlers.inviteDelete?.(
data.d as InviteDelete,
);
eventHandlers.inviteDelete?.(data.d as InviteDelete);
}

View File

@@ -1,28 +1,26 @@
import { cache, cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildMembersChunk } from "../../types/members/guild_members_chunk.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildMembersChunk } from "../../types/members/guild_members_chunk.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { Collection } from "../../util/collection.ts";
export async function handleGuildMembersChunk(data: DiscordGatewayPayload) {
const payload = data.d as GuildMembersChunk;
const guildId = snowflakeToBigint(payload.guildId);
const members = await Promise.all(
payload.members.map(async (member) => {
const discordenoMember = await structures.createDiscordenoMember(
member,
payload.guildId,
);
const discordenoMember = await structures.createDiscordenoMember(member, guildId);
await cacheHandlers.set("members", discordenoMember.id, discordenoMember);
return discordenoMember;
}),
})
);
// Check if its necessary to resolve the fetchmembers promise for this chunk or if more chunks will be coming
if (
payload.nonce
) {
if (payload.nonce) {
const resolve = cache.fetchAllMembersProcessingRequests.get(payload.nonce);
if (!resolve) return;
@@ -33,12 +31,7 @@ export async function handleGuildMembersChunk(data: DiscordGatewayPayload) {
return resolve(new Collection(members.map((m) => [m.id, m])));
}
return resolve(
await cacheHandlers.filter(
"members",
(m) => m.guilds.has(payload.guildId),
),
);
return resolve(await cacheHandlers.filter("members", (m) => m.guilds.has(guildId)));
}
}
}

View File

@@ -1,19 +1,17 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildMemberAdd } from "../../types/members/guild_member_add.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildMemberAdd } from "../../types/members/guild_member_add.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildMemberAdd(data: DiscordGatewayPayload) {
const payload = data.d as GuildMemberAdd;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
guild.memberCount++;
const discordenoMember = await structures.createDiscordenoMember(
payload,
payload.guildId,
);
const discordenoMember = await structures.createDiscordenoMember(payload, guild.id);
await cacheHandlers.set("members", discordenoMember.id, discordenoMember);
eventHandlers.guildMemberAdd?.(guild, discordenoMember);

View File

@@ -1,15 +1,16 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildMemberRemove } from "../../types/members/guild_member_remove.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildMemberRemove } from "../../types/members/guild_member_remove.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildMemberRemove(data: DiscordGatewayPayload) {
const payload = data.d as GuildMemberRemove;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
guild.memberCount--;
const member = await cacheHandlers.get("members", payload.user.id);
const member = await cacheHandlers.get("members", snowflakeToBigint(payload.user.id));
eventHandlers.guildMemberRemove?.(guild, payload.user, member);
member?.guilds.delete(guild.id);

View File

@@ -1,40 +1,32 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildMemberUpdate } from "../../types/members/guild_member_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildMemberUpdate } from "../../types/members/guild_member_update.ts";
import { bigintToSnowflake, snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildMemberUpdate(data: DiscordGatewayPayload) {
const payload = data.d as GuildMemberUpdate;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
const cachedMember = await cacheHandlers.get("members", payload.user.id);
const guildMember = cachedMember?.guilds.get(payload.guildId);
const cachedMember = await cacheHandlers.get("members", snowflakeToBigint(payload.user.id));
const guildMember = cachedMember?.guilds.get(guild.id);
const newMemberData = {
...payload,
premiumSince: payload.premiumSince || undefined,
joinedAt: new Date(guildMember?.joinedAt || Date.now())
.toISOString(),
joinedAt: new Date(guildMember?.joinedAt || Date.now()).toISOString(),
deaf: guildMember?.deaf || false,
mute: guildMember?.mute || false,
roles: payload.roles,
};
const discordenoMember = await structures.createDiscordenoMember(
newMemberData,
payload.guildId,
);
const discordenoMember = await structures.createDiscordenoMember(newMemberData, guild.id);
await cacheHandlers.set("members", discordenoMember.id, discordenoMember);
if (guildMember) {
if (guildMember.nick !== payload.nick) {
eventHandlers.nicknameUpdate?.(
guild,
discordenoMember,
payload.nick!,
guildMember.nick ?? undefined,
);
eventHandlers.nicknameUpdate?.(guild, discordenoMember, payload.nick!, guildMember.nick ?? undefined);
}
if (payload.pending === false && guildMember.pending === true) {
@@ -44,22 +36,16 @@ export async function handleGuildMemberUpdate(data: DiscordGatewayPayload) {
const roleIds = guildMember.roles || [];
roleIds.forEach((id) => {
eventHandlers.debug?.(
"loop",
`1. Running forEach loop in GUILD_MEMBER_UPDATE file.`,
);
if (!payload.roles.includes(id)) {
eventHandlers.debug?.("loop", `1. Running forEach loop in GUILD_MEMBER_UPDATE file.`);
if (!payload.roles.includes(bigintToSnowflake(id))) {
eventHandlers.roleLost?.(guild, discordenoMember, id);
}
});
payload.roles.forEach((id) => {
eventHandlers.debug?.(
"loop",
`2. Running forEach loop in GUILD_MEMBER_UPDATE file.`,
);
if (!roleIds.includes(id)) {
eventHandlers.roleGained?.(guild, discordenoMember, id);
eventHandlers.debug?.("loop", `2. Running forEach loop in GUILD_MEMBER_UPDATE file.`);
if (!roleIds.includes(snowflakeToBigint(id))) {
eventHandlers.roleGained?.(guild, discordenoMember, snowflakeToBigint(id));
}
});
}

View File

@@ -1,51 +1,46 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildMemberWithUser } from "../../types/guilds/guild_member.ts";
import { Message } from "../../types/messages/message.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildMemberWithUser } from "../../types/members/guild_member.ts";
import type { Message } from "../../types/messages/message.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleMessageCreate(data: DiscordGatewayPayload) {
const payload = data.d as Message;
const channel = await cacheHandlers.get("channels", payload.channelId);
if (channel) channel.lastMessageId = payload.id;
const channel = await cacheHandlers.get("channels", snowflakeToBigint(payload.channelId));
if (channel) channel.lastMessageId = snowflakeToBigint(payload.id);
const guild = payload.guildId
? await cacheHandlers.get("guilds", payload.guildId)
: undefined;
const guild = payload.guildId ? await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId)) : undefined;
if (payload.member && guild) {
// If in a guild cache the author as a member
const discordenoMember = await structures.createDiscordenoMember(
{ ...payload.member, user: payload.author } as GuildMemberWithUser,
guild.id,
guild.id
);
await cacheHandlers.set("members", discordenoMember.id, discordenoMember);
}
if (payload.mentions) {
await Promise.all(payload.mentions.map(async (mention) => {
// Cache the member if its a valid member
if (mention.member && guild) {
const discordenoMember = await structures.createDiscordenoMember(
{ ...mention.member, user: mention } as GuildMemberWithUser,
guild.id,
);
if (payload.mentions && guild) {
await Promise.all(
payload.mentions.map(async (mention) => {
// Cache the member if its a valid member
if (mention.member) {
const discordenoMember = await structures.createDiscordenoMember(
{ ...mention.member, user: mention } as GuildMemberWithUser,
guild.id
);
return cacheHandlers.set(
"members",
mention.id,
discordenoMember,
);
}
}));
return cacheHandlers.set("members", snowflakeToBigint(mention.id), discordenoMember);
}
})
);
}
const message = await structures.createDiscordenoMessage(
data.d as Message,
);
const message = await structures.createDiscordenoMessage(data.d as Message);
// Cache the message
await cacheHandlers.set("messages", payload.id, message);
await cacheHandlers.set("messages", snowflakeToBigint(payload.id), message);
eventHandlers.messageCreate?.(message);
}

View File

@@ -1,17 +1,18 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { MessageDelete } from "../../types/messages/message_delete.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { MessageDelete } from "../../types/messages/message_delete.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleMessageDelete(data: DiscordGatewayPayload) {
const payload = data.d as MessageDelete;
const channel = await cacheHandlers.get("channels", payload.channelId);
const channel = await cacheHandlers.get("channels", snowflakeToBigint(payload.channelId));
if (!channel) return;
eventHandlers.messageDelete?.(
{ id: payload.id, channel },
await cacheHandlers.get("messages", payload.id),
await cacheHandlers.get("messages", snowflakeToBigint(payload.id))
);
await cacheHandlers.delete("messages", payload.id);
await cacheHandlers.delete("messages", snowflakeToBigint(payload.id));
}

View File

@@ -1,18 +1,18 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { MessageDeleteBulk } from "../../types/messages/message_delete_bulk.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { MessageDeleteBulk } from "../../types/messages/message_delete_bulk.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleMessageDeleteBulk(data: DiscordGatewayPayload) {
const payload = data.d as MessageDeleteBulk;
const channel = await cacheHandlers.get("channels", payload.channelId);
const channel = await cacheHandlers.get("channels", snowflakeToBigint(payload.channelId));
if (!channel) return;
return Promise.all(payload.ids.map(async (id) => {
eventHandlers.messageDelete?.(
{ id, channel },
await cacheHandlers.get("messages", id),
);
await cacheHandlers.delete("messages", id);
}));
return Promise.all(
payload.ids.map(async (id) => {
eventHandlers.messageDelete?.({ id, channel }, await cacheHandlers.get("messages", snowflakeToBigint(id)));
await cacheHandlers.delete("messages", snowflakeToBigint(id));
})
);
}

View File

@@ -1,51 +1,39 @@
import { botId, eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import {
MessageReactionAdd,
} from "../../types/messages/message_reaction_add.ts";
import { snakeKeysToCamelCase } from "../../util/utils.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { MessageReactionAdd } from "../../types/messages/message_reaction_add.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleMessageReactionAdd(data: DiscordGatewayPayload) {
const payload = data.d as MessageReactionAdd;
const message = await cacheHandlers.get("messages", payload.messageId);
const message = await cacheHandlers.get("messages", snowflakeToBigint(payload.messageId));
if (message) {
const reactionExisted = message.reactions?.find(
(reaction) =>
reaction.emoji.id === payload.emoji.id &&
reaction.emoji.name === payload.emoji.name,
(reaction) => reaction.emoji.id === payload.emoji.id && reaction.emoji.name === payload.emoji.name
);
if (reactionExisted) reactionExisted.count++;
else {
const newReaction = {
count: 1,
me: payload.userId === botId,
me: snowflakeToBigint(payload.userId) === botId,
emoji: { ...payload.emoji, id: payload.emoji.id || undefined },
};
message.reactions = message.reactions
? [...message.reactions, newReaction]
: [newReaction];
message.reactions = message.reactions ? [...message.reactions, newReaction] : [newReaction];
}
await cacheHandlers.set("messages", payload.messageId, message);
await cacheHandlers.set("messages", snowflakeToBigint(payload.messageId), message);
}
if (payload.member && payload.guildId) {
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (guild) {
const discordenoMember = await structures.createDiscordenoMember(
payload.member,
guild.id,
);
const discordenoMember = await structures.createDiscordenoMember(payload.member, guild.id);
await cacheHandlers.set("members", discordenoMember.id, discordenoMember);
}
}
eventHandlers.reactionAdd?.(
snakeKeysToCamelCase<MessageReactionAdd>(payload),
message,
);
eventHandlers.reactionAdd?.(payload, message);
}

View File

@@ -1,21 +1,18 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import {
MessageReactionRemove,
} from "../../types/messages/message_reaction_remove.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { MessageReactionRemove } from "../../types/messages/message_reaction_remove.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleMessageReactionRemove(
data: DiscordGatewayPayload,
) {
export async function handleMessageReactionRemove(data: DiscordGatewayPayload) {
const payload = data.d as MessageReactionRemove;
const message = await cacheHandlers.get("messages", payload.messageId);
const message = await cacheHandlers.get("messages", snowflakeToBigint(payload.messageId));
if (message) {
const reaction = message.reactions?.find((reaction) =>
// MUST USE == because discord sends null and we use undefined
reaction.emoji.id == payload.emoji.id &&
reaction.emoji.name === payload.emoji.name
const reaction = message.reactions?.find(
(reaction) =>
// MUST USE == because discord sends null and we use undefined
reaction.emoji.id == payload.emoji.id && reaction.emoji.name === payload.emoji.name
);
if (reaction) {
@@ -25,12 +22,9 @@ export async function handleMessageReactionRemove(
}
if (!message.reactions?.length) message.reactions = undefined;
await cacheHandlers.set("messages", payload.messageId, message);
await cacheHandlers.set("messages", message.id, message);
}
}
eventHandlers.reactionRemove?.(
payload,
message,
);
eventHandlers.reactionRemove?.(payload, message);
}

View File

@@ -1,24 +1,18 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import {
MessageReactionRemoveAll,
} from "../../types/messages/message_reaction_remove_all.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { MessageReactionRemoveAll } from "../../types/messages/message_reaction_remove_all.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleMessageReactionRemoveAll(
data: DiscordGatewayPayload,
) {
export async function handleMessageReactionRemoveAll(data: DiscordGatewayPayload) {
const payload = data.d as MessageReactionRemoveAll;
const message = await cacheHandlers.get("messages", payload.messageId);
const message = await cacheHandlers.get("messages", snowflakeToBigint(payload.messageId));
if (message?.reactions) {
message.reactions = undefined;
await cacheHandlers.set("messages", payload.messageId, message);
await cacheHandlers.set("messages", snowflakeToBigint(payload.messageId), message);
}
eventHandlers.reactionRemoveAll?.(
payload,
message,
);
eventHandlers.reactionRemoveAll?.(payload, message);
}

View File

@@ -1,33 +1,31 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { MessageReactionRemoveEmoji } from "../../types/messages/message_reaction_remove_emoji.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { MessageReactionRemoveEmoji } from "../../types/messages/message_reaction_remove_emoji.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleMessageReactionRemoveEmoji(
data: DiscordGatewayPayload,
) {
export async function handleMessageReactionRemoveEmoji(data: DiscordGatewayPayload) {
const payload = data.d as MessageReactionRemoveEmoji;
const message = await cacheHandlers.get("messages", payload.messageId);
const message = await cacheHandlers.get("messages", snowflakeToBigint(payload.messageId));
if (message?.reactions) {
message.reactions = message.reactions.filter(
(reaction) =>
!(
// MUST USE == because discord sends null and we use undefined
reaction.emoji.id == payload.emoji.id &&
reaction.emoji.name === payload.emoji.name
),
(reaction.emoji.id == payload.emoji.id && reaction.emoji.name === payload.emoji.name)
)
);
if (!message.reactions.length) message.reactions = undefined;
await cacheHandlers.set("messages", payload.messageId, message);
await cacheHandlers.set("messages", message.id, message);
}
eventHandlers.reactionRemoveEmoji?.(
payload.emoji,
payload.messageId,
payload.channelId,
payload.guildId,
snowflakeToBigint(payload.messageId),
snowflakeToBigint(payload.channelId),
payload.guildId ? snowflakeToBigint(payload.guildId) : undefined
);
}

View File

@@ -1,28 +1,26 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { Message } from "../../types/messages/message.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Message } from "../../types/messages/message.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleMessageUpdate(data: DiscordGatewayPayload) {
const payload = data.d as Message;
const channel = await cacheHandlers.get("channels", payload.channelId);
const channel = await cacheHandlers.get("channels", snowflakeToBigint(payload.channelId));
if (!channel) return;
const oldMessage = await cacheHandlers.get("messages", payload.id);
const oldMessage = await cacheHandlers.get("messages", snowflakeToBigint(payload.id));
if (!oldMessage) return;
// Messages with embeds can trigger update but they wont have edited_timestamp
if (
!payload.editedTimestamp ||
(oldMessage.content === payload.content)
) {
if (!payload.editedTimestamp || oldMessage.content === payload.content) {
return;
}
const message = await structures.createDiscordenoMessage(payload);
await cacheHandlers.set("messages", payload.id, message);
await cacheHandlers.set("messages", snowflakeToBigint(payload.id), message);
eventHandlers.messageUpdate?.(message, oldMessage);
}

View File

@@ -1,13 +1,14 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { PresenceUpdate } from "../../types/misc/presence_update.ts";
import type { PresenceUpdate } from "../../types/activity/presence_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handlePresenceUpdate(data: DiscordGatewayPayload) {
const payload = data.d as PresenceUpdate;
const oldPresence = await cacheHandlers.get("presences", payload.user.id);
await cacheHandlers.set("presences", payload.user.id, payload);
const oldPresence = await cacheHandlers.get("presences", snowflakeToBigint(payload.user.id));
await cacheHandlers.set("presences", snowflakeToBigint(payload.user.id), payload);
eventHandlers.presenceUpdate?.(payload, oldPresence);
}

View File

@@ -1,116 +1,73 @@
import { eventHandlers, setApplicationId, setBotId } from "../../bot.ts";
import { cache, cacheHandlers } from "../../cache.ts";
import { initialMemberLoadQueue } from "../../structures/guild.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { Ready } from "../../types/gateway/ready.ts";
import { GuildMemberWithUser } from "../../types/mod.ts";
import { ws } from "../../ws/ws.ts";
import { cache } from "../../cache.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { Ready } from "../../types/gateway/ready.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { DiscordenoShard, ws } from "../../ws/ws.ts";
export function handleReady(data: DiscordGatewayPayload, shardId: number) {
// Triggered on each shard
eventHandlers.shardReady?.(shardId);
export function handleReady(
data: DiscordGatewayPayload,
shardId: number,
) {
// The bot has already started, the last shard is resumed, however.
if (cache.isReady) return;
const shard = ws.shards.get(shardId);
if (!shard) return;
const payload = data.d as Ready;
setBotId(payload.user.id);
setApplicationId(payload.application.id);
// Triggered on each shard
eventHandlers.shardReady?.(shardId);
// Save when the READY event was received to prevent infinite load loops
const now = Date.now();
const shard = ws.shards.get(shardId);
if (!shard) return;
// Set ready to false just to go sure
shard.ready = false;
// All guilds are unavailable at first
shard.unavailableGuildIds = new Set(payload.guilds.map((g) => g.id));
shard.unavailableGuildIds = new Set(payload.guilds.map((g) => snowflakeToBigint(g.id)));
// Set the last available to now
shard.lastAvailable = Date.now();
// Start ready check in 2 seconds
setTimeout(async () => {
eventHandlers.debug?.(
"loop",
`1. Running setTimeout in READY file.`,
);
await checkReady(payload, shardId, now);
setTimeout(() => {
eventHandlers.debug?.("loop", `1. Running setTimeout in READY file.`);
checkReady(payload, shard);
}, 2000);
}
// Don't pass the shard itself because unavailableGuilds won't be updated by the GUILD_CREATE event
/** This function checks if the shard is fully loaded */
async function checkReady(payload: Ready, shardId: number, now: number) {
const shard = ws.shards.get(shardId);
if (!shard) return;
function checkReady(payload: Ready, shard: DiscordenoShard) {
// Check if all guilds were loaded
if (shard.unavailableGuildIds.size) {
if (Date.now() - now > 10000) {
eventHandlers.shardFailedToLoad?.(shardId, shard.unavailableGuildIds);
// Force execute the loaded function to prevent infinite loop
await loaded(shardId);
} else {
// Not all guilds were loaded but 10 seconds haven't passed so check again
setTimeout(async () => {
eventHandlers.debug?.(
"loop",
`2. Running setTimeout in READY file.`,
);
await checkReady(payload, shardId, now);
}, 2000);
}
} else {
// All guilds were loaded
await loaded(shardId);
if (!shard.unavailableGuildIds.size) return loaded(shard);
// If the last GUILD_CREATE has been received before 5 seconds if so most likely the remaining guilds are unavailable
if (shard.lastAvailable + 5000 < Date.now()) {
eventHandlers.shardFailedToLoad?.(shard.id, shard.unavailableGuildIds);
// Force execute the loaded function to prevent infinite loop
return loaded(shard);
}
// Not all guilds were loaded but 5 seconds haven't passed so check again
setTimeout(() => {
eventHandlers.debug?.("loop", `2. Running setTimeout in READY file.`);
checkReady(payload, shard);
}, 2000);
}
async function loaded(shardId: number) {
const shard = ws.shards.get(shardId);
if (!shard) return;
function loaded(shard: DiscordenoShard) {
shard.ready = true;
// If it is the last shard we can go full ready
if (shardId === ws.lastShardId - 1) {
// Still some shards are loading so wait another 2 seconds for them
if (ws.shards.some((shard) => !shard.ready)) {
setTimeout(async () => {
eventHandlers.debug?.(
"loop",
`3. Running setTimeout in CHANNEL_DELTE file.`,
);
await loaded(shardId);
}, 2000);
} else {
cache.isReady = true;
eventHandlers.ready?.();
// If it is not the last shard we can't go full ready
if (shard.id !== ws.lastShardId) return;
// All the members that came in on guild creates should now be processed 1 by 1
for (const [guildId, members] of initialMemberLoadQueue.entries()) {
eventHandlers.debug?.(
"loop",
"Running for of loop in READY file for loading members.",
);
await Promise.allSettled(
members.map(async (member) => {
const discordenoMember = await structures.createDiscordenoMember(
member as GuildMemberWithUser,
guildId,
);
// Still some shards are loading so wait another 2 seconds for them
if (ws.shards.some((shard) => !shard.ready)) {
setTimeout(() => {
eventHandlers.debug?.("loop", `3. Running setTimeout in READY file.`);
loaded(shard);
}, 2000);
return cacheHandlers.set(
"members",
discordenoMember.id,
discordenoMember,
);
}),
);
}
}
return;
}
cache.isReady = true;
eventHandlers.ready?.();
}

View File

@@ -1,9 +1,7 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { TypingStart } from "../../types/misc/typing_start.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { TypingStart } from "../../types/misc/typing_start.ts";
export function handleTypingStart(data: DiscordGatewayPayload) {
eventHandlers.typingStart?.(
data.d as TypingStart,
);
eventHandlers.typingStart?.(data.d as TypingStart);
}

View File

@@ -1,24 +1,35 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { User } from "../../types/users/user.ts";
import { memberToggles } from "../../structures/member.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { User } from "../../types/users/user.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { iconHashToBigInt } from "../../util/hash.ts";
export async function handleUserUpdate(data: DiscordGatewayPayload) {
const userData = data.d as User;
const member = await cacheHandlers.get("members", userData.id);
const member = await cacheHandlers.get("members", snowflakeToBigint(userData.id));
if (!member) return;
Object.entries(userData).forEach(([key, value]) => {
eventHandlers.debug?.(
"loop",
`Running forEach loop in USER_UPDATE file.`,
);
// @ts-ignore index signatures
if (member[key] !== value) return member[key] = value;
});
// Update username
member.username = userData.username;
// Update discriminator
member.discriminator = Number(userData.discriminator);
await cacheHandlers.set("members", userData.id, member);
// Check if a avatar is available
const hash = userData.avatar ? iconHashToBigInt(userData.avatar) : undefined;
// Update the avatar
member.avatar = hash?.bigint || 0n;
// Update the animated status if its animated
if (hash?.animated) member.bitfield |= memberToggles.animatedAvatar;
else member.bitfield &= ~memberToggles.animatedAvatar;
member.flags = userData.flags;
member.premiumType = userData.premiumType;
member.publicFlags = userData.publicFlags;
await cacheHandlers.set("members", snowflakeToBigint(userData.id), member);
eventHandlers.botUpdate?.(userData);
}

View File

@@ -2,6 +2,15 @@ import { handleChannelCreate } from "./channels/CHANNEL_CREATE.ts";
import { handleChannelDelete } from "./channels/CHANNEL_DELETE.ts";
import { handleChannelPinsUpdate } from "./channels/CHANNEL_PINS_UPDATE.ts";
import { handleChannelUpdate } from "./channels/CHANNEL_UPDATE.ts";
import { handleStageInstanceCreate } from "./channels/STAGE_INSTANCE_CREATE.ts";
import { handleStageInstanceUpdate } from "./channels/STAGE_INSTANCE_UPDATE.ts";
import { handleStageInstanceDelete } from "./channels/STAGE_INSTANCE_DELETE.ts";
import { handleThreadCreate } from "./channels/THREAD_CREATE.ts";
import { handleThreadDelete } from "./channels/THREAD_DELETE.ts";
import { handleThreadListSync } from "./channels/THREAD_LIST_SYNC.ts";
import { handleThreadMembersUpdate } from "./channels/THREAD_MEMBERS_UPDATE.ts";
import { handleThreadMemberUpdate } from "./channels/THREAD_MEMBER_UPDATE.ts";
import { handleThreadUpdate } from "./channels/THREAD_UPDATE.ts";
import { handleApplicationCommandCreate } from "./commands/APPLICATION_COMMAND_CREATE.ts";
import { handleApplicationCommandDelete } from "./commands/APPLICATION_COMMAND_DELETE.ts";
import { handleApplicationCommandUpdate } from "./commands/APPLICATION_COMMAND_UPDATE.ts";
@@ -77,6 +86,15 @@ export {
handleMessageUpdate,
handlePresenceUpdate,
handleReady,
handleStageInstanceCreate,
handleStageInstanceDelete,
handleStageInstanceUpdate,
handleThreadCreate,
handleThreadDelete,
handleThreadListSync,
handleThreadMembersUpdate,
handleThreadMemberUpdate,
handleThreadUpdate,
handleTypingStart,
handleUserUpdate,
handleVoiceServerUpdate,
@@ -92,6 +110,16 @@ export let handlers = {
CHANNEL_DELETE: handleChannelDelete,
CHANNEL_PINS_UPDATE: handleChannelPinsUpdate,
CHANNEL_UPDATE: handleChannelUpdate,
THREAD_CREATE: handleThreadCreate,
THREAD_UPDATE: handleThreadUpdate,
THREAD_DELETE: handleThreadDelete,
THREAD_LIST_SYNC: handleThreadListSync,
THREAD_MEMBER_UPDATE: handleThreadMemberUpdate,
THREAD_MEMBERS_UPDATE: handleThreadMembersUpdate,
STAGE_INSTANCE_CREATE: handleStageInstanceCreate,
STAGE_INSTANCE_UPDATE: handleStageInstanceUpdate,
STAGE_INSTANCE_DELETE: handleStageInstanceDelete,
// commands
APPLICATION_COMMAND_CREATE: handleApplicationCommandCreate,
APPLICATION_COMMAND_DELETE: handleApplicationCommandDelete,

View File

@@ -1,17 +1,21 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildRoleCreate } from "../../types/mod.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildRoleCreate } from "../../types/guilds/guild_role_create.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildRoleCreate(data: DiscordGatewayPayload) {
const payload = data.d as GuildRoleCreate;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
const role = await structures.createDiscordenoRole(payload);
guild.roles = guild.roles.set(payload.role.id, role);
await cacheHandlers.set("guilds", payload.guildId, guild);
const role = await structures.createDiscordenoRole({
...payload,
guildId: guild.id,
});
guild.roles = guild.roles.set(snowflakeToBigint(payload.role.id), role);
await cacheHandlers.set("guilds", guild.id, guild);
eventHandlers.roleCreate?.(guild, role);
}

View File

@@ -1,36 +1,33 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildRoleDelete } from "../../types/guilds/guild_role_delete.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildRoleDelete } from "../../types/guilds/guild_role_delete.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildRoleDelete(data: DiscordGatewayPayload) {
const payload = data.d as GuildRoleDelete;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
const cachedRole = guild.roles.get(payload.roleId)!;
guild.roles.delete(payload.roleId);
const roleId = snowflakeToBigint(payload.roleId);
const cachedRole = guild.roles.get(roleId)!;
guild.roles.delete(roleId);
if (cachedRole) eventHandlers.roleDelete?.(guild, cachedRole);
// For bots without GUILD_MEMBERS member.roles is never updated breaking permissions checking.
cacheHandlers.forEach("members", (member) => {
eventHandlers.debug?.(
"loop",
`1. Running forEach members loop in GUILD_ROLE_DELETE file.`,
);
eventHandlers.debug?.("loop", `1. Running forEach members loop in GUILD_ROLE_DELETE file.`);
// Not in the relevant guild so just skip.
if (!member.guilds.has(guild.id)) return;
member.guilds.forEach((g) => {
eventHandlers.debug?.(
"loop",
`2. Running forEach loop in CHANNEL_DELTE file.`,
);
eventHandlers.debug?.("loop", `2. Running forEach loop in CHANNEL_DELTE file.`);
// Member does not have this role
if (!g.roles.includes(payload.roleId)) return;
if (!g.roles.includes(roleId)) return;
// Remove this role from the members cache
g.roles = g.roles.filter((id) => id !== payload.roleId);
g.roles = g.roles.filter((id) => id !== roleId);
cacheHandlers.set("members", member.id, member);
});
});

View File

@@ -1,19 +1,23 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { GuildRoleUpdate } from "../../types/mod.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { GuildRoleUpdate } from "../../types/guilds/guild_role_update.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleGuildRoleUpdate(data: DiscordGatewayPayload) {
const payload = data.d as GuildRoleUpdate;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
const cachedRole = guild.roles.get(payload.role.id);
const cachedRole = guild.roles.get(snowflakeToBigint(payload.role.id));
if (!cachedRole) return;
const role = await structures.createDiscordenoRole(payload);
guild.roles.set(payload.role.id, role);
const role = await structures.createDiscordenoRole({
...payload,
guildId: guild.id,
});
guild.roles.set(snowflakeToBigint(payload.role.id), role);
await cacheHandlers.set("guilds", guild.id, guild);
eventHandlers.roleUpdate?.(guild, role, cachedRole);

View File

@@ -1,12 +1,13 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { VoiceServerUpdate } from "../../types/voice/voice_server_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { VoiceServerUpdate } from "../../types/voice/voice_server_update.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleVoiceServerUpdate(data: DiscordGatewayPayload) {
const payload = data.d as VoiceServerUpdate;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
eventHandlers.voiceServerUpdate?.(payload, guild);

View File

@@ -1,50 +1,45 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { structures } from "../../structures/mod.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { VoiceState } from "../../types/voice/voice_state.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { VoiceState } from "../../types/voice/voice_state.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export async function handleVoiceStateUpdate(data: DiscordGatewayPayload) {
const payload = data.d as VoiceState;
if (!payload.guildId) return;
const guild = await cacheHandlers.get("guilds", payload.guildId);
const guild = await cacheHandlers.get("guilds", snowflakeToBigint(payload.guildId));
if (!guild) return;
const member = payload.member
? await structures.createDiscordenoMember(
payload.member,
guild.id,
)
: await cacheHandlers.get("members", payload.userId);
? await structures.createDiscordenoMember(payload.member, guild.id)
: await cacheHandlers.get("members", snowflakeToBigint(payload.userId));
if (!member) return;
// No cached state before so lets make one for em
const cachedState = guild.voiceStates.get(payload.userId);
const cachedState = guild.voiceStates.get(snowflakeToBigint(payload.userId));
guild.voiceStates.set(
payload.userId,
payload,
snowflakeToBigint(payload.userId),
await structures.createDiscordenoVoiceState(guild.id, payload)
);
await cacheHandlers.set("guilds", payload.guildId, guild);
await cacheHandlers.set("guilds", guild.id, guild);
if (cachedState?.channelId !== payload.channelId) {
if (cachedState?.channelId !== (payload.channelId ? snowflakeToBigint(payload.channelId) : null)) {
// Either joined or moved channels
if (payload.channelId) {
if (cachedState?.channelId) { // Was in a channel before
eventHandlers.voiceChannelSwitch?.(
member,
payload.channelId,
cachedState.channelId,
);
} else { // Was not in a channel before so user just joined
eventHandlers.voiceChannelJoin?.(member, payload.channelId);
if (cachedState?.channelId) {
// Was in a channel before
eventHandlers.voiceChannelSwitch?.(member, snowflakeToBigint(payload.channelId), cachedState.channelId);
} else {
// Was not in a channel before so user just joined
eventHandlers.voiceChannelJoin?.(member, snowflakeToBigint(payload.channelId));
}
} // Left the channel
else if (cachedState?.channelId) {
guild.voiceStates.delete(payload.userId);
guild.voiceStates.delete(snowflakeToBigint(payload.userId));
eventHandlers.voiceChannelLeave?.(member, cachedState.channelId);
}
}

View File

@@ -1,11 +1,9 @@
import { eventHandlers } from "../../bot.ts";
import { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import { WebhookUpdate } from "../../types/webhooks/webhooks_update.ts";
import type { DiscordGatewayPayload } from "../../types/gateway/gateway_payload.ts";
import type { WebhookUpdate } from "../../types/webhooks/webhooks_update.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
export function handleWebhooksUpdate(data: DiscordGatewayPayload) {
const options = data.d as WebhookUpdate;
eventHandlers.webhooksUpdate?.(
options.channelId,
options.guildId,
);
eventHandlers.webhooksUpdate?.(snowflakeToBigint(options.channelId), snowflakeToBigint(options.guildId));
}

View File

@@ -1,9 +1,6 @@
import { cacheHandlers } from "../../cache.ts";
/** Gets an array of all the channels ids that are the children of this category. */
export function categoryChildren(id: string) {
return cacheHandlers.filter(
"channels",
(channel) => channel.parentId === id,
);
export async function categoryChildren(id: bigint) {
return await cacheHandlers.filter("channels", (channel) => channel.parentId === id);
}

View File

@@ -1,32 +1,30 @@
import { DiscordOverwrite } from "../../types/channels/overwrite.ts";
import type { DiscordOverwrite } from "../../types/channels/overwrite.ts";
import { DiscordBitwisePermissionFlags } from "../../types/permissions/bitwise_permission_flags.ts";
import { PermissionStrings } from "../../types/permissions/permission_strings.ts";
import type { PermissionStrings } from "../../types/permissions/permission_strings.ts";
/** Checks if a channel overwrite for a user id or a role id has permission in this channel */
export function channelOverwriteHasPermission(
guildId: string,
id: string,
overwrites: DiscordOverwrite[],
permissions: PermissionStrings[],
guildId: bigint,
id: bigint,
overwrites: (Omit<DiscordOverwrite, "id" | "allow" | "deny"> & {
id: bigint;
allow: bigint;
deny: bigint;
})[],
permissions: PermissionStrings[]
) {
const overwrite = overwrites.find((perm) => perm.id === id) ||
overwrites.find((perm) => perm.id === guildId);
const overwrite = overwrites.find((perm) => perm.id === id) || overwrites.find((perm) => perm.id === guildId);
if (!overwrite) return false;
return permissions.every((perm) => {
if (overwrite) {
const allowBits = overwrite.allow;
const denyBits = overwrite.deny;
if (
BigInt(denyBits) & BigInt(DiscordBitwisePermissionFlags[perm])
) {
return false;
}
if (
BigInt(allowBits) & BigInt(DiscordBitwisePermissionFlags[perm])
) {
return true;
}
const allowBits = overwrite.allow;
const denyBits = overwrite.deny;
if (BigInt(denyBits) & BigInt(DiscordBitwisePermissionFlags[perm])) {
return false;
}
if (BigInt(allowBits) & BigInt(DiscordBitwisePermissionFlags[perm])) {
return true;
}
return false;
});
}

View File

@@ -1,21 +1,17 @@
import { cacheHandlers } from "../../cache.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import { CreateGuildChannel } from "../../types/guilds/create_guild_channel.ts";
import { Errors } from "../../types/misc/errors.ts";
import type { CreateGuildChannel } from "../../types/guilds/create_guild_channel.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { calculatePermissions } from "../../util/permissions.ts";
import { createChannel } from "./create_channel.ts";
import { helpers } from "../mod.ts";
/** Create a copy of a channel */
export async function cloneChannel(channelId: string, reason?: string) {
export async function cloneChannel(channelId: bigint, reason?: string) {
const channelToClone = await cacheHandlers.get("channels", channelId);
//Return undefined if channel is not cached
if (!channelToClone) throw new Error(Errors.CHANNEL_NOT_FOUND);
//Check for DM channel
if (
channelToClone.type === DiscordChannelTypes.DM ||
channelToClone.type === DiscordChannelTypes.GROUP_DM
) {
if (channelToClone.type === DiscordChannelTypes.DM || channelToClone.type === DiscordChannelTypes.GroupDm) {
throw new Error(Errors.CHANNEL_NOT_IN_GUILD);
}
@@ -23,11 +19,8 @@ export async function cloneChannel(channelId: string, reason?: string) {
...channelToClone,
name: channelToClone.name!,
topic: channelToClone.topic || undefined,
parentId: channelToClone.parentId || undefined,
permissionOverwrites: channelToClone.permissionOverwrites.map((
overwrite,
) => ({
id: overwrite.id,
permissionOverwrites: channelToClone.permissionOverwrites.map((overwrite) => ({
id: overwrite.id.toString(),
type: overwrite.type,
allow: calculatePermissions(overwrite.allow),
deny: calculatePermissions(overwrite.deny),
@@ -35,5 +28,5 @@ export async function cloneChannel(channelId: string, reason?: string) {
};
//Create the channel (also handles permissions)
return createChannel(channelToClone.guildId!, createChannelOptions, reason);
return await helpers.createChannel(channelToClone.guildId!, createChannelOptions, reason);
}

View File

@@ -1,57 +1,32 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import { Channel } from "../../types/channels/channel.ts";
import type { Channel } from "../../types/channels/channel.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import {
CreateGuildChannel,
DiscordCreateGuildChannel,
} from "../../types/guilds/create_guild_channel.ts";
import { PermissionStrings } from "../../types/permissions/permission_strings.ts";
import type { CreateGuildChannel, DiscordCreateGuildChannel } from "../../types/guilds/create_guild_channel.ts";
import { endpoints } from "../../util/constants.ts";
import {
calculateBits,
requireBotGuildPermissions,
} from "../../util/permissions.ts";
import { camelKeysToSnakeCase } from "../../util/utils.ts";
import { calculateBits, requireOverwritePermissions } from "../../util/permissions.ts";
import { snakelize } from "../../util/utils.ts";
/** Create a channel in your server. Bot needs MANAGE_CHANNEL permissions in the server. */
export async function createChannel(
guildId: string,
options?: CreateGuildChannel,
reason?: string,
) {
const requiredPerms: Set<PermissionStrings> = new Set(["MANAGE_CHANNELS"]);
options?.permissionOverwrites?.forEach((overwrite) => {
eventHandlers.debug?.(
"loop",
`Running forEach loop in create_channel file.`,
);
overwrite.allow.forEach(requiredPerms.add, requiredPerms);
overwrite.deny.forEach(requiredPerms.add, requiredPerms);
});
await requireBotGuildPermissions(guildId, [...requiredPerms]);
export async function createChannel(guildId: bigint, options?: CreateGuildChannel, reason?: string) {
if (options?.permissionOverwrites) {
await requireOverwritePermissions(guildId, options.permissionOverwrites);
}
// BITRATES ARE IN THOUSANDS SO IF USER PROVIDES 32 WE CONVERT TO 32000
if (options?.bitrate && options.bitrate < 1000) options.bitrate *= 1000;
const result = await rest.runMethod<Channel>(
"post",
endpoints.GUILD_CHANNELS(guildId),
{
...camelKeysToSnakeCase<DiscordCreateGuildChannel>(options ?? {}),
permission_overwrites: options?.permissionOverwrites?.map((perm) => ({
...perm,
allow: calculateBits(perm.allow),
deny: calculateBits(perm.deny),
})),
type: options?.type || DiscordChannelTypes.GUILD_TEXT,
reason,
},
);
const result = await rest.runMethod<Channel>("post", endpoints.GUILD_CHANNELS(guildId), {
...snakelize<DiscordCreateGuildChannel>(options ?? {}),
permission_overwrites: options?.permissionOverwrites?.map((perm) => ({
...perm,
allow: calculateBits(perm.allow),
deny: calculateBits(perm.deny),
})),
type: options?.type || DiscordChannelTypes.GuildText,
reason,
});
const discordenoChannel = await structures.createDiscordenoChannel(result);
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);

View File

@@ -0,0 +1,37 @@
import { validateLength } from "../../util/validate_length.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import { cacheHandlers } from "../../cache.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
import { PrivacyLevel } from "../../types/channels/privacy_level.ts";
import { snakelize } from "../../util/utils.ts";
/** Creates a new Stage instance associated to a Stage channel. Requires the user to be a moderator of the Stage channel. */
export async function createStageInstance(channelId: bigint, topic: string, privacyLevel?: PrivacyLevel) {
const channel = await cacheHandlers.get("channels", channelId);
if (channel) {
if (channel.type !== ChannelTypes.GuildStageVoice) {
throw new Error(Errors.CHANNEL_NOT_STAGE_VOICE);
}
await requireBotChannelPermissions(channel, ["MANAGE_CHANNELS", "MUTE_MEMBERS", "MOVE_MEMBERS"]);
}
if (!validateLength(topic, { max: 120, min: 1 })) {
throw new Error(Errors.INVALID_TOPIC_LENGTH);
}
return await rest.runMethod<StageInstance>(
"post",
endpoints.STAGE_INSTANCES,
snakelize({
channelId,
topic,
privacyLevel,
})
);
}

View File

@@ -1,31 +1,35 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/misc/errors.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotGuildPermissions } from "../../util/permissions.ts";
/** Delete a channel in your server. Bot needs MANAGE_CHANNEL permissions in the server. */
export async function deleteChannel(
guildId: string,
channelId: string,
reason?: string,
): Promise<undefined> {
await requireBotGuildPermissions(guildId, ["MANAGE_CHANNELS"]);
export async function deleteChannel(channelId: bigint, reason?: string) {
const channel = await cacheHandlers.get("channels", channelId);
const guild = await cacheHandlers.get("guilds", guildId);
if (!guild) throw new Error(Errors.GUILD_NOT_FOUND);
if (channel?.guildId) {
const guild = await cacheHandlers.get("guilds", channel.guildId);
if (!guild) throw new Error(Errors.GUILD_NOT_FOUND);
if (guild?.rulesChannelId === channelId) {
throw new Error(Errors.RULES_CHANNEL_CANNOT_BE_DELETED);
// TODO(threads): check if this requires guild perms or channel is enough
await requireBotGuildPermissions(
guild,
[ChannelTypes.GuildNewsThread, ChannelTypes.GuildPivateThread, ChannelTypes.GuildPublicThread].includes(
channel.type
)
? ["MANAGE_THREADS"]
: ["MANAGE_CHANNELS"]
);
if (guild.rulesChannelId === channelId) {
throw new Error(Errors.RULES_CHANNEL_CANNOT_BE_DELETED);
}
if (guild.publicUpdatesChannelId === channelId) {
throw new Error(Errors.UPDATES_CHANNEL_CANNOT_BE_DELETED);
}
}
if (guild?.publicUpdatesChannelId === channelId) {
throw new Error(Errors.UPDATES_CHANNEL_CANNOT_BE_DELETED);
}
return await rest.runMethod<undefined>(
"delete",
endpoints.CHANNEL_BASE(channelId),
{ reason },
);
return await rest.runMethod<undefined>("delete", endpoints.CHANNEL_BASE(channelId), { reason });
}

View File

@@ -4,14 +4,11 @@ import { requireBotGuildPermissions } from "../../util/permissions.ts";
/** Delete the channel permission overwrites for a user or role in this channel. Requires `MANAGE_ROLES` permission. */
export async function deleteChannelOverwrite(
guildId: string,
channelId: string,
overwriteId: string,
guildId: bigint,
channelId: bigint,
overwriteId: bigint
): Promise<undefined> {
await requireBotGuildPermissions(guildId, ["MANAGE_ROLES"]);
return await rest.runMethod<undefined>(
"delete",
endpoints.CHANNEL_OVERWRITE(channelId, overwriteId),
);
return await rest.runMethod<undefined>("delete", endpoints.CHANNEL_OVERWRITE(channelId, overwriteId));
}

View File

@@ -0,0 +1,21 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
/** Deletes the Stage instance. Requires the user to be a moderator of the Stage channel. */
export async function deleteStageInstance(channelId: bigint) {
const channel = await cacheHandlers.get("channels", channelId);
if (channel) {
if (channel.type !== ChannelTypes.GuildStageVoice) {
throw new Error(Errors.CHANNEL_NOT_STAGE_VOICE);
}
await requireBotChannelPermissions(channel, ["MUTE_MEMBERS", "MANAGE_CHANNELS", "MOVE_MEMBERS"]);
}
return await rest.runMethod<undefined>("delete", endpoints.STAGE_INSTANCE(channelId));
}

View File

@@ -1,22 +1,52 @@
import { eventHandlers } from "../../bot.ts";
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { ModifyChannel } from "../../types/channels/modify_channel.ts";
import { Channel } from "../../types/mod.ts";
import type { DiscordenoChannel } from "../../structures/channel.ts";
import { structures } from "../../structures/mod.ts";
import type { Channel } from "../../types/channels/channel.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import type { ModifyChannel } from "../../types/channels/modify_channel.ts";
import type { ModifyThread } from "../../types/channels/threads/modify_thread.ts";
import type { PermissionStrings } from "../../types/permissions/permission_strings.ts";
import { endpoints } from "../../util/constants.ts";
import {
calculateBits,
requireBotChannelPermissions,
} from "../../util/permissions.ts";
import { calculateBits, requireBotChannelPermissions, requireOverwritePermissions } from "../../util/permissions.ts";
import { hasOwnProperty, snakelize } from "../../util/utils.ts";
//TODO: implement DM group channel edit
//TODO(threads): check thread perms
/** Update a channel's settings. Requires the `MANAGE_CHANNELS` permission for the guild. */
export async function editChannel(
channelId: string,
options: ModifyChannel,
reason?: string,
) {
await requireBotChannelPermissions(channelId, ["MANAGE_CHANNELS"]);
export async function editChannel(channelId: bigint, options: ModifyChannel | ModifyThread, reason?: string) {
const channel = await cacheHandlers.get("channels", channelId);
if (options.name || options.topic) {
if (channel) {
if (
[
DiscordChannelTypes.GuildNewsThread,
DiscordChannelTypes.GuildPivateThread,
DiscordChannelTypes.GuildPublicThread,
].includes(channel.type)
) {
const permissions = new Set<PermissionStrings>();
if (hasOwnProperty(options, "archive") && options.archive === false) {
permissions.add("SEND_MESSAGES");
}
// TODO(threads): change this to a better check
// hacky way of checking if more is being modified
if (Object.keys(options).length > 1) {
permissions.add("MANAGE_THREADS");
}
await requireBotChannelPermissions(channel.parentId ?? 0n, [...permissions]);
}
if (hasOwnProperty<ModifyChannel>(options, "permissionOverwrites") && Array.isArray(options.permissionOverwrites)) {
await requireOverwritePermissions(channel.guildId, options.permissionOverwrites);
}
}
if (options.name || (options as ModifyChannel).topic) {
const request = editChannelNameTopicQueue.get(channelId);
if (!request) {
// If this hasnt been done before simply add 1 for it
@@ -32,66 +62,61 @@ export async function editChannel(
request.amount = 2;
request.timestamp = Date.now() + 600000;
} else {
// 2 have already been used add to queue
request.items.push({ channelId, options });
if (editChannelProcessing) return;
editChannelProcessing = true;
processEditChannelQueue();
return;
return new Promise<DiscordenoChannel>((resolve, reject) => {
// 2 have already been used add to queue
request.items.push({ channelId, options, resolve, reject });
if (editChannelProcessing) return;
editChannelProcessing = true;
processEditChannelQueue();
});
}
}
const payload = {
...options,
...snakelize<Record<string, unknown>>(options),
// deno-lint-ignore camelcase
rate_limit_per_user: options.rateLimitPerUser,
// deno-lint-ignore camelcase
parent_id: options.parentId,
// deno-lint-ignore camelcase
user_limit: options.userLimit,
// deno-lint-ignore camelcase
permission_overwrites: options.permissionOverwrites?.map((overwrite) => {
return {
...overwrite,
allow: calculateBits(overwrite.allow),
deny: calculateBits(overwrite.deny),
};
}),
permission_overwrites: hasOwnProperty<ModifyChannel>(options, "permissionOverwrites")
? options.permissionOverwrites?.map((overwrite) => {
return {
...overwrite,
allow: calculateBits(overwrite.allow),
deny: calculateBits(overwrite.deny),
};
})
: undefined,
};
return await rest.runMethod<Channel>(
"patch",
endpoints.CHANNEL_BASE(channelId),
{
...payload,
reason,
},
);
const result = await rest.runMethod<Channel>("patch", endpoints.CHANNEL_BASE(channelId), {
...payload,
reason,
});
return await structures.createDiscordenoChannel(result);
}
interface EditChannelRequest {
amount: number;
timestamp: number;
channelId: string;
channelId: bigint;
items: {
channelId: string;
channelId: bigint;
options: ModifyChannel;
resolve: (channel: DiscordenoChannel) => void;
// deno-lint-ignore no-explicit-any
reject: (error: any) => void;
}[];
}
const editChannelNameTopicQueue = new Map<string, EditChannelRequest>();
const editChannelNameTopicQueue = new Map<bigint, EditChannelRequest>();
let editChannelProcessing = false;
function processEditChannelQueue() {
if (!editChannelProcessing) return;
const now = Date.now();
editChannelNameTopicQueue.forEach((request) => {
eventHandlers.debug?.(
"loop",
`Running forEach loop in edit_channel file.`,
);
if (now > request.timestamp) return;
editChannelNameTopicQueue.forEach(async (request) => {
eventHandlers.debug?.("loop", `Running forEach loop in edit_channel file.`);
if (now < request.timestamp) return;
// 10 minutes have passed so we can reset this channel again
if (!request.items.length) {
return editChannelNameTopicQueue.delete(request.channelId);
@@ -102,21 +127,23 @@ function processEditChannelQueue() {
if (!details) return;
editChannel(details.channelId, details.options);
await editChannel(details.channelId, details.options)
.then((result) => details.resolve(result))
.catch(details.reject);
const secondDetails = request.items.shift();
if (!secondDetails) return;
return editChannel(secondDetails.channelId, secondDetails.options);
await editChannel(secondDetails.channelId, secondDetails.options)
.then((result) => secondDetails.resolve(result))
.catch(secondDetails.reject);
return;
});
if (editChannelNameTopicQueue.size) {
setTimeout(() => {
eventHandlers.debug?.(
"loop",
`Running setTimeout in EDIT_CHANNEL file.`,
);
eventHandlers.debug?.("loop", `Running setTimeout in EDIT_CHANNEL file.`);
processEditChannelQueue();
}, 600000);
}, 60000);
} else {
editChannelProcessing = false;
}

View File

@@ -1,27 +1,20 @@
import { rest } from "../../rest/rest.ts";
import { Overwrite } from "../../types/channels/overwrite.ts";
import type { Overwrite } from "../../types/channels/overwrite.ts";
import { endpoints } from "../../util/constants.ts";
import {
calculateBits,
requireBotGuildPermissions,
} from "../../util/permissions.ts";
import { calculateBits, requireBotGuildPermissions } from "../../util/permissions.ts";
/** Edit the channel permission overwrites for a user or role in this channel. Requires `MANAGE_ROLES` permission. */
export async function editChannelOverwrite(
guildId: string,
channelId: string,
overwriteId: string,
options: Omit<Overwrite, "id">,
guildId: bigint,
channelId: bigint,
overwriteId: bigint,
options: Omit<Overwrite, "id">
): Promise<undefined> {
await requireBotGuildPermissions(guildId, ["MANAGE_ROLES"]);
return await rest.runMethod<undefined>(
"put",
endpoints.CHANNEL_OVERWRITE(channelId, overwriteId),
{
allow: calculateBits(options.allow),
deny: calculateBits(options.deny),
type: options.type,
},
);
return await rest.runMethod<undefined>("put", endpoints.CHANNEL_OVERWRITE(channelId, overwriteId), {
allow: calculateBits(options.allow),
deny: calculateBits(options.deny),
type: options.type,
});
}

View File

@@ -1,22 +1,15 @@
import { rest } from "../../rest/rest.ts";
import { FollowedChannel } from "../../types/channels/followed_channel.ts";
import type { FollowedChannel } from "../../types/channels/followed_channel.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
/** Follow a News Channel to send messages to a target channel. Requires the `MANAGE_WEBHOOKS` permission in the target channel. Returns the webhook id. */
export async function followChannel(
sourceChannelId: string,
targetChannelId: string,
) {
export async function followChannel(sourceChannelId: bigint, targetChannelId: bigint) {
await requireBotChannelPermissions(targetChannelId, ["MANAGE_WEBHOOKS"]);
const data = await rest.runMethod<FollowedChannel>(
"post",
endpoints.CHANNEL_FOLLOW(sourceChannelId),
{
webhook_channel_id: targetChannelId,
},
);
const data = await rest.runMethod<FollowedChannel>("post", endpoints.CHANNEL_FOLLOW(sourceChannelId), {
webhook_channel_id: targetChannelId,
});
return data.webhookId;
}

View File

@@ -1,29 +1,23 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import { Channel } from "../../types/channels/channel.ts";
import type { Channel } from "../../types/channels/channel.ts";
import { snowflakeToBigint } from "../../util/bigint.ts";
import { endpoints } from "../../util/constants.ts";
/** Fetches a single channel object from the api.
*
* ⚠️ **If you need this, you are probably doing something wrong. This is not intended for use. Your channels will be cached in your guild.**
*/
export async function getChannel(channelId: string, addToCache = true) {
const result = await rest.runMethod<Channel>(
"get",
endpoints.CHANNEL_BASE(channelId),
);
export async function getChannel(channelId: bigint, addToCache = true) {
const result = await rest.runMethod<Channel>("get", endpoints.CHANNEL_BASE(channelId));
const discordenoChannel = await structures.createDiscordenoChannel(
result,
result.guildId,
result.guildId ? snowflakeToBigint(result.guildId) : undefined
);
if (addToCache) {
await cacheHandlers.set(
"channels",
discordenoChannel.id,
discordenoChannel,
);
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
}
return discordenoChannel;

View File

@@ -1,19 +1,14 @@
import { rest } from "../../rest/rest.ts";
import { Webhook } from "../../types/webhooks/webhook.ts";
import type { Webhook } from "../../types/webhooks/webhook.ts";
import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
/** Gets the webhooks for this channel. Requires MANAGE_WEBHOOKS */
export async function getChannelWebhooks(channelId: string) {
export async function getChannelWebhooks(channelId: bigint) {
await requireBotChannelPermissions(channelId, ["MANAGE_WEBHOOKS"]);
const result = await rest.runMethod<Webhook[]>(
"get",
endpoints.CHANNEL_WEBHOOKS(channelId),
);
const result = await rest.runMethod<Webhook[]>("get", endpoints.CHANNEL_WEBHOOKS(channelId));
return new Collection(
result.map((webhook) => [webhook.id, webhook]),
);
return new Collection(result.map((webhook) => [webhook.id, webhook]));
}

View File

@@ -1,7 +1,7 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import { Channel } from "../../types/channels/channel.ts";
import type { Channel } from "../../types/channels/channel.ts";
import { Collection } from "../../util/collection.ts";
import { endpoints } from "../../util/constants.ts";
@@ -9,31 +9,21 @@ import { endpoints } from "../../util/constants.ts";
*
* ⚠️ **If you need this, you are probably doing something wrong. This is not intended for use. Your channels will be cached in your guild.**
*/
export async function getChannels(guildId: string, addToCache = true) {
const result = await rest.runMethod<Channel[]>(
"get",
endpoints.GUILD_CHANNELS(guildId),
);
export async function getChannels(guildId: bigint, addToCache = true) {
const result = await rest.runMethod<Channel[]>("get", endpoints.GUILD_CHANNELS(guildId));
return new Collection(
(
await Promise.all(
result.map(async (res) => {
const discordenoChannel = await structures.createDiscordenoChannel(
res,
guildId,
);
const discordenoChannel = await structures.createDiscordenoChannel(res, guildId);
if (addToCache) {
await cacheHandlers.set(
"channels",
discordenoChannel.id,
discordenoChannel,
);
await cacheHandlers.set("channels", discordenoChannel.id, discordenoChannel);
}
return discordenoChannel;
}),
})
)
).map((c) => [c.id, c]),
).map((c) => [c.id, c])
);
}

View File

@@ -1,16 +1,11 @@
import { rest } from "../../rest/rest.ts";
import { structures } from "../../structures/mod.ts";
import { Message } from "../../types/messages/message.ts";
import type { Message } from "../../types/messages/message.ts";
import { endpoints } from "../../util/constants.ts";
/** Get pinned messages in this channel. */
export async function getPins(channelId: string) {
const result = await rest.runMethod<Message[]>(
"get",
endpoints.CHANNEL_PINS(channelId),
);
export async function getPins(channelId: bigint) {
const result = await rest.runMethod<Message[]>("get", endpoints.CHANNEL_PINS(channelId));
return Promise.all(
result.map((res) => structures.createDiscordenoMessage(res)),
);
return Promise.all(result.map((res) => structures.createDiscordenoMessage(res)));
}

View File

@@ -0,0 +1,19 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
/** Gets the stage instance associated with the Stage channel, if it exists. */
export async function getStageInstance(channelId: bigint) {
const channel = await cacheHandlers.get("channels", channelId);
if (channel) {
if (channel.type !== ChannelTypes.GuildStageVoice) {
throw new Error(Errors.CHANNEL_NOT_STAGE_VOICE);
}
}
return await rest.runMethod<StageInstance>("get", endpoints.STAGE_INSTANCE(channelId));
}

View File

@@ -1,7 +1,7 @@
import { cacheHandlers } from "../../cache.ts";
/** Checks whether a channel is synchronized with its parent/category channel or not. */
export async function isChannelSynced(channelId: string) {
export async function isChannelSynced(channelId: bigint) {
const channel = await cacheHandlers.get("channels", channelId);
if (!channel?.parentId) return false;
@@ -9,12 +9,8 @@ export async function isChannelSynced(channelId: string) {
if (!parentChannel) return false;
return channel.permissionOverwrites?.every((overwrite) => {
const permission = parentChannel.permissionOverwrites?.find(
(ow) => ow.id === overwrite.id,
);
const permission = parentChannel.permissionOverwrites?.find((ow) => ow.id === overwrite.id);
if (!permission) return false;
return !(
overwrite.allow !== permission.allow || overwrite.deny !== permission.deny
);
return !(overwrite.allow !== permission.allow || overwrite.deny !== permission.deny);
});
}

View File

@@ -1,7 +1,7 @@
import { cacheHandlers } from "../../cache.ts";
import { rest } from "../../rest/rest.ts";
import { DiscordChannelTypes } from "../../types/channels/channel_types.ts";
import { Errors } from "../../types/misc/errors.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import { endpoints } from "../../util/constants.ts";
import { botHasChannelPermissions } from "../../util/permissions.ts";
@@ -10,33 +10,28 @@ import { botHasChannelPermissions } from "../../util/permissions.ts";
* However, if a bot is responding to a command and expects the computation to take a few seconds,
* this endpoint may be called to let the user know that the bot is processing their message.
*/
export async function startTyping(channelId: string) {
export async function startTyping(channelId: bigint) {
const channel = await cacheHandlers.get("channels", channelId);
// If the channel is cached, we can do extra checks/safety
if (channel) {
if (
![
DiscordChannelTypes.DM,
DiscordChannelTypes.GUILD_NEWS,
DiscordChannelTypes.GUILD_TEXT,
DiscordChannelTypes.GuildNews,
DiscordChannelTypes.GuildText,
DiscordChannelTypes.GuildNewsThread,
DiscordChannelTypes.GuildPivateThread,
DiscordChannelTypes.GuildPublicThread,
].includes(channel.type)
) {
throw new Error(Errors.CHANNEL_NOT_TEXT_BASED);
}
const hasSendMessagesPerm = await botHasChannelPermissions(
channelId,
["SEND_MESSAGES"],
);
if (
!hasSendMessagesPerm
) {
const hasSendMessagesPerm = await botHasChannelPermissions(channelId, ["SEND_MESSAGES"]);
if (!hasSendMessagesPerm) {
throw new Error(Errors.MISSING_SEND_MESSAGES);
}
}
return await rest.runMethod<undefined>(
"post",
endpoints.CHANNEL_TYPING(channelId),
);
return await rest.runMethod<undefined>("post", endpoints.CHANNEL_TYPING(channelId));
}

View File

@@ -1,19 +1,12 @@
import { rest } from "../../rest/rest.ts";
import { ModifyGuildChannelPositions } from "../../types/guilds/modify_guild_channel_position.ts";
import type { ModifyGuildChannelPositions } from "../../types/guilds/modify_guild_channel_position.ts";
import { endpoints } from "../../util/constants.ts";
/** Modify the positions of channels on the guild. Requires MANAGE_CHANNELS permisison. */
export async function swapChannels(
guildId: string,
channelPositions: ModifyGuildChannelPositions[],
) {
export async function swapChannels(guildId: bigint, channelPositions: ModifyGuildChannelPositions[]) {
if (channelPositions.length < 2) {
throw "You must provide at least two channels to be swapped.";
}
return await rest.runMethod<undefined>(
"patch",
endpoints.GUILD_CHANNELS(guildId),
channelPositions,
);
return await rest.runMethod<undefined>("patch", endpoints.GUILD_CHANNELS(guildId), channelPositions);
}

View File

@@ -0,0 +1,27 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { ChannelTypes } from "../../../types/channels/channel_types.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
//TODO(threads): this does not work rn
/** Adds the current user to a thread. Returns a 204 empty response on success. Also requires the thread is not archived. Fires a Thread Members Update Gateway event.Adds another user to a thread. Requires the ability to send messages in the thread. Also requires the thread is not archived. Returns a 204 empty response on success. Fires a Thread Members Update Gateway event.
* @param userId the user to add to the thread defaults to bot
*/
export async function addToThread(channelId: bigint, userId?: bigint) {
// TODO(threads): perm check
const channel = await cacheHandlers.get("channels", channelId);
if (channel) {
if (
![ChannelTypes.GuildNewsThread, ChannelTypes.GuildPivateThread, ChannelTypes.GuildPublicThread].includes(
channel.type
)
) {
throw new Error(Errors.NOT_A_THREAD_CHANNEL);
}
}
return await rest.runMethod(
"put",
userId ? endpoints.THREAD_USER(channelId, userId) : endpoints.THREAD_ME(channelId)
);
}

View File

@@ -0,0 +1,9 @@
import { rest } from "../../../rest/rest.ts";
import { endpoints } from "../../../util/constants.ts";
/** Returns all active threads in the channel, including public and private threads. Threads are ordered by their id, in descending order. Requires the READ_MESSAGE_HISTORY permission. */
export async function getActiveThreads(channelId: bigint) {
// TODO(threads): perm check
// TODO(threads): test if it works
return await rest.runMethod("get", endpoints.THREAD_ACTIVE(channelId));
}

View File

@@ -0,0 +1,24 @@
import { rest } from "../../../rest/rest.ts";
import { ListPublicArchivedThreads } from "../../../types/channels/threads/list_public_archived_threads.ts";
import { endpoints } from "../../../util/constants.ts";
import { snakelize } from "../../../util/utils.ts";
export async function getArchivedThreads(
channelId: bigint,
options?: ListPublicArchivedThreads & {
type?: "public" | "private" | "privateJoinedThreads";
}
) {
// TODO(threads): perm check
// TODO(threads): check if this works
return await rest.runMethod(
"get",
options?.type === "privateJoinedThreads"
? endpoints.THREAD_ARCHIVED_PRIVATE_JOINED(channelId)
: options?.type === "private"
? endpoints.THREAD_ARCHIVED_PRIVATE(channelId)
: endpoints.THREAD_ARCHIVED_PUBLIC(channelId),
snakelize(options ?? {})
);
}

View File

@@ -0,0 +1,24 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { ChannelTypes } from "../../../types/channels/channel_types.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
// TODO(threads): it seems like the documented return type is wrong
/** Returns array of thread members objects that are members of the thread. */
export async function getThreadMembers(channelId: bigint) {
// TODO(threads): perm check
// TODO(threads): intents check
const channel = await cacheHandlers.get("channels", channelId);
if (channel) {
if (
![ChannelTypes.GuildNewsThread, ChannelTypes.GuildPivateThread, ChannelTypes.GuildPublicThread].includes(
channel.type
)
) {
throw new Error(Errors.NOT_A_THREAD_CHANNEL);
}
}
return await rest.runMethod("get", endpoints.THREAD_MEMBERS(channelId));
}

View File

@@ -0,0 +1,25 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { ChannelTypes } from "../../../types/channels/channel_types.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
/** Removes another user from a thread. Requires the MANAGE_THREADS permission or that you are the creator of the thread. Also requires the thread is not archived. Returns a 204 empty response on success. Fires a Thread Members Update Gateway event. */
export async function removeFromThread(channelId: bigint, userId?: bigint) {
// TODO(threads): perm check
const channel = await cacheHandlers.get("channels", channelId);
if (channel) {
if (
![ChannelTypes.GuildNewsThread, ChannelTypes.GuildPivateThread, ChannelTypes.GuildPublicThread].includes(
channel.type
)
) {
throw new Error(Errors.NOT_A_THREAD_CHANNEL);
}
}
return await rest.runMethod(
"delete",
userId ? endpoints.THREAD_USER(channelId, userId) : endpoints.THREAD_ME(channelId)
);
}

View File

@@ -0,0 +1,33 @@
import { cacheHandlers } from "../../../cache.ts";
import { rest } from "../../../rest/rest.ts";
import { ChannelTypes } from "../../../types/channels/channel_types.ts";
import { StartThread } from "../../../types/channels/threads/start_thread.ts";
import { Errors } from "../../../types/discordeno/errors.ts";
import { endpoints } from "../../../util/constants.ts";
import { snakelize } from "../../../util/utils.ts";
/**
* Creates a new public thread from an existing message. Returns a channel on success, and a 400 BAD REQUEST on invalid parameters. Fires a Thread Create Gateway event.
* @param messageId when provided the thread will be public
*/
export async function startThread(channelId: bigint, options: StartThread & { messageId?: bigint }) {
const channel = await cacheHandlers.get("channels", channelId);
if (channel) {
// TODO(threads): perm check
if (![ChannelTypes.GuildText, ChannelTypes.GuildNews].includes(channel.type)) {
throw new Error(Errors.INVALID_THREAD_PARENT_CHANNEL_TYPE);
}
if (!options.messageId && channel.type === ChannelTypes.GuildNews) {
throw new Error(Errors.GUILD_NEWS_CHANNEL_ONLY_SUPPORT_PUBLIC_THREADS);
}
}
return await rest.runMethod(
"post",
options?.messageId
? endpoints.THREAD_START_PUBLIC(channelId, options.messageId)
: endpoints.THREAD_START_PRIVATE(channelId),
snakelize(options)
);
}

View File

@@ -0,0 +1,37 @@
import { rest } from "../../rest/rest.ts";
import { Errors } from "../../types/discordeno/errors.ts";
import type { StageInstance } from "../../types/channels/stage_instance.ts";
import { endpoints } from "../../util/constants.ts";
import { validateLength } from "../../util/validate_length.ts";
import { cacheHandlers } from "../../cache.ts";
import { requireBotChannelPermissions } from "../../util/permissions.ts";
import { ChannelTypes } from "../../types/channels/channel_types.ts";
import { snakelize } from "../../util/utils.ts";
/** Updates fields of an existing Stage instance. Requires the user to be a moderator of the Stage channel. */
export async function updateStageInstance(
channelId: bigint,
data: Partial<Pick<StageInstance, "topic" | "privacyLevel">> = {}
) {
const channel = await cacheHandlers.get("channels", channelId);
if (channel) {
if (channel.type !== ChannelTypes.GuildStageVoice) {
throw new Error(Errors.CHANNEL_NOT_STAGE_VOICE);
}
await requireBotChannelPermissions(channel, ["MOVE_MEMBERS", "MUTE_MEMBERS", "MANAGE_CHANNELS"]);
}
if (
data?.topic &&
!validateLength(data.topic, {
min: 1,
max: 120,
})
) {
throw new Error(Errors.INVALID_TOPIC_LENGTH);
}
return await rest.runMethod<StageInstance>("patch", endpoints.STAGE_INSTANCE(channelId), snakelize(data));
}

View File

@@ -0,0 +1,27 @@
import { rest } from "../../rest/rest.ts";
import { UpdateOthersVoiceState } from "../../types/guilds/update_others_voice_state.ts";
import type { UpdateSelfVoiceState } from "../../types/guilds/update_self_voice_state.ts";
import { endpoints } from "../../util/constants.ts";
import { hasOwnProperty, snakelize } from "../../util/utils.ts";
/**
* Updates the a user's voice state, defaults to the current user
* Caveats:
* - `channel_id` must currently point to a stage channel.
* - User must already have joined `channel_id`.
* - You must have the `MUTE_MEMBERS` permission. But can always suppress yourself.
* - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not.
* - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak.
* - You are able to set `request_to_speak_timestamp` to any present or future time.
* - When suppressed, the user will have their `request_to_speak_timestamp` removed.
*/
export async function updateBotVoiceState(
guildId: bigint,
options: UpdateSelfVoiceState | ({ userId: bigint } & UpdateOthersVoiceState)
) {
return await rest.runMethod(
"patch",
endpoints.UPDATE_VOICE_STATE(guildId, hasOwnProperty(options, "userId") ? options.userId : undefined),
snakelize(options)
);
}

View File

@@ -1,17 +0,0 @@
import { applicationId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts";
import { ApplicationCommandPermissions } from "../../types/interactions/application_command_permissions.ts";
import { endpoints } from "../../util/constants.ts";
import { camelKeysToSnakeCase } from "../../util/utils.ts";
/** Batch edits permissions for all commands in a guild. Takes an array of partial GuildApplicationCommandPermissions objects including `id` and `permissions`. */
export async function batchEditSlashCommandPermissions(
guildId: string,
options: { id: string; permissions: ApplicationCommandPermissions[] }[],
) {
return await rest.runMethod(
"put",
endpoints.COMMANDS_PERMISSIONS(applicationId, guildId),
camelKeysToSnakeCase(options),
);
}

View File

@@ -1,16 +0,0 @@
import { applicationId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
/** Deletes a slash command. */
export async function deleteSlashCommand(
id: string,
guildId?: string,
) {
return await rest.runMethod<undefined>(
"delete",
guildId
? endpoints.COMMANDS_GUILD_ID(applicationId, guildId, id)
: endpoints.COMMANDS_ID(applicationId, id),
);
}

View File

@@ -1,20 +0,0 @@
import { applicationId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts";
import { endpoints } from "../../util/constants.ts";
/** To delete your response to a slash command. If a message id is not provided, it will default to deleting the original response. */
export async function deleteSlashResponse(
token: string,
messageId?: string,
) {
return await rest.runMethod<undefined>(
"delete",
messageId
? endpoints.INTERACTION_ID_TOKEN_MESSAGE_ID(
applicationId,
token,
messageId,
)
: endpoints.INTERACTION_ORIGINAL_ID_TOKEN(applicationId, token),
);
}

View File

@@ -1,18 +0,0 @@
import { applicationId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts";
import { ApplicationCommandPermissions } from "../../types/interactions/application_command_permissions.ts";
import { endpoints } from "../../util/constants.ts";
import { camelKeysToSnakeCase } from "../../util/utils.ts";
/** Edits command permissions for a specific command for your application in a guild. */
export async function editSlashCommandPermissions(
guildId: string,
commandId: string,
options: ApplicationCommandPermissions[],
) {
return await rest.runMethod(
"put",
endpoints.COMMANDS_PERMISSION(applicationId, guildId, commandId),
{ permissions: camelKeysToSnakeCase(options) },
);
}

View File

@@ -1,14 +0,0 @@
import { applicationId } from "../../bot.ts";
import { rest } from "../../rest/rest.ts";
import { ApplicationCommand } from "../../types/interactions/application_command.ts";
import { endpoints } from "../../util/constants.ts";
/** Fetchs the global command for the given Id. If a guildId is provided, the guild command will be fetched. */
export async function getSlashCommand(commandId: string, guildId?: string) {
return await rest.runMethod<ApplicationCommand>(
"get",
guildId
? endpoints.COMMANDS_GUILD_ID(applicationId, guildId, commandId)
: endpoints.COMMANDS_ID(applicationId, commandId),
);
}

Some files were not shown because too many files have changed in this diff Show More