This commit is contained in:
Skillz4Killz
2022-05-08 14:05:08 +00:00
committed by GitHub
15 changed files with 195 additions and 63 deletions

View File

@@ -32,7 +32,7 @@ jobs:
run: deno cache template/beginner/mod.ts template/bigbot/src/bot/mod.ts template/bigbot/src/gateway/mod.ts template/bigbot/src/rest/mod.ts template/minimal/mod.ts
- name: Run test script for maintainers
if: ${{ github.actor == 'Skillz4Killz' || github.actor == 'itohatweb' }}
run: deno test --unstable --coverage=coverage -A tests/mod.ts
run: deno test --unstable --coverage=coverage -A testss/
- name: Create coverage report
if: github.ref == 'refs/heads/main'
run: deno coverage --exclude=tests ./coverage --lcov > coverage.lcov
@@ -43,3 +43,5 @@ jobs:
file: ./coverage.lcov
env:
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}
PROXY_REST_SECRET: ${{ secrets.PROXY_REST_SECRET }}
PROXY_REST_URL: ${{ secrets.PROXY_REST_URL }}

View File

@@ -133,6 +133,7 @@ these awesome official and unofficial templates:
- [Discordeno Template (official)](https://github.com/discordeno/discordeno/tree/main/template)
- [Serverless Slash Commands Template (official)](https://github.com/discordeno/serverless-deno-deploy-template)
- [`create-discordeno-bot` (WIP, unoffical)](https://github.com/Reboot-Codes/create-discordeno-bot/)
- [Add Your Own!](https://github.com/discordeno/discordeno/pulls)
### Frameworks

View File

@@ -26,6 +26,11 @@ export async function handleOnMessage(gateway: GatewayManager, message: any, sha
if (typeof message !== "string") return;
const shard = gateway.shards.get(shardId);
if (shard) {
// Edge case for big bots when too many events that 45 seconds are not enough for receving the heartbeat ack. As long as we are receving events no point in closing a connection.
shard.heartbeat.acknowledged = true;
}
const messageData = JSON.parse(message) as DiscordGatewayPayload;
gateway.debug("GW RAW", { shardId, payload: messageData });
@@ -52,8 +57,7 @@ export async function handleOnMessage(gateway: GatewayManager, message: any, sha
if (shard) shard.safeRequestsPerShard = gateway.safeRequestsPerShard(gateway, shard);
break;
case GatewayOpcodes.HeartbeatACK:
if (gateway.shards.has(shardId)) {
const shard = gateway.shards.get(shardId)!;
if (shard) {
shard.heartbeat.acknowledged = true;
shard.heartbeat.lastReceivedAt = Date.now();
}

View File

@@ -9,8 +9,11 @@ export async function getChannel(bot: Bot, channelId: bigint) {
bot.constants.endpoints.CHANNEL_BASE(channelId),
);
return bot.transformers.channel(bot, {
channel: result,
guildId: result.guild_id ? bot.transformers.snowflake(result.guild_id) : undefined,
});
// IF A CHANNEL DOESN'T EXIST, DISCORD RETURNS `{}`
return result.id
? bot.transformers.channel(bot, {
channel: result,
guildId: result.guild_id ? bot.transformers.snowflake(result.guild_id) : undefined,
})
: undefined;
}

12
site/package-lock.json generated
View File

@@ -3753,9 +3753,9 @@
"integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY="
},
"node_modules/async": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.3.tgz",
"integrity": "sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg==",
"version": "2.6.4",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz",
"integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==",
"dependencies": {
"lodash": "^4.17.14"
}
@@ -15638,9 +15638,9 @@
"integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY="
},
"async": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.3.tgz",
"integrity": "sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg==",
"version": "2.6.4",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz",
"integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==",
"requires": {
"lodash": "^4.17.14"
}

View File

@@ -1,77 +1,90 @@
# Discordeno Big Bot Template
Support: https://discord.gg/ddeno
Support: <https://discord.gg/ddeno>
This template is designed for bots that aim or are already in millions of Discord servers.
This template is designed for bots that aim or are already in millions of
Discord servers.
## Setup
- Use the template generator button to make your own copy.
- Delete all the template folders except the bigbot folder.
- Move all files from the bigbot folder to the root of the project.
- You may encounter an issue with .vscode but force move the files to the root of the project. We have setup special
import maps in this template that should override the general .vscode folder already in the root folder.
- Rename the .env.example file to .env
- Fill out the .env file
- Go to configs.ts file and remove all the intents you don't want in your bot.
- Install `make` if you want to make it easier to use.
- This may be switched to `deno tasks` when it is available.
- Delete all the template folders except the `bigbot` folder.
- Move all files from the `bigbot` folder to the root of the project.
- You may encounter an issue with .vscode but force move the files to the root
of the project. We have setup special import maps in this template that
should override the general .vscode folder already in the root folder.
- Rename the `.env.example` file to `.env`
- Fill out the `.env` file
- Go to `configs.ts` file and remove all the intents you don't want in your bot.
## Usage
- Always run the `rest` process first. `make rest`
- Start the `bot` process next. `make bot`
- Lastly, start the `gateway` process. `make gateway`
- Always run the `rest` process first. `deno task rest`
- Start the `bot` process next. `deno task bot`
- Lastly, start the `gateway` process. `deno task gateway`
Note: The `gateway` process and `rest` are designed not to be shut off. So once those are on, the only thing you should
be doing is restarting your `bot` process.
Note: The `gateway` process and `rest` are designed not to be shut off. So once
those are on, the only thing you should be doing is restarting your `bot`
process.
## Details
### Translating Application Commands
The template supports translations for application commands. This is possible using guild commands. If you use global
commands, translations will not work and will default to english.
The template supports translations for application commands. This is possible
using guild commands. If you use global commands, translations will not work and
will default to english.
If you prefer a different default(not english), please use the Find And Replace to change the `'english'` everywhere
necessary.
If you prefer a different default(not english), please use the Find And Replace
to change the `'english'` everywhere necessary.
#### Autocomplete & Type Checking
One cool thing about the translations is that you will get autocomplete and type checking built in for all the keys.
This will ensure you do not miss a key to be translated. It will also make it easier to code by providing the
autocomplete functionality.
One cool thing about the translations is that you will get autocomplete and type
checking built in for all the keys. This will ensure you do not miss a key to be
translated. It will also make it easier to code by providing the autocomplete
functionality.
### Updating Application Commands
The template is designed in a way that you will no longer need to worry about updating or maintaing your commands.
The template is designed in a way that you will no longer need to worry about
updating or maintaing your commands.
- Global Commands: For simplicity you can add a line in mod.ts to update them globally. This generally takes 1 call and
isn't a deal breaker.
- `/update global` is also available on your development server, to trigger manually.
- Guild Commands: This is a bit more complicated. By default, our system will update guild commands on demand! Instead
of making a million requests for all your servers, we will update them as needed.
- Global Commands: For simplicity you can add a line in mod.ts to update them
globally. This generally takes 1 call and isn't a deal breaker.
- `/update global` is also available on your development server, to trigger
manually.
- Guild Commands: This is a bit more complicated. By default, our system will
update guild commands on demand! Instead of making a million requests for all
your servers, we will update them as needed.
**Guild Commands Kwik & Command Versioning**
For Global Commands you can make 1 request to api to update all commands on restart. Its not a big deal. But with Guild
commands essentially you need to make a request per guild. This can get spammy. That would be crazy. To solve this we
created the concept of `commandVersions`. This basically will decide whether or not guild commands should be updated.
For Global Commands you can make 1 request to api to update all commands on
restart. Its not a big deal. But with Guild commands essentially you need to
make a request per guild. This can get spammy. That would be crazy. To solve
this we created the concept of `commandVersions`. This basically will decide
whether or not guild commands should be updated.
Kwik is a file based database I used in order to make this setup easy and allow any dev using this template to use a
database of their choice for their bot. I do not recommend using Kwik as your database. Please add a full database of
your choice for your bot. You can even replace Kwik should you choose in the database folder.
Kwik is a file based database I used in order to make this setup easy and allow
any dev using this template to use a database of their choice for their bot. I
do not recommend using Kwik as your database. Please add a full database of your
choice for your bot. You can even replace Kwik should you choose in the database
folder.
Process:
1. You update your command options/args or create new commands etc...
2. Increment the `CURRENT_SLASH_COMMAND_VERSION` in `src/database/commandVersion.ts`
2. Increment the `CURRENT_SLASH_COMMAND_VERSION` in
`src/database/commandVersion.ts`
- I recommend moving this into your database so you can build a dev command or eval and update this on the fly as you
wish.
- I recommend moving this into your database so you can build a dev command or
eval and update this on the fly as you wish.
3. Now whenever a guild emits any event, this will make sure to update the guild commands if necessary. If it already
has the latest commands, it will just ignore. If it was never updated or is using an outdated version, it will update
it.
3. Now whenever a guild emits any event, this will make sure to update the guild
commands if necessary. If it already has the latest commands, it will just
ignore. If it was never updated or is using an outdated version, it will
update it.
Aside from the automated system, there is also the option of `/update guild id` to update a guild manually.
Aside from the automated system, there is also the option of `/update guild id`
to update a guild manually.

View File

@@ -25,7 +25,7 @@ export const GATEWAY_INTENTS: (keyof typeof GatewayIntents)[] = [
if (!env.DISCORD_TOKEN) {
throw new Error("DUDE! You did not provide a Discord token!");
}
export const DISCORD_TOKEN = `Bot ${env.DISCORD_TOKEN!}`;
export const DISCORD_TOKEN = env.DISCORD_TOKEN!;
// Set as 0 to make it use default values. NOT RECOMMENDED TO DEFAULT FOR BIG BOTS!!!!
export const MAX_SHARDS = env.MAX_SHARDS ? parseInt(env.MAX_SHARDS, 10) : 0;

View File

@@ -0,0 +1,7 @@
{
"tasks": {
"rest": "deno run -A --unstable --import-map ./importMap.json ./src/rest/mod.ts",
"bot": "deno run -A --unstable --import-map ./importMap.json ./src/bot/mod.ts",
"gateway": "deno run -A --unstable --import-map ./importMap.json ./src/gateway/mod.ts"
}
}

View File

@@ -1,8 +1,8 @@
rest:
deno run -A --unstable --import-map ./importMap.json rest/mod.ts
deno run -A --unstable --import-map ./importMap.json ./src/rest/mod.ts
gateway:
deno run -A --unstable --import-map ./importMap.json src/gateway/mod.ts
deno run -A --unstable --import-map ./importMap.json ./src/gateway/mod.ts
bot:
deno run -A --unstable --import-map ./importMap.json src/bot/mod.ts
deno run -A --unstable --import-map ./importMap.json ./src/bot/mod.ts

View File

@@ -68,10 +68,16 @@ async function startGateway() {
gateway.buckets.forEach((bucket, bucketId) => {
for (let i = 0; i < bucket.workers.length; i++) {
const workerId = bucket.workers[i][0];
const worker = new Worker(new URL("./worker.js", import.meta.url).href, {
name: `w-${workerId}-b${bucketId}`,
type: "module",
});
const worker = new Worker(
new URL("./worker.ts", import.meta.url).href,
{
name: `w-${workerId}-b${bucketId}`,
type: "module",
deno: {
namespace: true,
},
},
);
workers.set(workerId, worker);
if (bucket.workers[i + 1]) {

View File

@@ -0,0 +1,23 @@
import { assertEquals, assertExists } from "../deps.ts";
import { loadBot } from "../mod.ts";
import { CACHED_COMMUNITY_GUILD_ID, delayUntil } from "../utils.ts";
Deno.test({
name: "[channel] delete a channel with a reason",
async fn(t) {
const bot = loadBot();
const channel = await bot.helpers.createChannel(CACHED_COMMUNITY_GUILD_ID, {
name: "delete-channel",
});
// Make sure the channel was created
assertExists(channel.id);
// Delete the channel now with a reason
await bot.helpers.deleteChannel(channel.id, "with a reason");
// Check if channel still exists
const exists = await bot.helpers.getChannel(channel.id);
assertEquals(exists, undefined);
},
});

View File

@@ -0,0 +1,24 @@
import { assertEquals, assertExists, assertThrows, assertThrowsAsync } from "../deps.ts";
import { loadBot } from "../mod.ts";
import { CACHED_COMMUNITY_GUILD_ID } from "../utils.ts";
Deno.test({
name: "[channel] delete a channel without a reason",
async fn(t) {
const bot = loadBot();
// Create a channel to delete
const channel = await bot.helpers.createChannel(CACHED_COMMUNITY_GUILD_ID, {
name: "delete-channel",
});
// Make sure the channel was created
assertExists(channel.id);
// Delete the channel now without a reason
await bot.helpers.deleteChannel(channel.id);
// Check if channel still exists
const exists = await bot.helpers.getChannel(channel.id);
assertEquals(exists, undefined);
},
});

2
testss/deps.ts Normal file
View File

@@ -0,0 +1,2 @@
export { config as dotenv } from "https://deno.land/x/dotenv@v3.2.0/mod.ts";
export * from "https://deno.land/std@0.137.0/testing/asserts.ts";

26
testss/mod.ts Normal file
View File

@@ -0,0 +1,26 @@
import { createBot, createRestManager, runMethod } from "../mod.ts";
import enableCachePlugin from "../plugins/cache/mod.ts";
import { dotenv } from "./deps.ts";
dotenv({ export: true, path: `${Deno.cwd()}/.env` });
export function loadBot() {
const token = Deno.env.get("DISCORD_TOKEN");
if (!token) throw new Error("Token was not provided.");
const botId = BigInt(atob(token.split(".")[0]));
const bot = enableCachePlugin(createBot({
events: {},
intents: [],
botId,
token,
}));
bot.rest = createRestManager({
token,
customUrl: Deno.env.get("PROXY_REST_URL"),
secretKey: Deno.env.get("PROXY_REST_SECRET"),
});
return bot;
}

21
testss/utils.ts Normal file
View File

@@ -0,0 +1,21 @@
export const CACHED_COMMUNITY_GUILD_ID = 907350958810480671n;
export function delayUntil(
maxMs: number,
isReady: () => boolean | undefined | Promise<boolean | undefined>,
timeoutTime = 100,
): Promise<void> {
const maxTime = Date.now() + maxMs;
async function hackyFix(resolve: () => void) {
if ((await isReady()) || Date.now() >= maxTime) {
resolve();
} else {
setTimeout(() => {
hackyFix(resolve);
}, timeoutTime);
}
}
return new Promise((resolve) => hackyFix(resolve));
}