This commit is contained in:
Skillz4Killz
2022-10-09 22:41:11 +00:00
5 changed files with 63 additions and 58 deletions
+7 -5
View File
@@ -8,12 +8,14 @@ export async function connect(shard: Shard): Promise<void> {
}
shard.events.connecting?.(shard);
let url = shard.gatewayConfig.url;
let url = new URL(shard.gatewayConfig.url);
// If not connecting to a proxy but directly to discord need to handle resuming
if (url === "wss://gateway.discord.gg") {
url = `${
shard.state === ShardState.Resuming ? shard.resumeGatewayUrl : shard.gatewayConfig.url
}/?v=${shard.gatewayConfig.version}&encoding=json`;
if (url.origin === "wss://gateway.discord.gg") {
if (shard.state === ShardState.Resuming) {
url = new URL(shard.resumeGatewayUrl);
}
url.searchParams.set("v", shard.gatewayConfig.version.toString());
url.searchParams.set("encoding", "json");
}
const socket = new WebSocket(url);
@@ -9,7 +9,7 @@ export function connectToVoiceChannel(bot: BotWithCache) {
if (!channel) throw new Error("CHANNEL_NOT_FOUND");
if (
[ChannelTypes.GuildStageVoice, ChannelTypes.GuildVoice].includes(
![ChannelTypes.GuildStageVoice, ChannelTypes.GuildVoice].includes(
channel.type,
)
) {
@@ -50,7 +50,7 @@ emitting some event to trigger that function.
// EventEmitter Example
EventEmitter.emit("guildCreate", guild);
// Discordeno Example
eventHandlers.guildCreate?.(guild);
bot.events.guildCreate?.(bot, guild);
```
There isn't really any difference especially for users when they use it. One bad thing about EventEmitter is that if
@@ -60,10 +60,10 @@ issues I had. It prevents anyone from having this as a potential issue. Another
update the code in those functions without having to deal with headaches left and right of removing and adding
listeners. You don't need to worry about binding or not binding events. They are just pure functions
In Discordeno, this is extremely simple, you just simply give it the new event handlers.
In Discordeno, this is extremely simple, you just simply give it the new event handlers. For example:
```typescript
updateEventHandlers(newEventHandlers);
bot.events.guildCreate = newGuildCreateEventHandler;
```
## Why Do You Have A Class for Collection If Classes Are Bad?
@@ -99,17 +99,18 @@ have even seen some bots have hundreds of thousands of Missing Permission or Mis
don't handle it. IMO, this is a crucial part of any good library as much as it is to handle rate limiting.
```typescript
import { Errors, Message } from "https://deno.land/x/discordeno@10.0.0/mod.ts";
import { Bot, Errors, Message } from "https://deno.land/x/discordeno@16.0.0/mod.ts";
export function handleCommandError(message: Message, type: Errors) {
export function handleCommandError(bot: Bot, message: Message, type: Errors) {
switch (type) {
case Errors.MISSING_MANAGE_NICKNAMES:
return message.channel.sendMessage(
"The bot does not have the necessary permission to manage/edit other user's nicknames. Grant the **MANAGE_NICKNAME** permission to the bot and try again.",
);
return bot.helpers.sendMessage(message.channelId, {
content:
"The bot does not have the necessary permission to manage/edit other user's nicknames. Grant the **MANAGE_NICKNAME** permission to the bot and try again.",
});
case Errors.MISSING_MANAGE_ROLES:
// Note: i18n is not part of the library. This is just an example of how you could use i18n for custom error responses.
return message.channel.sendMessage(i18n.translate(type));
return bot.helpers.sendMessage(message.channelId, { content: i18n.translate(type) });
}
}
```
+17 -15
View File
@@ -36,7 +36,7 @@ in handy!
You can install Discordeno by importing:
```ts
import { startBot } from "https://deno.land/x/discordeno@10.0.0/mod.ts";
import { startBot } from "https://deno.land/x/discordeno@16.0.0/mod.ts";
```
## Example Usage
@@ -45,22 +45,24 @@ Starting with Discordeno is very simple, you can start from scratch without any
of code into a new TypeScript file:
```ts
import { Intents, startBot } from "https://deno.land/x/discordeno/mod.ts";
import { createBot, Intents, startBot } from "https://deno.land/x/discordeno/mod.ts";
startBot({
token: "BOT TOKEN",
intents: Intents.Guilds | Intents.GuildMessages,
eventHandlers: {
ready() {
console.log("Successfully connected to gateway");
startBot(
createBot({
token: "BOT TOKEN",
intents: Intents.Guilds | Intents.GuildMessages,
events: {
ready() {
console.log("Successfully connected to gateway");
},
messageCreate(bot, message) {
if (message.content === "!ping") {
bot.helpers.sendMessage(message.channelId, { content: "Pong using Discordeno!" });
}
},
},
messageCreate(message) {
if (message.content === "!ping") {
message.reply("Pong using Discordeno!");
}
},
},
});
}),
);
```
## Tutorials
+28 -28
View File
@@ -163,7 +163,7 @@ startBot({
// For instance, to work with guild message reactions, you will have to pass the Intents.GUILD_MESSAGE_REACTIONS intent to the array.
intents: Intents.Guilds | Intents.GuildMessages,
// These are all your event handler functions. Imported from the events folder
eventHandlers: botCache.eventHandlers,
events: botCache.events,
});
```
@@ -174,19 +174,19 @@ there is already a `ready.ts` file. We can just use that.
In our `ready.ts` file we can add the `ready` event listener.
```ts
import { ActivityType, botCache, cache, chooseRandom, editBotsStatus, StatusTypes } from "../../deps.ts";
import { ActivityTypes, botCache, cache, chooseRandom, editBotStatus, StatusTypes } from "../../deps.ts";
import { registerTasks } from "./../utils/taskHelper.ts";
botCache.eventHandlers.ready = function () {
editBotsStatus(
botCache.events.ready = function () {
editBotStatus(
StatusTypes.DoNotDisturb,
"Discordeno Best Lib",
ActivityType.Game,
ActivityTypes.Game,
);
console.log(`Loaded ${botCache.arguments.size} Argument(s)`);
console.log(`Loaded ${botCache.commands.size} Command(s)`);
console.log(`Loaded ${Object.keys(botCache.eventHandlers).length} Event(s)`);
console.log(`Loaded ${Object.keys(botCache.events).length} Event(s)`);
console.log(`Loaded ${botCache.inhibitors.size} Inhibitor(s)`);
console.log(`Loaded ${botCache.monitors.size} Monitor(s)`);
console.log(`Loaded ${botCache.tasks.size} Task(s)`);
@@ -200,18 +200,19 @@ botCache.eventHandlers.ready = function () {
// list of activities that the bot goes through
const activityArray = [`${configs.prefix}help | `];
setInterval(() => {
editBotsStatus(
StatusType.Online,
chooseRandom(activityArray),
ActivityType.Game,
);
const randomActivity = activityArray[Math.floor(Math.random() * activityArray.length)];
editBotStatus(botCache, {
activities: [{ name: randomActivity, type: ActivityTypes.Game, createdAt: Date.now() }],
status: "online",
});
}, 5000);
};
```
To understand this code, we are setting a function to be run when the bot is `ready`. Then the bot will edit the bots
status every 5 seconds. Notice, that Discordeno provides a nice clean util function to choose a random item from an
array. You also have beautiful enums provided that prevent you from making any typos/mistakes.
To understand this code, we are setting a function to be run when the bot is `ready`. Then the bot will edit the bot's
status every 5 seconds. Notice that you also have beautiful enums provided that prevents you from making any
typos/mistakes.
We have now converted the entire `main.js` file, in a matter of seconds. The Discordeno official generator took care of
the majority of workload and we just modified the `ready.ts` file.
@@ -293,18 +294,17 @@ createCommand({
{ name: "member", type: "member" },
{ name: "role", type: "role" },
],
execute: (message, args) => {
execute: (bot, message, args) => {
// checking to see if the user has the role or not
if (!args.member.roles.includes(args.role.id)) {
args.member.addRole(message.guildId, args.role.id);
message.reply(
`${args.member.mention} has been given the role: ${args.role.name}`,
5,
);
bot.helpers.addRole(message.guildId, args.member.id, args.role.id);
bot.helpers.sendMessage(message.channelId, {
content: `${args.member.mention} has been given the role: ${args.role.name}`,
});
} else {
message.reply(
`${args.member.mention} already has the role: ${args.role.name}`,
);
bot.helpers.sendMessage(message.channelId, {
content: `${args.member.mention} already has the role: ${args.role.name}`,
});
}
},
});
@@ -427,7 +427,7 @@ createCommand({
lowercase: true,
},
],
execute: function (message, args: KickArgs) {
execute: function (bot, message, args: KickArgs) {
// setting up the embed for report/log
const embed = new Embed()
.setDescription(`Report: ${args.member.mention} Kick`)
@@ -436,15 +436,15 @@ createCommand({
const reportchannel = message.guild?.channels.find((channel) => channel.name === "report");
if (!reportchannel) {
return message.reply("*`Report channel cannot be found!`*");
return bot.helpers.sendMessage(message.channelId, { content: "*`Report channel cannot be found!`*" });
}
// Delete the message command
message.delete("Remove kick command trigger.");
bot.helpers.deleteMessage(message.channelId, { content: "Remove kick command trigger." });
// Kick the user with reason
args.member.kick(message.guildId, args.reason);
bot.helpers.kickMember(message.guildId, args.member.id, args.reason);
// sends the kick report into log/report
reporchannel.send({ embed });
bot.helpers.sendMessage(message.channelId, { embeds: [embed] });
},
});