chore: use single quotes (#68)

* chore: single quote
This commit is contained in:
Yuzu 2022-07-18 18:25:23 +00:00 committed by GitHub
parent 77f251e5d6
commit b15666f20e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
130 changed files with 7958 additions and 1430 deletions

View File

@ -42,18 +42,18 @@ that you should not make software that does things it is not supposed to do.
### Example bot (TS/JS)
```js
import Biscuit, { GatewayIntents } from "@oasisjs/biscuit";
import Biscuit, { GatewayIntents } from '@oasisjs/biscuit';
const intents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages;
const session = new Biscuit({ token: "your token", intents });
const session = new Biscuit({ token: 'your token', intents });
session.on("ready", ({ user }) => {
console.log("Logged in as:", user.username);
session.on('ready', ({ user }) => {
console.log('Logged in as:', user.username);
});
session.on("messageCreate", (message) => {
if (message.content.startsWith("!ping")) {
message.reply({ content: "pong!" });
session.on('messageCreate', (message) => {
if (message.content.startsWith('!ping')) {
message.reply({ content: 'pong!' });
}
});

6527
biscuit.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,70 +1,70 @@
import { build } from "https://deno.land/x/dnt@0.26.0/mod.ts";
import { build } from 'https://deno.land/x/dnt@0.26.0/mod.ts';
await Deno.remove("npm", { recursive: true }).catch((_) => {});
await Deno.remove('npm', { recursive: true }).catch((_) => {});
await build({
compilerOptions: {
lib: ["webworker", "es2020"],
lib: ['webworker', 'es2020'],
},
shims: {
custom: [
{
package: {
name: "ws",
version: "^8.4.0",
name: 'ws',
version: '^8.4.0',
},
globalNames: [
{
name: "WebSocket",
exportName: "default",
name: 'WebSocket',
exportName: 'default',
},
],
},
],
},
package: {
author: "Yuzuru",
name: "@oasisjs/biscuit",
author: 'Yuzuru',
name: '@oasisjs/biscuit',
version: Deno.args[0],
description: " brand new bleeding edge non bloated Discord library",
license: "Apache License 2.0",
description: ' brand new bleeding edge non bloated Discord library',
license: 'Apache License 2.0',
repository: {
type: "git",
url: "git+https://github.com/oasisjs/biscuit.git",
type: 'git',
url: 'git+https://github.com/oasisjs/biscuit.git',
},
bugs: {
url: "https://github.com/oasisjs/biscuit/issues",
url: 'https://github.com/oasisjs/biscuit/issues',
},
typesVersions: {
"*": {
"*": ["./types/mod.d.ts"],
"biscuit": ["./types/packages/biscuit/mod.d.ts"],
"discordeno": ["./types/packages/discordeno/mod.d.ts"],
"cache": ["./types/packages/cache/mod.d.ts"],
'*': {
'*': ['./types/mod.d.ts'],
'biscuit': ['./types/packages/biscuit/mod.d.ts'],
'discordeno': ['./types/packages/discordeno/mod.d.ts'],
'cache': ['./types/packages/cache/mod.d.ts'],
},
},
},
entryPoints: [
"./mod.ts",
'./mod.ts',
{
name: "./biscuit",
path: "packages/biscuit/mod.ts",
name: './biscuit',
path: 'packages/biscuit/mod.ts',
},
{
name: "./discordeno",
path: "packages/discordeno/mod.ts",
name: './discordeno',
path: 'packages/discordeno/mod.ts',
},
{
name: "./cache",
path: "packages/cache/mod.ts",
name: './cache',
path: 'packages/cache/mod.ts',
},
],
outDir: "./npm",
outDir: './npm',
declaration: true,
typeCheck: false,
test: false,
});
// post build steps
Deno.copyFileSync("LICENSE", "npm/LICENSE");
Deno.copyFileSync("README.md", "npm/README.md");
Deno.copyFileSync('LICENSE', 'npm/LICENSE');
Deno.copyFileSync('README.md', 'npm/README.md');

View File

@ -2,7 +2,8 @@
"fmt": {
"options": {
"indentWidth": 4,
"lineWidth": 120
"lineWidth": 120,
"singleQuote": true
}
}
}

View File

@ -4,7 +4,7 @@
"entry": "./mod.ts",
"description": "A brand new bleeding edge non bloated Discord library",
"homepage": "https://github.com/oasisjs/biscuit",
"version": "0.2.0",
"version": "0.2.1",
"releaseType": "patch",
"unstable": false,
"unlisted": false,

View File

@ -1,4 +1,4 @@
import "https://deno.land/std@0.146.0/dotenv/load.ts";
import 'https://deno.land/std@0.146.0/dotenv/load.ts';
import {
ActionRowBuilder,
ButtonBuilder,
@ -6,26 +6,26 @@ import {
GatewayIntents,
InteractionResponseTypes,
Session,
} from "https://deno.land/x/biscuit/mod.ts";
} from 'https://deno.land/x/biscuit/mod.ts';
const token = Deno.env.get("TOKEN") ?? Deno.args[0];
const token = Deno.env.get('TOKEN') ?? Deno.args[0];
if (!token) {
throw new Error("Please provide a token");
throw new Error('Please provide a token');
}
const intents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages;
const session = new Session({ token, intents });
const PREFIX = ">";
const components = new ButtonBuilder().setCustomId("ping").setLabel("Hello!").setStyle(ButtonStyles.Success);
const PREFIX = '>';
const components = new ButtonBuilder().setCustomId('ping').setLabel('Hello!').setStyle(ButtonStyles.Success);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(components).toJSON();
session.on("ready", (payload) => {
console.log("Logged in as:", payload.user.username);
session.on('ready', (payload) => {
console.log('Logged in as:', payload.user.username);
});
session.on("messageCreate", (message) => {
session.on('messageCreate', (message) => {
if (message.author?.bot || !message.content.startsWith(PREFIX)) {
return;
}
@ -33,21 +33,21 @@ session.on("messageCreate", (message) => {
const args = message.content.substring(PREFIX.length).trim().split(/\s+/gm);
const name = args.shift()?.toLowerCase();
if (name === "ping") {
if (name === 'ping') {
message.reply({ components: [row] });
}
});
// Follow interaction event
session.on("interactionCreate", (interaction) => {
session.on('interactionCreate', (interaction) => {
if (!interaction.isComponent()) {
return;
}
if (interaction.customId === "ping") {
if (interaction.customId === 'ping') {
interaction.respond({
type: InteractionResponseTypes.ChannelMessageWithSource,
data: { content: "pong!" },
data: { content: 'pong!' },
});
}
});

View File

@ -3,7 +3,7 @@
* this example should work on most systems, but if it doesn't just clone the library and import everything from mod.ts
*/
const { GatewayIntents, Session } = require("../mod.ts");
const { GatewayIntents, Session } = require('../mod.ts');
// if it didn't worked use:
// import { GatewayIntents, Session } from "@oasisjs/biscuit";
@ -12,20 +12,20 @@ const token = process.env.TOKEN;
const intents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages;
const session = new Session({ token, intents });
session.on("ready", (payload) => {
console.log("Logged in as:", payload.user.username);
session.on('ready', (payload) => {
console.log('Logged in as:', payload.user.username);
});
session.on("messageCreate", async (message) => {
session.on('messageCreate', async (message) => {
// GET
if (message.content.startsWith("whatever")) {
if (message.content.startsWith('whatever')) {
const whatever = await message.fetch();
console.log(whatever);
}
// POST
if (message.content.startsWith("ping")) {
message.reply({ content: "pong!" }).catch((err) => console.error(err));
if (message.content.startsWith('ping')) {
message.reply({ content: 'pong!' }).catch((err) => console.error(err));
}
});

View File

@ -2,27 +2,27 @@
* Deno example
*/
import "https://deno.land/std@0.146.0/dotenv/load.ts";
import 'https://deno.land/std@0.146.0/dotenv/load.ts';
// Session to create a new bot (and intents)
import { GatewayIntents, Session } from "https://deno.land/x/biscuit/mod.ts";
import { GatewayIntents, Session } from 'https://deno.land/x/biscuit/mod.ts';
const token = Deno.env.get("TOKEN") ?? Deno.args[0];
const token = Deno.env.get('TOKEN') ?? Deno.args[0];
if (!token) {
throw new Error("Please provide a token");
throw new Error('Please provide a token');
}
const intents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages;
const session = new Session({ token, intents });
session.on("ready", (payload) => {
console.log("Logged in as:", payload.user.username);
session.on('ready', (payload) => {
console.log('Logged in as:', payload.user.username);
});
const PREFIX = ">";
const PREFIX = '>';
session.on("messageCreate", (message) => {
session.on('messageCreate', (message) => {
if (message.author?.bot || !message.content.startsWith(PREFIX)) {
return;
}
@ -30,8 +30,8 @@ session.on("messageCreate", (message) => {
const args = message.content.substring(PREFIX.length).trim().split(/\s+/gm);
const name = args.shift()?.toLowerCase();
if (name === "ping") {
message.reply({ content: "pong!" });
if (name === 'ping') {
message.reply({ content: 'pong!' });
}
});

View File

@ -4,31 +4,31 @@
// process for get the token
/** @type {NodeJS.Process} process */
import process from "node:process";
import process from 'node:process';
// Session for create a new bot and intents
import { GatewayIntents, Session } from "@oasisjs/biscuit";
import { GatewayIntents, Session } from '@oasisjs/biscuit';
// Discord bot token
/** @type {string} token */
const token = process.env.TOKEN || "YOUR_TOKEN_HERE";
const token = process.env.TOKEN || 'YOUR_TOKEN_HERE';
if (token === "") {
console.log(new Error("Please set the TOKEN environment variable"));
if (token === '') {
console.log(new Error('Please set the TOKEN environment variable'));
}
const intents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages;
const session = new Session({ token, intents });
// Command prefix
const PREFIX = ">";
const PREFIX = '>';
session.on("ready", (data) => {
console.log("Ready! Let's start chatting!");
console.log("Connected as: " + data.user.username);
session.on('ready', (data) => {
console.log('Ready! Let\'s start chatting!');
console.log('Connected as: ' + data.user.username);
});
session.on("messageCreate", (message) => {
session.on('messageCreate', (message) => {
if (message.author?.bot || !message.content.startsWith(PREFIX)) {
return;
}
@ -36,8 +36,8 @@ session.on("messageCreate", (message) => {
const args = message.content.substring(PREFIX.length).trim().split(/\s+/gm);
const name = args.shift()?.toLowerCase();
if (name === "ping") {
message.reply({ content: "pong!" });
if (name === 'ping') {
message.reply({ content: 'pong!' });
}
});

View File

@ -4,31 +4,31 @@
// process for get the token
/** @type {NodeJS.Process} process */
const process = require("node:process");
const process = require('node:process');
// Session for create a new bot and intents
const { Session, GatewayIntents } = require("@oasisjs/biscuit");
const { Session, GatewayIntents } = require('@oasisjs/biscuit');
// Discord bot token
/** @type {string} token */
const token = process.env.TOKEN || "YOUR_TOKEN_HERE";
const token = process.env.TOKEN || 'YOUR_TOKEN_HERE';
if (token === "") {
return new Error("Please set the TOKEN environment variable");
if (token === '') {
return new Error('Please set the TOKEN environment variable');
}
const intents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages;
const session = new Session({ token, intents });
// Command prefix
const PREFIX = ">";
const PREFIX = '>';
session.on("ready", (data) => {
console.log("Ready! Let's start chatting!");
console.log("Connected as: " + data.user.username);
session.on('ready', (data) => {
console.log('Ready! Let\'s start chatting!');
console.log('Connected as: ' + data.user.username);
});
session.on("messageCreate", (message) => {
session.on('messageCreate', (message) => {
if (message.author?.bot || !message.content.startsWith(PREFIX)) {
return;
}
@ -36,8 +36,8 @@ session.on("messageCreate", (message) => {
const args = message.content.substring(PREFIX.length).trim().split(/\s+/gm);
const name = args.shift()?.toLowerCase();
if (name === "ping") {
message.reply({ content: "pong!" });
if (name === 'ping') {
message.reply({ content: 'pong!' });
}
});

View File

@ -1,47 +1,47 @@
import "https://deno.land/std@0.146.0/dotenv/load.ts";
import 'https://deno.land/std@0.146.0/dotenv/load.ts';
import {
CreateApplicationCommand,
GatewayIntents,
InteractionResponseTypes,
Session,
} from "https://deno.land/x/biscuit/mod.ts";
} from 'https://deno.land/x/biscuit/mod.ts';
const token = Deno.env.get("TOKEN") ?? Deno.args[0];
const token = Deno.env.get('TOKEN') ?? Deno.args[0];
if (!token) {
throw new Error("Please provide a token");
throw new Error('Please provide a token');
}
const intents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages;
const session = new Session({ token, intents });
const command: CreateApplicationCommand = {
name: "ping",
description: "Replies with pong!",
name: 'ping',
description: 'Replies with pong!',
};
session.on("ready", async (payload) => {
console.log("Logged in as:", payload.user.username);
console.log("Creating the application commands...");
session.on('ready', async (payload) => {
console.log('Logged in as:', payload.user.username);
console.log('Creating the application commands...');
// create command
try {
await session.createApplicationCommand(command);
console.log("Done!");
console.log('Done!');
} catch (err) {
console.error(err);
}
});
// Follow interaction event
session.on("interactionCreate", (interaction) => {
session.on('interactionCreate', (interaction) => {
if (!interaction.isCommand()) {
return;
}
if (interaction.commandName === "ping") {
if (interaction.commandName === 'ping') {
interaction.respond({
type: InteractionResponseTypes.ChannelMessageWithSource,
data: { content: "pong!" },
data: { content: 'pong!' },
});
}
});

View File

@ -1,17 +1,17 @@
// Biscuit Discord library showcase
import Biscuit, { GatewayIntents } from "https://deno.land/x/biscuit/mod.ts";
import Biscuit, { GatewayIntents } from 'https://deno.land/x/biscuit/mod.ts';
const intents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages;
const session = new Biscuit({ token: Deno.args[0], intents });
session.on("ready", ({ user }) => {
console.log("Logged in as: %s!\nUse !ping to get a reply", user.username);
session.on('ready', ({ user }) => {
console.log('Logged in as: %s!\nUse !ping to get a reply', user.username);
});
session.on("messageCreate", (message) => {
if (message.content.startsWith("!ping")) {
message.reply({ content: "pong!" });
session.on('messageCreate', (message) => {
if (message.content.startsWith('!ping')) {
message.reply({ content: 'pong!' });
}
});

10
mod.ts
View File

@ -1,8 +1,8 @@
import Session from "./packages/biscuit/mod.ts";
import Session from './packages/biscuit/mod.ts';
export default Session;
export * from "./packages/biscuit/mod.ts";
export * from "./packages/discordeno/mod.ts";
export * from "./packages/cache/mod.ts";
export { default as enableCache } from "./packages/cache/mod.ts";
export * from './packages/biscuit/mod.ts';
export * from './packages/discordeno/mod.ts';
export * from './packages/cache/mod.ts';
export { default as enableCache } from './packages/cache/mod.ts';

View File

@ -37,34 +37,34 @@ import type {
DiscordTypingStart,
DiscordUser,
DiscordWebhookUpdate,
} from "../discordeno/mod.ts";
} from '../discordeno/mod.ts';
import type { Snowflake } from "./Snowflake.ts";
import type { Session } from "./Session.ts";
import type { Interaction } from "./structures/interactions/InteractionFactory.ts";
import type { Snowflake } from './Snowflake.ts';
import type { Session } from './Session.ts';
import type { Interaction } from './structures/interactions/InteractionFactory.ts';
import { AutoModerationRule } from "./structures/AutoModerationRule.ts";
import { AutoModerationExecution } from "./structures/AutoModerationExecution.ts";
import { type Channel, ChannelFactory, GuildChannel, ThreadChannel } from "./structures/channels.ts";
import { type DiscordStageInstanceB, StageInstance } from "./structures/StageInstance.ts";
import { ScheduledEvent } from "./structures/GuildScheduledEvent.ts";
import { Presence } from "./structures/Presence.ts";
import { AutoModerationRule } from './structures/AutoModerationRule.ts';
import { AutoModerationExecution } from './structures/AutoModerationExecution.ts';
import { type Channel, ChannelFactory, GuildChannel, ThreadChannel } from './structures/channels.ts';
import { type DiscordStageInstanceB, StageInstance } from './structures/StageInstance.ts';
import { ScheduledEvent } from './structures/GuildScheduledEvent.ts';
import { Presence } from './structures/Presence.ts';
import ThreadMember from "./structures/ThreadMember.ts";
import Member from "./structures/Member.ts";
import Message from "./structures/Message.ts";
import User from "./structures/User.ts";
import Integration from "./structures/Integration.ts";
import { Guild } from "./structures/guilds.ts";
import InteractionFactory from "./structures/interactions/InteractionFactory.ts";
import { InviteCreate, NewInviteCreate } from "./structures/Invite.ts";
import ThreadMember from './structures/ThreadMember.ts';
import Member from './structures/Member.ts';
import Message from './structures/Message.ts';
import User from './structures/User.ts';
import Integration from './structures/Integration.ts';
import { Guild } from './structures/guilds.ts';
import InteractionFactory from './structures/interactions/InteractionFactory.ts';
import { InviteCreate, NewInviteCreate } from './structures/Invite.ts';
import {
MessageReactionAdd,
MessageReactionRemove,
MessageReactionRemoveAll,
MessageReactionRemoveEmoji,
NewMessageReactionAdd,
} from "./structures/MessageReaction.ts";
} from './structures/MessageReaction.ts';
export type RawHandler<T> = (...args: [Session, number, T]) => void;
export type Handler<T extends [obj?: unknown, ddy?: unknown]> = (...args: T) => unknown;
@ -72,11 +72,11 @@ export type Handler<T extends [obj?: unknown, ddy?: unknown]> = (...args: T) =>
export const READY: RawHandler<DiscordReady> = (session, shardId, payload) => {
session.applicationId = payload.application.id;
session.botId = payload.user.id;
session.emit("ready", { ...payload, user: new User(session, payload.user) }, shardId);
session.emit('ready', { ...payload, user: new User(session, payload.user) }, shardId);
};
export const MESSAGE_CREATE: RawHandler<DiscordMessage> = (session, _shardId, message) => {
session.emit("messageCreate", new Message(session, message));
session.emit('messageCreate', new Message(session, message));
};
export const MESSAGE_UPDATE: RawHandler<DiscordMessage> = (session, _shardId, new_message) => {
@ -95,63 +95,63 @@ export const MESSAGE_UPDATE: RawHandler<DiscordMessage> = (session, _shardId, ne
// we aknowledge people that their callback could be partial but giving them all functions of Message
Object.setPrototypeOf(message, Message.prototype);
session.emit("messageUpdate", message);
session.emit('messageUpdate', message);
return;
}
session.emit("messageUpdate", new Message(session, new_message));
session.emit('messageUpdate', new Message(session, new_message));
};
export const MESSAGE_DELETE: RawHandler<DiscordMessageDelete> = (session, _shardId, { id, channel_id, guild_id }) => {
session.emit("messageDelete", { id, channelId: channel_id, guildId: guild_id });
session.emit('messageDelete', { id, channelId: channel_id, guildId: guild_id });
};
export const GUILD_CREATE: RawHandler<DiscordGuild> = (session, _shardId, guild) => {
session.emit("guildCreate", new Guild(session, guild));
session.emit('guildCreate', new Guild(session, guild));
};
export const GUILD_DELETE: RawHandler<DiscordGuild> = (session, _shardId, guild) => {
session.emit("guildDelete", { id: guild.id, unavailable: true });
session.emit('guildDelete', { id: guild.id, unavailable: true });
};
export const GUILD_MEMBER_ADD: RawHandler<DiscordGuildMemberAdd> = (session, _shardId, member) => {
session.emit("guildMemberAdd", new Member(session, member, member.guild_id));
session.emit('guildMemberAdd', new Member(session, member, member.guild_id));
};
export const GUILD_MEMBER_UPDATE: RawHandler<DiscordGuildMemberUpdate> = (session, _shardId, member) => {
session.emit("guildMemberUpdate", new Member(session, member, member.guild_id));
session.emit('guildMemberUpdate', new Member(session, member, member.guild_id));
};
export const GUILD_MEMBER_REMOVE: RawHandler<DiscordGuildMemberRemove> = (session, _shardId, member) => {
session.emit("guildMemberRemove", new User(session, member.user), member.guild_id);
session.emit('guildMemberRemove', new User(session, member.user), member.guild_id);
};
export const GUILD_BAN_ADD: RawHandler<DiscordGuildBanAddRemove> = (session, _shardId, data) => {
session.emit("guildBanAdd", { guildId: data.guild_id, user: data.user });
session.emit('guildBanAdd', { guildId: data.guild_id, user: data.user });
};
export const GUILD_BAN_REMOVE: RawHandler<DiscordGuildBanAddRemove> = (session, _shardId, data) => {
session.emit("guildBanRemove", { guildId: data.guild_id, user: data.user });
session.emit('guildBanRemove', { guildId: data.guild_id, user: data.user });
};
export const GUILD_EMOJIS_UPDATE: RawHandler<DiscordGuildEmojisUpdate> = (session, _shardId, data) => {
session.emit("guildEmojisUpdate", { guildId: data.guild_id, emojis: data.emojis });
session.emit('guildEmojisUpdate', { guildId: data.guild_id, emojis: data.emojis });
};
export const GUILD_ROLE_CREATE: RawHandler<DiscordGuildRoleCreate> = (session, _shardId, data) => {
session.emit("guildRoleCreate", { guildId: data.guild_id, role: data.role });
session.emit('guildRoleCreate', { guildId: data.guild_id, role: data.role });
};
export const GUILD_ROLE_UPDATE: RawHandler<DiscordGuildRoleUpdate> = (session, _shardId, data) => {
session.emit("guildRoleUpdate", { guildId: data.guild_id, role: data.role });
session.emit('guildRoleUpdate', { guildId: data.guild_id, role: data.role });
};
export const GUILD_ROLE_DELETE: RawHandler<DiscordGuildRoleDelete> = (session, _shardId, data) => {
session.emit("guildRoleDelete", { guildId: data.guild_id, roleId: data.role_id });
session.emit('guildRoleDelete', { guildId: data.guild_id, roleId: data.role_id });
};
export const TYPING_START: RawHandler<DiscordTypingStart> = (session, _shardId, payload) => {
session.emit("typingStart", {
session.emit('typingStart', {
channelId: payload.channel_id,
guildId: payload.guild_id ? payload.guild_id : undefined,
userId: payload.user_id,
@ -163,43 +163,43 @@ export const TYPING_START: RawHandler<DiscordTypingStart> = (session, _shardId,
};
export const INTERACTION_CREATE: RawHandler<DiscordInteraction> = (session, _shardId, interaction) => {
session.emit("interactionCreate", InteractionFactory.from(session, interaction));
session.emit('interactionCreate', InteractionFactory.from(session, interaction));
};
export const CHANNEL_CREATE: RawHandler<DiscordChannel> = (session, _shardId, channel) => {
session.emit("channelCreate", ChannelFactory.from(session, channel));
session.emit('channelCreate', ChannelFactory.from(session, channel));
};
export const CHANNEL_UPDATE: RawHandler<DiscordChannel> = (session, _shardId, channel) => {
session.emit("channelUpdate", ChannelFactory.from(session, channel));
session.emit('channelUpdate', ChannelFactory.from(session, channel));
};
export const CHANNEL_DELETE: RawHandler<DiscordChannel> = (session, _shardId, channel) => {
if (!channel.guild_id) return;
session.emit("channelDelete", new GuildChannel(session, channel, channel.guild_id));
session.emit('channelDelete', new GuildChannel(session, channel, channel.guild_id));
};
export const THREAD_CREATE: RawHandler<DiscordChannel> = (session, _shardId, channel) => {
if (!channel.guild_id) return;
session.emit("threadCreate", new ThreadChannel(session, channel, channel.guild_id));
session.emit('threadCreate', new ThreadChannel(session, channel, channel.guild_id));
};
export const THREAD_UPDATE: RawHandler<DiscordChannel> = (session, _shardId, channel) => {
if (!channel.guild_id) return;
session.emit("threadUpdate", new ThreadChannel(session, channel, channel.guild_id));
session.emit('threadUpdate', new ThreadChannel(session, channel, channel.guild_id));
};
export const THREAD_DELETE: RawHandler<DiscordChannel> = (session, _shardId, channel) => {
if (!channel.guild_id) return;
session.emit("threadDelete", new ThreadChannel(session, channel, channel.guild_id));
session.emit('threadDelete', new ThreadChannel(session, channel, channel.guild_id));
};
export const THREAD_MEMBER_UPDATE: RawHandler<DiscordThreadMemberUpdate> = (session, _shardId, payload) => {
session.emit("threadMemberUpdate", {
session.emit('threadMemberUpdate', {
guildId: payload.guild_id,
id: payload.id,
userId: payload.user_id,
@ -209,7 +209,7 @@ export const THREAD_MEMBER_UPDATE: RawHandler<DiscordThreadMemberUpdate> = (sess
};
export const THREAD_MEMBERS_UPDATE: RawHandler<DiscordThreadMembersUpdate> = (session, _shardId, payload) => {
session.emit("threadMembersUpdate", {
session.emit('threadMembersUpdate', {
memberCount: payload.member_count,
addedMembers: payload.added_members
? payload.added_members.map((tm) => new ThreadMember(session, tm))
@ -221,7 +221,7 @@ export const THREAD_MEMBERS_UPDATE: RawHandler<DiscordThreadMembersUpdate> = (se
};
export const THREAD_LIST_SYNC: RawHandler<DiscordThreadListSync> = (session, _shardId, payload) => {
session.emit("threadListSync", {
session.emit('threadListSync', {
guildId: payload.guild_id,
channelIds: payload.channel_ids ?? [],
threads: payload.threads.map((channel) => new ThreadChannel(session, channel, payload.guild_id)),
@ -230,7 +230,7 @@ export const THREAD_LIST_SYNC: RawHandler<DiscordThreadListSync> = (session, _sh
};
export const CHANNEL_PINS_UPDATE: RawHandler<DiscordChannelPinsUpdate> = (session, _shardId, payload) => {
session.emit("channelPinsUpdate", {
session.emit('channelPinsUpdate', {
guildId: payload.guild_id,
channelId: payload.channel_id,
lastPinTimestamp: payload.last_pin_timestamp ? Date.parse(payload.last_pin_timestamp) : undefined,
@ -238,15 +238,15 @@ export const CHANNEL_PINS_UPDATE: RawHandler<DiscordChannelPinsUpdate> = (sessio
};
export const USER_UPDATE: RawHandler<DiscordUser> = (session, _shardId, payload) => {
session.emit("userUpdate", new User(session, payload));
session.emit('userUpdate', new User(session, payload));
};
export const PRESENCE_UPDATE: RawHandler<DiscordPresenceUpdate> = (session, _shardId, payload) => {
session.emit("presenceUpdate", new Presence(session, payload));
session.emit('presenceUpdate', new Presence(session, payload));
};
export const WEBHOOKS_UPDATE: RawHandler<DiscordWebhookUpdate> = (session, _shardId, webhook) => {
session.emit("webhooksUpdate", { guildId: webhook.guild_id, channelId: webhook.channel_id });
session.emit('webhooksUpdate', { guildId: webhook.guild_id, channelId: webhook.channel_id });
};
export const INTEGRATION_CREATE: RawHandler<DiscordIntegration & { guildId?: Snowflake }> = (
@ -254,7 +254,7 @@ export const INTEGRATION_CREATE: RawHandler<DiscordIntegration & { guildId?: Sno
_shardId,
payload,
) => {
session.emit("integrationCreate", new Integration(session, payload));
session.emit('integrationCreate', new Integration(session, payload));
};
export const INTEGRATION_UPDATE: RawHandler<DiscordIntegration & { guildId?: Snowflake }> = (
@ -262,11 +262,11 @@ export const INTEGRATION_UPDATE: RawHandler<DiscordIntegration & { guildId?: Sno
_shardId,
payload,
) => {
session.emit("integrationCreate", new Integration(session, payload));
session.emit('integrationCreate', new Integration(session, payload));
};
export const INTEGRATION_DELETE: RawHandler<DiscordIntegrationDelete> = (session, _shardId, payload) => {
session.emit("integrationDelete", {
session.emit('integrationDelete', {
id: payload.id,
guildId: payload.guild_id,
applicationId: payload.application_id,
@ -274,15 +274,15 @@ export const INTEGRATION_DELETE: RawHandler<DiscordIntegrationDelete> = (session
};
export const AUTO_MODERATION_RULE_CREATE: RawHandler<DiscordAutoModerationRule> = (session, _shardId, payload) => {
session.emit("autoModerationRuleCreate", new AutoModerationRule(session, payload));
session.emit('autoModerationRuleCreate', new AutoModerationRule(session, payload));
};
export const AUTO_MODERATION_RULE_UPDATE: RawHandler<DiscordAutoModerationRule> = (session, _shardId, payload) => {
session.emit("autoModerationRuleUpdate", new AutoModerationRule(session, payload));
session.emit('autoModerationRuleUpdate', new AutoModerationRule(session, payload));
};
export const AUTO_MODERATION_RULE_DELETE: RawHandler<DiscordAutoModerationRule> = (session, _shardId, payload) => {
session.emit("autoModerationRuleDelete", new AutoModerationRule(session, payload));
session.emit('autoModerationRuleDelete', new AutoModerationRule(session, payload));
};
export const AUTO_MODERATION_ACTION_EXECUTE: RawHandler<DiscordAutoModerationActionExecution> = (
@ -290,15 +290,15 @@ export const AUTO_MODERATION_ACTION_EXECUTE: RawHandler<DiscordAutoModerationAct
_shardId,
payload,
) => {
session.emit("autoModerationActionExecution", new AutoModerationExecution(session, payload));
session.emit('autoModerationActionExecution', new AutoModerationExecution(session, payload));
};
export const MESSAGE_REACTION_ADD: RawHandler<DiscordMessageReactionAdd> = (session, _shardId, reaction) => {
session.emit("messageReactionAdd", NewMessageReactionAdd(session, reaction));
session.emit('messageReactionAdd', NewMessageReactionAdd(session, reaction));
};
export const MESSAGE_REACTION_REMOVE: RawHandler<DiscordMessageReactionRemove> = (session, _shardId, reaction) => {
session.emit("messageReactionRemove", NewMessageReactionAdd(session, reaction));
session.emit('messageReactionRemove', NewMessageReactionAdd(session, reaction));
};
export const MESSAGE_REACTION_REMOVE_ALL: RawHandler<DiscordMessageReactionRemoveAll> = (
@ -306,7 +306,7 @@ export const MESSAGE_REACTION_REMOVE_ALL: RawHandler<DiscordMessageReactionRemov
_shardId,
reaction,
) => {
session.emit("messageReactionRemoveAll", NewMessageReactionAdd(session, reaction as DiscordMessageReactionAdd));
session.emit('messageReactionRemoveAll', NewMessageReactionAdd(session, reaction as DiscordMessageReactionAdd));
};
export const MESSAGE_REACTION_REMOVE_EMOJI: RawHandler<DiscordMessageReactionRemoveEmoji> = (
@ -314,39 +314,39 @@ export const MESSAGE_REACTION_REMOVE_EMOJI: RawHandler<DiscordMessageReactionRem
_shardId,
reaction,
) => {
session.emit("messageReactionRemoveEmoji", NewMessageReactionAdd(session, reaction as DiscordMessageReactionAdd));
session.emit('messageReactionRemoveEmoji', NewMessageReactionAdd(session, reaction as DiscordMessageReactionAdd));
};
export const INVITE_CREATE: RawHandler<DiscordInviteCreate> = (session, _shardId, invite) => {
session.emit("inviteCreate", NewInviteCreate(session, invite));
session.emit('inviteCreate', NewInviteCreate(session, invite));
};
export const INVITE_DELETE: RawHandler<DiscordInviteDelete> = (session, _shardId, data) => {
session.emit("inviteDelete", { channelId: data.channel_id, guildId: data.guild_id, code: data.code });
session.emit('inviteDelete', { channelId: data.channel_id, guildId: data.guild_id, code: data.code });
};
export const STAGE_INSTANCE_CREATE: RawHandler<DiscordStageInstanceB> = (session, _shardId, payload) => {
session.emit("stageInstanceCreate", new StageInstance(session, payload));
session.emit('stageInstanceCreate', new StageInstance(session, payload));
};
export const STAGE_INSTANCE_UPDATE: RawHandler<DiscordStageInstanceB> = (session, _shardId, payload) => {
session.emit("stageInstanceUpdate", new StageInstance(session, payload));
session.emit('stageInstanceUpdate', new StageInstance(session, payload));
};
export const STAGE_INSTANCE_DELETE: RawHandler<DiscordStageInstanceB> = (session, _shardId, payload) => {
session.emit("stageInstanceDelete", new StageInstance(session, payload));
session.emit('stageInstanceDelete', new StageInstance(session, payload));
};
export const GUILD_SCHEDULED_EVENT_CREATE: RawHandler<DiscordScheduledEvent> = (session, _shardId, payload) => {
session.emit("guildScheduledEventCreate", new ScheduledEvent(session, payload));
session.emit('guildScheduledEventCreate', new ScheduledEvent(session, payload));
};
export const GUILD_SCHEDULED_EVENT_UPDATE: RawHandler<DiscordScheduledEvent> = (session, _shardId, payload) => {
session.emit("guildScheduledEventUpdate", new ScheduledEvent(session, payload));
session.emit('guildScheduledEventUpdate', new ScheduledEvent(session, payload));
};
export const GUILD_SCHEDULED_EVENT_DELETE: RawHandler<DiscordScheduledEvent> = (session, _shardId, payload) => {
session.emit("guildScheduledEventDelete", new ScheduledEvent(session, payload));
session.emit('guildScheduledEventDelete', new ScheduledEvent(session, payload));
};
export const GUILD_SCHEDULED_EVENT_USER_ADD: RawHandler<DiscordScheduledEventUserAdd> = (
@ -354,7 +354,7 @@ export const GUILD_SCHEDULED_EVENT_USER_ADD: RawHandler<DiscordScheduledEventUse
_shardId,
payload,
) => {
session.emit("guildScheduledEventUserAdd", {
session.emit('guildScheduledEventUserAdd', {
scheduledEventId: payload.guild_scheduled_event_id,
userId: payload.user_id,
guildId: payload.guild_id,
@ -366,7 +366,7 @@ export const GUILD_SCHEDULED_EVENT_USER_REMOVE: RawHandler<DiscordScheduledEvent
_shardId,
payload,
) => {
session.emit("guildScheduledEventUserRemove", {
session.emit('guildScheduledEventUserRemove', {
scheduledEventId: payload.guild_scheduled_event_id,
userId: payload.user_id,
guildId: payload.guild_id,
@ -374,10 +374,10 @@ export const GUILD_SCHEDULED_EVENT_USER_REMOVE: RawHandler<DiscordScheduledEvent
};
export const raw: RawHandler<unknown> = (session, shardId, data) => {
session.emit("raw", data as { t: string; d: unknown }, shardId);
session.emit('raw', data as { t: string; d: unknown }, shardId);
};
export interface Ready extends Omit<DiscordReady, "user"> {
export interface Ready extends Omit<DiscordReady, 'user'> {
user: User;
}

View File

@ -1,12 +1,12 @@
import type { Snowflake } from "./Snowflake.ts";
import { baseEndpoints as Endpoints } from "../discordeno/mod.ts";
import type { Snowflake } from './Snowflake.ts';
import { baseEndpoints as Endpoints } from '../discordeno/mod.ts';
export function USER_AVATAR(userId: Snowflake, icon: string): string {
return `${Endpoints.CDN_URL}/avatars/${userId}/${icon}`;
}
export function EMOJI_URL(id: Snowflake, animated = false): string {
return `https://cdn.discordapp.com/emojis/${id}.${animated ? "gif" : "png"}`;
return `https://cdn.discordapp.com/emojis/${id}.${animated ? 'gif' : 'png'}`;
}
export function USER_DEFAULT_AVATAR(

View File

@ -1,15 +1,15 @@
import type { Snowflake } from "./Snowflake.ts";
import type { Snowflake } from './Snowflake.ts';
// cdn endpoints
export * from "./Cdn.ts";
export * from './Cdn.ts';
export function USER(userId?: Snowflake): string {
if (!userId) return "/users/@me";
if (!userId) return '/users/@me';
return `/users/${userId}`;
}
export function GATEWAY_BOT(): string {
return "/gateway/bot";
return '/gateway/bot';
}
export interface GetMessagesOptions {

View File

@ -9,29 +9,29 @@ import type {
GatewayBot,
GatewayIntents,
Localization,
} from "../discordeno/mod.ts";
} from '../discordeno/mod.ts';
import type { DiscordGatewayPayload, Shard } from "../discordeno/mod.ts";
import type { Events } from "./Actions.ts";
import type { PermissionResolvable } from "./structures/Permissions.ts";
import type { Activities, StatusTypes } from "./structures/Presence.ts";
import type { DiscordGatewayPayload, Shard } from '../discordeno/mod.ts';
import type { Events } from './Actions.ts';
import type { PermissionResolvable } from './structures/Permissions.ts';
import type { Activities, StatusTypes } from './structures/Presence.ts';
import { Permissions } from "./structures/Permissions.ts";
import { Snowflake } from "./Snowflake.ts";
import { EventEmitter } from "./util/EventEmmiter.ts";
import { Permissions } from './structures/Permissions.ts';
import { Snowflake } from './Snowflake.ts';
import { EventEmitter } from './util/EventEmmiter.ts';
import {
ApplicationCommandTypes,
createGatewayManager,
createRestManager,
GatewayOpcodes,
getBotIdFromToken,
} from "../discordeno/mod.ts";
} from '../discordeno/mod.ts';
import User from "./structures/User.ts";
import { urlToBase64 } from "./util/urlToBase64.ts";
import User from './structures/User.ts';
import { urlToBase64 } from './util/urlToBase64.ts';
import * as Routes from "./Routes.ts";
import * as Actions from "./Actions.ts";
import * as Routes from './Routes.ts';
import * as Actions from './Actions.ts';
export type DiscordRawEventHandler = (shard: Shard, data: DiscordGatewayPayload) => unknown;
@ -54,7 +54,7 @@ export interface CreateApplicationCommand {
/**
* @link https://discord.com/developers/docs/interactions/application-commands#endpoints-json-params
*/
export interface CreateContextApplicationCommand extends Omit<CreateApplicationCommand, "options"> {
export interface CreateContextApplicationCommand extends Omit<CreateApplicationCommand, 'options'> {
type: ApplicationCommandTypes.Message | ApplicationCommandTypes.User;
}
@ -164,7 +164,7 @@ export class Session extends EventEmitter {
token: this.options.token,
debug: (text) => {
// TODO: set this using the event emitter
super.rawListeners("debug")?.forEach((fn) => fn(text));
super.rawListeners('debug')?.forEach((fn) => fn(text));
},
secretKey: this.options.rest?.secretKey ?? undefined,
});
@ -203,7 +203,7 @@ export class Session extends EventEmitter {
async editProfile(nick?: string, avatarURL?: string | null): Promise<User> {
const avatar = avatarURL ? await urlToBase64(avatarURL) : avatarURL;
const user = await this.rest.runMethod<DiscordUser>(this.rest, "PATCH", Routes.USER(), {
const user = await this.rest.runMethod<DiscordUser>(this.rest, 'PATCH', Routes.USER(), {
username: nick,
avatar: avatar,
});
@ -265,7 +265,7 @@ export class Session extends EventEmitter {
}
async fetchUser(id: Snowflake): Promise<User | undefined> {
const user: DiscordUser = await this.rest.runMethod<DiscordUser>(this.rest, "GET", Routes.USER(id));
const user: DiscordUser = await this.rest.runMethod<DiscordUser>(this.rest, 'GET', Routes.USER(id));
if (!user.id) return;
@ -278,7 +278,7 @@ export class Session extends EventEmitter {
): Promise<DiscordApplicationCommand> {
return this.rest.runMethod<DiscordApplicationCommand>(
this.rest,
"POST",
'POST',
guildId
? Routes.GUILD_APPLICATION_COMMANDS(this.applicationId, guildId)
: Routes.APPLICATION_COMMANDS(this.applicationId),
@ -306,7 +306,7 @@ export class Session extends EventEmitter {
deleteApplicationCommand(id: Snowflake, guildId?: Snowflake): Promise<undefined> {
return this.rest.runMethod<undefined>(
this.rest,
"DELETE",
'DELETE',
guildId
? Routes.GUILD_APPLICATION_COMMANDS(this.applicationId, guildId, id)
: Routes.APPLICATION_COMMANDS(this.applicationId, id),
@ -321,7 +321,7 @@ export class Session extends EventEmitter {
): Promise<DiscordGuildApplicationCommandPermissions> {
return this.rest.runMethod<DiscordGuildApplicationCommandPermissions>(
this.rest,
"PUT",
'PUT',
Routes.GUILD_APPLICATION_COMMANDS_PERMISSIONS(this.applicationId, guildId, id),
{
permissions: options,
@ -335,7 +335,7 @@ export class Session extends EventEmitter {
fetchApplicationCommand(id: Snowflake, options?: GetApplicationCommand): Promise<DiscordApplicationCommand> {
return this.rest.runMethod<DiscordApplicationCommand>(
this.rest,
"GET",
'GET',
options?.guildId
? Routes.GUILD_APPLICATION_COMMANDS_LOCALIZATIONS(
this.applicationId,
@ -350,7 +350,7 @@ export class Session extends EventEmitter {
fetchApplicationCommandPermissions(guildId: Snowflake): Promise<DiscordGuildApplicationCommandPermissions[]> {
return this.rest.runMethod<DiscordGuildApplicationCommandPermissions[]>(
this.rest,
"GET",
'GET',
Routes.GUILD_APPLICATION_COMMANDS_PERMISSIONS(this.applicationId, guildId),
);
}
@ -361,7 +361,7 @@ export class Session extends EventEmitter {
): Promise<DiscordGuildApplicationCommandPermissions> {
return this.rest.runMethod<DiscordGuildApplicationCommandPermissions>(
this.rest,
"GET",
'GET',
Routes.GUILD_APPLICATION_COMMANDS_PERMISSIONS(this.applicationId, guildId, id),
);
}
@ -373,7 +373,7 @@ export class Session extends EventEmitter {
): Promise<DiscordApplicationCommand> {
return this.rest.runMethod<DiscordApplicationCommand>(
this.rest,
"PATCH",
'PATCH',
guildId
? Routes.GUILD_APPLICATION_COMMANDS(this.applicationId, guildId)
: Routes.APPLICATION_COMMANDS(this.applicationId, id),
@ -397,7 +397,7 @@ export class Session extends EventEmitter {
): Promise<DiscordApplicationCommand[]> {
return this.rest.runMethod<DiscordApplicationCommand[]>(
this.rest,
"PUT",
'PUT',
guildId
? Routes.GUILD_APPLICATION_COMMANDS(this.applicationId, guildId)
: Routes.APPLICATION_COMMANDS(this.applicationId),
@ -420,7 +420,7 @@ export class Session extends EventEmitter {
fetchCommands(guildId?: Snowflake): Promise<DiscordApplicationCommand[]> {
return this.rest.runMethod<DiscordApplicationCommand[]>(
this.rest,
"GET",
'GET',
guildId
? Routes.GUILD_APPLICATION_COMMANDS(this.applicationId, guildId)
: Routes.APPLICATION_COMMANDS(this.applicationId),
@ -433,7 +433,7 @@ export class Session extends EventEmitter {
}
async start(): Promise<void> {
const getGatewayBot = () => this.rest.runMethod<DiscordGetGatewayBot>(this.rest, "GET", Routes.GATEWAY_BOT());
const getGatewayBot = () => this.rest.runMethod<DiscordGetGatewayBot>(this.rest, 'GET', Routes.GATEWAY_BOT());
// check if is empty
if (!Object.keys(this.options.gateway?.data ?? {}).length) {

View File

@ -1,6 +1,6 @@
import type { ButtonBuilder, InputTextBuilder, SelectMenuBuilder } from "./mod.ts";
import type { Permissions } from "./structures/Permissions.ts";
import type { Snowflake } from "./Snowflake.ts";
import type { ButtonBuilder, InputTextBuilder, SelectMenuBuilder } from './mod.ts';
import type { Permissions } from './structures/Permissions.ts';
import type { Snowflake } from './Snowflake.ts';
/*
* Represents a session's cache
@ -60,7 +60,7 @@ export interface PermissionsOverwrites {
/**
* @link https://discord.com/developers/docs/reference#image-formatting
*/
export type ImageFormat = "jpg" | "jpeg" | "png" | "webp" | "gif" | "json";
export type ImageFormat = 'jpg' | 'jpeg' | 'png' | 'webp' | 'gif' | 'json';
/**
* @link https://discord.com/developers/docs/reference#image-formatting
@ -72,17 +72,17 @@ export type ImageSize = 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096;
*/
export class Util {
static formatImageURL(url: string, size: ImageSize = 128, format?: ImageFormat) {
return `${url}.${format || (url.includes("/a_") ? "gif" : "jpg")}?size=${size}`;
return `${url}.${format || (url.includes('/a_') ? 'gif' : 'jpg')}?size=${size}`;
}
static iconHashToBigInt(hash: string) {
return BigInt("0x" + (hash.startsWith("a_") ? `a${hash.substring(2)}` : `b${hash}`));
return BigInt('0x' + (hash.startsWith('a_') ? `a${hash.substring(2)}` : `b${hash}`));
}
static iconBigintToHash(icon: bigint) {
const hash: string = icon.toString(16);
return hash.startsWith("a") ? `a_${hash.substring(1)}` : hash.substring(1);
return hash.startsWith('a') ? `a_${hash.substring(1)}` : hash.substring(1);
}
}

View File

@ -1,77 +1,77 @@
// structures
import { Session } from "./Session.ts";
import { Session } from './Session.ts';
export default Session;
export * from "./structures/Application.ts";
export * from "./structures/Attachment.ts";
export * from "./structures/AutoModerationExecution.ts";
export * from "./structures/AutoModerationRule.ts";
export * from "./structures/Base.ts";
export * from "./structures/Embed.ts";
export * from "./structures/Emoji.ts";
export * from "./structures/GuildEmoji.ts";
export * from "./structures/GuildScheduledEvent.ts";
export * from "./structures/Integration.ts";
export * from "./structures/Invite.ts";
export * from "./structures/Member.ts";
export * from "./structures/Message.ts";
export * from "./structures/MessageReaction.ts";
export * from "./structures/Permissions.ts";
export * from "./structures/Presence.ts";
export * from "./structures/Role.ts";
export * from "./structures/StageInstance.ts";
export * from "./structures/Sticker.ts";
export * from "./structures/ThreadMember.ts";
export * from "./structures/User.ts";
export * from "./structures/Webhook.ts";
export * from "./structures/WelcomeChannel.ts";
export * from "./structures/WelcomeScreen.ts";
export * from './structures/Application.ts';
export * from './structures/Attachment.ts';
export * from './structures/AutoModerationExecution.ts';
export * from './structures/AutoModerationRule.ts';
export * from './structures/Base.ts';
export * from './structures/Embed.ts';
export * from './structures/Emoji.ts';
export * from './structures/GuildEmoji.ts';
export * from './structures/GuildScheduledEvent.ts';
export * from './structures/Integration.ts';
export * from './structures/Invite.ts';
export * from './structures/Member.ts';
export * from './structures/Message.ts';
export * from './structures/MessageReaction.ts';
export * from './structures/Permissions.ts';
export * from './structures/Presence.ts';
export * from './structures/Role.ts';
export * from './structures/StageInstance.ts';
export * from './structures/Sticker.ts';
export * from './structures/ThreadMember.ts';
export * from './structures/User.ts';
export * from './structures/Webhook.ts';
export * from './structures/WelcomeChannel.ts';
export * from './structures/WelcomeScreen.ts';
// channels
export * from "./structures/channels.ts";
export * from './structures/channels.ts';
// components
export * from "./structures/components/ActionRowComponent.ts";
export * from "./structures/components/ButtonComponent.ts";
export * from "./structures/components/Component.ts";
export * from "./structures/components/LinkButtonComponent.ts";
export * from "./structures/components/SelectMenuComponent.ts";
export * from "./structures/components/TextInputComponent.ts";
export * from './structures/components/ActionRowComponent.ts';
export * from './structures/components/ButtonComponent.ts';
export * from './structures/components/Component.ts';
export * from './structures/components/LinkButtonComponent.ts';
export * from './structures/components/SelectMenuComponent.ts';
export * from './structures/components/TextInputComponent.ts';
// guilds
export * from "./structures/guilds.ts";
export * from './structures/guilds.ts';
// builders
export * from "./structures/builders/EmbedBuilder.ts";
export * from "./structures/builders/components/InputTextComponentBuilder.ts";
export * from "./structures/builders/components/MessageActionRow.ts";
export * from "./structures/builders/components/MessageButton.ts";
export * from "./structures/builders/components/MessageSelectMenu.ts";
export * from "./structures/builders/components/SelectMenuOptionBuilder.ts";
export * from "./structures/builders/slash/ApplicationCommand.ts";
export * from "./structures/builders/slash/ApplicationCommandOption.ts";
export * from './structures/builders/EmbedBuilder.ts';
export * from './structures/builders/components/InputTextComponentBuilder.ts';
export * from './structures/builders/components/MessageActionRow.ts';
export * from './structures/builders/components/MessageButton.ts';
export * from './structures/builders/components/MessageSelectMenu.ts';
export * from './structures/builders/components/SelectMenuOptionBuilder.ts';
export * from './structures/builders/slash/ApplicationCommand.ts';
export * from './structures/builders/slash/ApplicationCommandOption.ts';
// interactions
export * from "./structures/interactions/AutoCompleteInteraction.ts";
export * from "./structures/interactions/BaseInteraction.ts";
export * from "./structures/interactions/CommandInteraction.ts";
export * from "./structures/interactions/CommandInteractionOptionResolver.ts";
export * from "./structures/interactions/ComponentInteraction.ts";
export * from "./structures/interactions/InteractionFactory.ts";
export * from "./structures/interactions/ModalSubmitInteraction.ts";
export * from "./structures/interactions/PingInteraction.ts";
export * from './structures/interactions/AutoCompleteInteraction.ts';
export * from './structures/interactions/BaseInteraction.ts';
export * from './structures/interactions/CommandInteraction.ts';
export * from './structures/interactions/CommandInteractionOptionResolver.ts';
export * from './structures/interactions/ComponentInteraction.ts';
export * from './structures/interactions/InteractionFactory.ts';
export * from './structures/interactions/ModalSubmitInteraction.ts';
export * from './structures/interactions/PingInteraction.ts';
// etc
export * from "./Snowflake.ts";
export * from './Snowflake.ts';
// session
export * from "./Session.ts";
export * from './Session.ts';
// util
export * from "./Util.ts";
export * from "./util/urlToBase64.ts";
export * from "./util/EventEmmiter.ts";
export * from './Util.ts';
export * from './util/urlToBase64.ts';
export * from './util/EventEmmiter.ts';
// routes
export * as Routes from "./Routes.ts";
export * as Cdn from "./Cdn.ts";
export * as Routes from './Routes.ts';
export * as Cdn from './Cdn.ts';

View File

@ -1,16 +1,16 @@
import { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import {
DiscordApplication,
DiscordInstallParams,
DiscordTeam,
DiscordUser,
TeamMembershipStates,
} from "../../discordeno/mod.ts";
import User from "./User.ts";
} from '../../discordeno/mod.ts';
import User from './User.ts';
type SummaryDeprecated = "";
type SummaryDeprecated = '';
export interface Team {
/** a hash of the image of the team's icon */
@ -28,11 +28,11 @@ export interface Team {
export interface TeamMember {
/** the user's membership state on the team */
membershipState: TeamMembershipStates;
permissions: "*"[];
permissions: '*'[];
teamId: string;
user: Partial<User> & Pick<User, "avatarHash" | "discriminator" | "id" | "username">;
user: Partial<User> & Pick<User, 'avatarHash' | 'discriminator' | 'id' | 'username'>;
}
// NewTeam create a new Team object for discord applications
@ -69,7 +69,7 @@ export class Application implements Model {
this.termsOfServiceURL = data.terms_of_service_url;
this.privacyPolicyURL = data.privacy_policy_url;
this.owner = data.owner ? new User(session, data.owner as DiscordUser) : undefined;
this.summary = "";
this.summary = '';
this.verifyKey = data.verify_key;
this.team = data.team ? NewTeam(session, data.team) : undefined;
this.guildId = data.guild_id;

View File

@ -1,7 +1,7 @@
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import type { DiscordAttachment } from "../../discordeno/mod.ts";
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import type { DiscordAttachment } from '../../discordeno/mod.ts';
/**
* Represents an attachment

View File

@ -1,7 +1,7 @@
import { AutoModerationTriggerTypes, DiscordAutoModerationActionExecution } from "../../discordeno/mod.ts";
import type { Session } from "../Session.ts";
import type { Snowflake } from "../Snowflake.ts";
import { AutoModerationAction } from "./AutoModerationRule.ts";
import { AutoModerationTriggerTypes, DiscordAutoModerationActionExecution } from '../../discordeno/mod.ts';
import type { Session } from '../Session.ts';
import type { Snowflake } from '../Snowflake.ts';
import { AutoModerationAction } from './AutoModerationRule.ts';
export class AutoModerationExecution {
constructor(session: Session, data: DiscordAutoModerationActionExecution) {

View File

@ -4,10 +4,10 @@ import {
AutoModerationTriggerTypes,
DiscordAutoModerationRule,
DiscordAutoModerationRuleTriggerMetadataPresets,
} from "../../discordeno/mod.ts";
import { Model } from "./Base.ts";
import type { Session } from "../Session.ts";
import type { Snowflake } from "../Snowflake.ts";
} from '../../discordeno/mod.ts';
import { Model } from './Base.ts';
import type { Session } from '../Session.ts';
import type { Snowflake } from '../Snowflake.ts';
export interface AutoModerationRuleTriggerMetadata {
keywordFilter?: string[];

View File

@ -1,5 +1,5 @@
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
/**
* Represents a Discord data model

View File

@ -1,4 +1,4 @@
import type { DiscordEmbed, EmbedTypes } from "../../discordeno/mod.ts";
import type { DiscordEmbed, EmbedTypes } from '../../discordeno/mod.ts';
export interface Embed {
title?: string;

View File

@ -1,6 +1,6 @@
import type { Session } from "../Session.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { DiscordEmoji } from "../../discordeno/mod.ts";
import type { Session } from '../Session.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { DiscordEmoji } from '../../discordeno/mod.ts';
export class Emoji {
constructor(session: Session, data: DiscordEmoji) {

View File

@ -1,12 +1,12 @@
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import type { DiscordEmoji } from "../../discordeno/mod.ts";
import type { ModifyGuildEmoji } from "./guilds.ts";
import Guild from "./guilds.ts";
import Emoji from "./Emoji.ts";
import User from "./User.ts";
import * as Routes from "../Routes.ts";
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import type { DiscordEmoji } from '../../discordeno/mod.ts';
import type { ModifyGuildEmoji } from './guilds.ts';
import Guild from './guilds.ts';
import Emoji from './Emoji.ts';
import User from './User.ts';
import * as Routes from '../Routes.ts';
export class GuildEmoji extends Emoji implements Model {
constructor(session: Session, data: DiscordEmoji, guildId: Snowflake) {

View File

@ -1,14 +1,14 @@
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import { PrivacyLevels } from "./StageInstance.ts";
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import { PrivacyLevels } from './StageInstance.ts';
import type {
DiscordScheduledEvent,
DiscordScheduledEventEntityMetadata,
ScheduledEventEntityType,
ScheduledEventStatus,
} from "../../discordeno/mod.ts";
import User from "./User.ts";
} from '../../discordeno/mod.ts';
import User from './User.ts';
export class ScheduledEvent implements Model {
constructor(session: Session, data: DiscordScheduledEvent) {

View File

@ -1,8 +1,8 @@
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import type { DiscordIntegration, IntegrationExpireBehaviors } from "../../discordeno/mod.ts";
import User from "./User.ts";
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import type { DiscordIntegration, IntegrationExpireBehaviors } from '../../discordeno/mod.ts';
import User from './User.ts';
export interface IntegrationAccount {
id: Snowflake;
@ -58,7 +58,7 @@ export class Integration implements Model {
guildId?: Snowflake;
name: string;
type: "twitch" | "youtube" | "discord";
type: 'twitch' | 'youtube' | 'discord';
enabled?: boolean;
syncing?: boolean;
roleId?: string;

View File

@ -1,5 +1,5 @@
import type { Session } from "../Session.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from '../Session.ts';
import type { Snowflake } from '../Snowflake.ts';
import type {
DiscordApplication,
DiscordChannel,
@ -10,13 +10,13 @@ import type {
ScheduledEventEntityType,
ScheduledEventPrivacyLevel,
ScheduledEventStatus,
} from "../../discordeno/mod.ts";
import { TargetTypes } from "../../discordeno/mod.ts";
import { GuildChannel } from "./channels.ts";
import { Member } from "./Member.ts";
import { Guild, InviteGuild } from "./guilds.ts";
import User from "./User.ts";
import Application from "./Application.ts";
} from '../../discordeno/mod.ts';
import { TargetTypes } from '../../discordeno/mod.ts';
import { GuildChannel } from './channels.ts';
import { Member } from './Member.ts';
import { Guild, InviteGuild } from './guilds.ts';
import User from './User.ts';
import Application from './Application.ts';
export interface InviteStageInstance {
/** The members speaking in the Stage */
@ -101,7 +101,7 @@ export class Invite {
this.targetType = data.target_type;
if (data.channel) {
const guildId = (data.guild && data.guild?.id) ? data.guild.id : "";
const guildId = (data.guild && data.guild?.id) ? data.guild.id : '';
this.channel = new GuildChannel(session, data.channel as DiscordChannel, guildId);
}
@ -135,7 +135,7 @@ export class Invite {
}
if (data.stage_instance) {
const guildId = (data.guild && data.guild?.id) ? data.guild.id : "";
const guildId = (data.guild && data.guild?.id) ? data.guild.id : '';
this.stageInstance = {
members: data.stage_instance.members.map((m) =>
new Member(session, m as DiscordMemberWithUser, guildId)

View File

@ -1,13 +1,13 @@
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import type { DiscordMemberWithUser } from "../../discordeno/mod.ts";
import type { ImageFormat, ImageSize } from "../Util.ts";
import type { CreateGuildBan, ModifyGuildMember } from "./guilds.ts";
import { Guild } from "./guilds.ts";
import Util from "../Util.ts";
import User from "./User.ts";
import * as Routes from "../Routes.ts";
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import type { DiscordMemberWithUser } from '../../discordeno/mod.ts';
import type { ImageFormat, ImageSize } from '../Util.ts';
import type { CreateGuildBan, ModifyGuildMember } from './guilds.ts';
import { Guild } from './guilds.ts';
import Util from '../Util.ts';
import User from './User.ts';
import * as Routes from '../Routes.ts';
/**
* @link https://discord.com/developers/docs/resources/guild#guild-member-object

View File

@ -1,5 +1,5 @@
import type { Model } from "./Base.ts";
import type { Session } from "../Session.ts";
import type { Model } from './Base.ts';
import type { Session } from '../Session.ts';
import type {
AllowedMentionsTypes,
DiscordEmbed,
@ -9,24 +9,24 @@ import type {
FileContent,
MessageActivityTypes,
MessageTypes,
} from "../../discordeno/mod.ts";
import type { Channel } from "./channels.ts";
import type { Component } from "./components/Component.ts";
import type { GetReactions } from "../Routes.ts";
import type { MessageInteraction } from "./interactions/InteractionFactory.ts";
import { MessageFlags } from "../Util.ts";
import { Snowflake } from "../Snowflake.ts";
import { ChannelFactory, ThreadChannel } from "./channels.ts";
import Util from "../Util.ts";
import User from "./User.ts";
import Member from "./Member.ts";
import Attachment from "./Attachment.ts";
import ComponentFactory from "./components/ComponentFactory.ts";
import MessageReaction from "./MessageReaction.ts";
import Application, { NewTeam } from "./Application.ts";
import InteractionFactory from "./interactions/InteractionFactory.ts";
import * as Routes from "../Routes.ts";
import { StickerItem } from "./Sticker.ts";
} from '../../discordeno/mod.ts';
import type { Channel } from './channels.ts';
import type { Component } from './components/Component.ts';
import type { GetReactions } from '../Routes.ts';
import type { MessageInteraction } from './interactions/InteractionFactory.ts';
import { MessageFlags } from '../Util.ts';
import { Snowflake } from '../Snowflake.ts';
import { ChannelFactory, ThreadChannel } from './channels.ts';
import Util from '../Util.ts';
import User from './User.ts';
import Member from './Member.ts';
import Attachment from './Attachment.ts';
import ComponentFactory from './components/ComponentFactory.ts';
import MessageReaction from './MessageReaction.ts';
import Application, { NewTeam } from './Application.ts';
import InteractionFactory from './interactions/InteractionFactory.ts';
import * as Routes from '../Routes.ts';
import { StickerItem } from './Sticker.ts';
/**
* @link https://discord.com/developers/docs/resources/channel#allowed-mentions-object
@ -137,7 +137,7 @@ export class Message implements Model {
}
// webhook handling
if (data.webhook_id && data.author.discriminator === "0000") {
if (data.webhook_id && data.author.discriminator === '0000') {
this.webhook = {
id: data.webhook_id!,
username: data.author.username,
@ -322,7 +322,7 @@ export class Message implements Model {
/** gets the url of the message that points to the message */
get url(): string {
return `https://discord.com/channels/${this.guildId ?? "@me"}/${this.channelId}/${this.id}`;
return `https://discord.com/channels/${this.guildId ?? '@me'}/${this.channelId}/${this.id}`;
}
/**
@ -339,7 +339,7 @@ export class Message implements Model {
async pin(): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"PUT",
'PUT',
Routes.CHANNEL_PIN(this.channelId, this.id),
);
}
@ -350,7 +350,7 @@ export class Message implements Model {
async unpin(): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.CHANNEL_PIN(this.channelId, this.id),
);
}
@ -359,7 +359,7 @@ export class Message implements Model {
async edit(options: EditMessage): Promise<Message> {
const message = await this.session.rest.runMethod(
this.session.rest,
"POST",
'POST',
Routes.CHANNEL_MESSAGE(this.id, this.channelId),
{
content: options.content,
@ -394,7 +394,7 @@ export class Message implements Model {
async delete({ reason }: { reason: string }): Promise<Message> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.CHANNEL_MESSAGE(this.channelId, this.id),
{ reason },
);
@ -406,7 +406,7 @@ export class Message implements Model {
async reply(options: CreateMessage): Promise<Message> {
const message = await this.session.rest.runMethod<DiscordMessage>(
this.session.rest,
"POST",
'POST',
Routes.CHANNEL_MESSAGES(this.channelId),
{
content: options.content,
@ -441,11 +441,11 @@ export class Message implements Model {
/** adds a Reaction */
async addReaction(reaction: EmojiResolvable): Promise<void> {
const r = typeof reaction === "string" ? reaction : `${reaction.name}:${reaction.id}`;
const r = typeof reaction === 'string' ? reaction : `${reaction.name}:${reaction.id}`;
await this.session.rest.runMethod<undefined>(
this.session.rest,
"PUT",
'PUT',
Routes.CHANNEL_MESSAGE_REACTION_ME(this.channelId, this.id, r),
{},
);
@ -453,11 +453,11 @@ export class Message implements Model {
/** removes a reaction from someone */
async removeReaction(reaction: EmojiResolvable, options?: { userId: Snowflake }): Promise<void> {
const r = typeof reaction === "string" ? reaction : `${reaction.name}:${reaction.id}`;
const r = typeof reaction === 'string' ? reaction : `${reaction.name}:${reaction.id}`;
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
options?.userId
? Routes.CHANNEL_MESSAGE_REACTION_USER(
this.channelId,
@ -474,11 +474,11 @@ export class Message implements Model {
* not recommended since the cache handles reactions already
*/
async fetchReactions(reaction: EmojiResolvable, options?: GetReactions): Promise<User[]> {
const r = typeof reaction === "string" ? reaction : `${reaction.name}:${reaction.id}`;
const r = typeof reaction === 'string' ? reaction : `${reaction.name}:${reaction.id}`;
const users = await this.session.rest.runMethod<DiscordUser[]>(
this.session.rest,
"GET",
'GET',
Routes.CHANNEL_MESSAGE_REACTION(this.channelId, this.id, encodeURIComponent(r), options),
);
@ -489,11 +489,11 @@ export class Message implements Model {
* same as Message.removeReaction but removes using a unicode emoji
*/
async removeReactionEmoji(reaction: EmojiResolvable): Promise<void> {
const r = typeof reaction === "string" ? reaction : `${reaction.name}:${reaction.id}`;
const r = typeof reaction === 'string' ? reaction : `${reaction.name}:${reaction.id}`;
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.CHANNEL_MESSAGE_REACTION(this.channelId, this.id, r),
);
}
@ -502,7 +502,7 @@ export class Message implements Model {
async nukeReactions(): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.CHANNEL_MESSAGE_REACTIONS(this.channelId, this.id),
);
}
@ -511,7 +511,7 @@ export class Message implements Model {
async crosspost(): Promise<Message> {
const message = await this.session.rest.runMethod<DiscordMessage>(
this.session.rest,
"POST",
'POST',
Routes.CHANNEL_MESSAGE_CROSSPOST(this.channelId, this.id),
);
@ -522,7 +522,7 @@ export class Message implements Model {
async fetch(): Promise<(Message | undefined)> {
const message = await this.session.rest.runMethod<DiscordMessage>(
this.session.rest,
"GET",
'GET',
Routes.CHANNEL_MESSAGE(this.channelId, this.id),
);

View File

@ -1,8 +1,8 @@
// deno-lint-ignore-file no-empty-interface
import type { Session } from "../Session.ts";
import type { DiscordMemberWithUser, DiscordMessageReactionAdd, DiscordReaction } from "../../discordeno/mod.ts";
import Emoji from "./Emoji.ts";
import Member from "./Member.ts";
import type { Session } from '../Session.ts';
import type { DiscordMemberWithUser, DiscordMessageReactionAdd, DiscordReaction } from '../../discordeno/mod.ts';
import Emoji from './Emoji.ts';
import Member from './Member.ts';
export interface MessageReactionAdd {
userId: string;
@ -13,13 +13,13 @@ export interface MessageReactionAdd {
emoji: Partial<Emoji>;
}
export interface MessageReactionRemove extends Omit<MessageReactionAdd, "member"> {}
export interface MessageReactionRemove extends Omit<MessageReactionAdd, 'member'> {}
export interface MessageReactionRemoveAll extends Pick<MessageReactionAdd, "channelId" | "messageId" | "guildId"> {}
export interface MessageReactionRemoveAll extends Pick<MessageReactionAdd, 'channelId' | 'messageId' | 'guildId'> {}
export type MessageReactionRemoveEmoji = Pick<
MessageReactionAdd,
"channelId" | "guildId" | "messageId" | "emoji"
'channelId' | 'guildId' | 'messageId' | 'emoji'
>;
export function NewMessageReactionAdd(session: Session, data: DiscordMessageReactionAdd): MessageReactionAdd {
@ -29,7 +29,7 @@ export function NewMessageReactionAdd(session: Session, data: DiscordMessageReac
messageId: data.message_id,
guildId: data.guild_id,
member: data.member
? new Member(session, data.member as DiscordMemberWithUser, data.guild_id || "")
? new Member(session, data.member as DiscordMemberWithUser, data.guild_id || '')
: undefined,
emoji: new Emoji(session, data.emoji),
};

View File

@ -1,4 +1,4 @@
import { BitwisePermissionFlags } from "../../discordeno/mod.ts";
import { BitwisePermissionFlags } from '../../discordeno/mod.ts';
export type PermissionString = keyof typeof BitwisePermissionFlags;
export type PermissionResolvable =
@ -25,13 +25,13 @@ export class Permissions {
static resolve(bit: PermissionResolvable): bigint {
switch (typeof bit) {
case "bigint":
case 'bigint':
return bit;
case "number":
case 'number':
return BigInt(bit);
case "string":
case 'string':
return BigInt(Permissions.Flags[bit]);
case "object":
case 'object':
return Permissions.resolve(
bit.map((p) => BigInt(Permissions.Flags[p])).reduce((acc, cur) => acc | cur, 0n),
);

View File

@ -4,11 +4,11 @@ import type {
DiscordActivitySecrets,
DiscordClientStatus,
DiscordPresenceUpdate,
} from "../../discordeno/mod.ts";
import type { Session } from "../Session.ts";
import { User } from "./User.ts";
import { Snowflake } from "../Snowflake.ts";
import type { ComponentEmoji } from "../Util.ts";
} from '../../discordeno/mod.ts';
import type { Session } from '../Session.ts';
import { User } from './User.ts';
import { Snowflake } from '../Snowflake.ts';
import type { ComponentEmoji } from '../Util.ts';
export interface ActivityAssets {
largeImage?: string;

View File

@ -1,10 +1,10 @@
import type { Model } from "./Base.ts";
import type { DiscordRole } from "../../discordeno/mod.ts";
import type { Session } from "../Session.ts";
import { Snowflake } from "../Snowflake.ts";
import { Guild, type ModifyGuildRole } from "./guilds.ts";
import Permissions from "./Permissions.ts";
import Util from "../Util.ts";
import type { Model } from './Base.ts';
import type { DiscordRole } from '../../discordeno/mod.ts';
import type { Session } from '../Session.ts';
import { Snowflake } from '../Snowflake.ts';
import { Guild, type ModifyGuildRole } from './guilds.ts';
import Permissions from './Permissions.ts';
import Util from '../Util.ts';
export class Role implements Model {
constructor(session: Session, data: DiscordRole, guildId: Snowflake) {
@ -44,7 +44,7 @@ export class Role implements Model {
}
get hexColor(): string {
return `#${this.color.toString(16).padStart(6, "0")}`;
return `#${this.color.toString(16).padStart(6, '0')}`;
}
async delete(): Promise<void> {
@ -67,7 +67,7 @@ export class Role implements Model {
toString(): string {
switch (this.id) {
case this.guildId:
return "@everyone";
return '@everyone';
default:
return `<@&${this.id}>`;
}

View File

@ -1,8 +1,8 @@
import type { Model } from "./Base.ts";
import type { Session } from "../Session.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { DiscordStageInstance as DiscordAutoClosingStageInstance } from "../../discordeno/mod.ts";
import * as Routes from "../Routes.ts";
import type { Model } from './Base.ts';
import type { Session } from '../Session.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { DiscordStageInstance as DiscordAutoClosingStageInstance } from '../../discordeno/mod.ts';
import * as Routes from '../Routes.ts';
export interface DiscordStageInstanceB extends DiscordAutoClosingStageInstance {
privacy_level: PrivacyLevels;
@ -42,7 +42,7 @@ export class StageInstance implements Model {
async edit(options: { topic?: string; privacyLevel?: PrivacyLevels }): Promise<StageInstance> {
const stageInstance = await this.session.rest.runMethod<DiscordStageInstanceB>(
this.session.rest,
"PATCH",
'PATCH',
Routes.STAGE_INSTANCE(this.id),
{
topic: options.topic,
@ -54,7 +54,7 @@ export class StageInstance implements Model {
}
async delete(): Promise<void> {
await this.session.rest.runMethod<undefined>(this.session.rest, "DELETE", Routes.STAGE_INSTANCE(this.id));
await this.session.rest.runMethod<undefined>(this.session.rest, 'DELETE', Routes.STAGE_INSTANCE(this.id));
}
}

View File

@ -1,9 +1,9 @@
import type { DiscordSticker, DiscordStickerPack, StickerFormatTypes, StickerTypes } from "../../discordeno/mod.ts";
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import { User } from "./User.ts";
import * as Routes from "../Routes.ts";
import type { DiscordSticker, DiscordStickerPack, StickerFormatTypes, StickerTypes } from '../../discordeno/mod.ts';
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import { User } from './User.ts';
import * as Routes from '../Routes.ts';
export interface StickerItem {
id: Snowflake;
@ -28,7 +28,7 @@ export class Sticker implements Model {
this.packId = data.pack_id;
this.name = data.name;
this.description = data.description;
this.tags = data.tags.split(",");
this.tags = data.tags.split(',');
this.type = data.type;
this.formatType = data.format_type;
this.available = !!data.available;
@ -52,7 +52,7 @@ export class Sticker implements Model {
async fetchPremiumPack(): Promise<StickerPack> {
const data = await this.session.rest.runMethod<DiscordStickerPack>(
this.session.rest,
"GET",
'GET',
Routes.STICKER_PACKS(),
);
return {

View File

@ -1,8 +1,8 @@
import type { Model } from "./Base.ts";
import type { Session } from "../Session.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { DiscordThreadMember } from "../../discordeno/mod.ts";
import * as Routes from "../Routes.ts";
import type { Model } from './Base.ts';
import type { Session } from '../Session.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { DiscordThreadMember } from '../../discordeno/mod.ts';
import * as Routes from '../Routes.ts';
/**
* A member that comes from a thread
@ -28,7 +28,7 @@ export class ThreadMember implements Model {
async quitThread(memberId: Snowflake = this.session.botId): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.THREAD_USER(this.id, memberId),
);
}
@ -36,7 +36,7 @@ export class ThreadMember implements Model {
async fetchMember(memberId: Snowflake = this.session.botId): Promise<ThreadMember> {
const member = await this.session.rest.runMethod<DiscordThreadMember>(
this.session.rest,
"GET",
'GET',
Routes.THREAD_USER(this.id, memberId),
);

View File

@ -1,10 +1,10 @@
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import type { DiscordUser, PremiumTypes, UserFlags } from "../../discordeno/mod.ts";
import type { ImageFormat, ImageSize } from "../Util.ts";
import Util from "../Util.ts";
import * as Routes from "../Routes.ts";
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import type { DiscordUser, PremiumTypes, UserFlags } from '../../discordeno/mod.ts';
import type { ImageFormat, ImageSize } from '../Util.ts';
import Util from '../Util.ts';
import * as Routes from '../Routes.ts';
/**
* @link https://discord.com/developers/docs/resources/user#user-object

View File

@ -1,6 +1,6 @@
import type { Model } from "./Base.ts";
import type { Session } from "../Session.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Model } from './Base.ts';
import type { Session } from '../Session.ts';
import type { Snowflake } from '../Snowflake.ts';
import type {
DiscordEmbed,
DiscordMessage,
@ -8,14 +8,14 @@ import type {
DiscordWebhook,
FileContent,
WebhookTypes,
} from "../../discordeno/mod.ts";
import type { WebhookOptions } from "../Routes.ts";
import type { Attachment } from "./Attachment.ts";
import type { AllowedMentions, CreateMessage } from "./Message.ts";
import Util from "../Util.ts";
import User from "./User.ts";
import Message from "./Message.ts";
import * as Routes from "../Routes.ts";
} from '../../discordeno/mod.ts';
import type { WebhookOptions } from '../Routes.ts';
import type { Attachment } from './Attachment.ts';
import type { AllowedMentions, CreateMessage } from './Message.ts';
import Util from '../Util.ts';
import User from './User.ts';
import Message from './Message.ts';
import * as Routes from '../Routes.ts';
/**
* @link https://discord.com/developers/docs/resources/webhook#edit-webhook-message-jsonform-params
@ -88,9 +88,9 @@ export class Webhook implements Model {
wait: options?.wait,
threadId: options?.threadId,
}),
method: "POST",
method: 'POST',
payload: this.session.rest.createRequestBody(this.session.rest, {
method: "POST",
method: 'POST',
body: {
...data,
},
@ -103,7 +103,7 @@ export class Webhook implements Model {
async fetch(): Promise<Webhook> {
const message = await this.session.rest.runMethod<DiscordWebhook>(
this.session.rest,
"GET",
'GET',
Routes.WEBHOOK_TOKEN(this.id, this.token),
);
@ -117,7 +117,7 @@ export class Webhook implements Model {
const message = await this.session.rest.runMethod<DiscordMessage>(
this.session.rest,
"GET",
'GET',
Routes.WEBHOOK_MESSAGE(this.id, this.token, messageId, options),
);
@ -126,12 +126,12 @@ export class Webhook implements Model {
async deleteMessage(messageId: Snowflake, options?: { threadId?: Snowflake }): Promise<void> {
if (!this.token) {
throw new Error("No token found");
throw new Error('No token found');
}
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.WEBHOOK_MESSAGE(this.id, this.token, messageId, options),
);
}
@ -141,12 +141,12 @@ export class Webhook implements Model {
options?: EditWebhookMessage & { threadId?: Snowflake },
): Promise<Message> {
if (!this.token) {
throw new Error("No token found");
throw new Error('No token found');
}
const message = await this.session.rest.runMethod<DiscordMessage>(
this.session.rest,
"PATCH",
'PATCH',
messageId
? Routes.WEBHOOK_MESSAGE(this.id, this.token, messageId)
: Routes.WEBHOOK_MESSAGE_ORIGINAL(this.id, this.token),

View File

@ -1,8 +1,8 @@
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import type { DiscordWelcomeScreenChannel } from "../../discordeno/mod.ts";
import Emoji from "./Emoji.ts";
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import type { DiscordWelcomeScreenChannel } from '../../discordeno/mod.ts';
import Emoji from './Emoji.ts';
/**
* Not a channel

View File

@ -1,6 +1,6 @@
import type { Session } from "../Session.ts";
import type { DiscordWelcomeScreen } from "../../discordeno/mod.ts";
import WelcomeChannel from "./WelcomeChannel.ts";
import type { Session } from '../Session.ts';
import type { DiscordWelcomeScreen } from '../../discordeno/mod.ts';
import WelcomeChannel from './WelcomeChannel.ts';
/**
* @link https://discord.com/developers/docs/resources/guild#welcome-screen-object

View File

@ -1,4 +1,4 @@
import type { DiscordEmbed, DiscordEmbedField, DiscordEmbedProvider } from "../../../discordeno/mod.ts";
import type { DiscordEmbed, DiscordEmbedField, DiscordEmbedProvider } from '../../../discordeno/mod.ts';
export interface EmbedFooter {
text: string;

View File

@ -1,4 +1,4 @@
import type { DiscordInputTextComponent, MessageComponentTypes, TextStyles } from "../../../../discordeno/mod.ts";
import type { DiscordInputTextComponent, MessageComponentTypes, TextStyles } from '../../../../discordeno/mod.ts';
export class InputTextBuilder {
constructor() {

View File

@ -1,5 +1,5 @@
import type { DiscordActionRow, MessageComponentTypes } from "../../../../discordeno/mod.ts";
import type { ComponentBuilder } from "../../../Util.ts";
import type { DiscordActionRow, MessageComponentTypes } from '../../../../discordeno/mod.ts';
import type { ComponentBuilder } from '../../../Util.ts';
export class ActionRowBuilder<T extends ComponentBuilder> {
constructor() {
@ -26,7 +26,7 @@ export class ActionRowBuilder<T extends ComponentBuilder> {
toJSON(): DiscordActionRow {
return {
type: this.type,
components: this.components.map((c) => c.toJSON()) as DiscordActionRow["components"],
components: this.components.map((c) => c.toJSON()) as DiscordActionRow['components'],
};
}
}

View File

@ -1,5 +1,5 @@
import { type ButtonStyles, type DiscordButtonComponent, MessageComponentTypes } from "../../../../discordeno/mod.ts";
import type { ComponentEmoji } from "../../../Util.ts";
import { type ButtonStyles, type DiscordButtonComponent, MessageComponentTypes } from '../../../../discordeno/mod.ts';
import type { ComponentEmoji } from '../../../Util.ts';
export class ButtonBuilder {
constructor() {

View File

@ -1,5 +1,5 @@
import { type DiscordSelectMenuComponent, MessageComponentTypes } from "../../../../discordeno/mod.ts";
import type { SelectMenuOptionBuilder } from "./SelectMenuOptionBuilder.ts";
import { type DiscordSelectMenuComponent, MessageComponentTypes } from '../../../../discordeno/mod.ts';
import type { SelectMenuOptionBuilder } from './SelectMenuOptionBuilder.ts';
export class SelectMenuBuilder {
constructor() {

View File

@ -1,5 +1,5 @@
import type { DiscordSelectOption } from "../../../../discordeno/mod.ts";
import type { ComponentEmoji } from "../../../Util.ts";
import type { DiscordSelectOption } from '../../../../discordeno/mod.ts';
import type { ComponentEmoji } from '../../../Util.ts';
export class SelectMenuOptionBuilder {
constructor() {

View File

@ -1,13 +1,13 @@
import type { Localization, PermissionStrings } from "../../../../discordeno/mod.ts";
import { ApplicationCommandTypes } from "../../../../discordeno/mod.ts";
import { OptionBased } from "./ApplicationCommandOption.ts";
import { CreateApplicationCommand } from "../../../Session.ts";
import type { Localization, PermissionStrings } from '../../../../discordeno/mod.ts';
import { ApplicationCommandTypes } from '../../../../discordeno/mod.ts';
import { OptionBased } from './ApplicationCommandOption.ts';
import { CreateApplicationCommand } from '../../../Session.ts';
export abstract class ApplicationCommandBuilder implements CreateApplicationCommand {
constructor(
type: ApplicationCommandTypes = ApplicationCommandTypes.ChatInput,
name: string = "",
description: string = "",
name: string = '',
description: string = '',
defaultMemberPermissions?: PermissionStrings[],
nameLocalizations?: Localization,
descriptionLocalizations?: Localization,
@ -74,7 +74,7 @@ export class MessageApplicationCommandBuilder {
}
toJSON(): { name: string; type: ApplicationCommandTypes.Message } {
if (!this.name) throw new TypeError("Propety 'name' is required");
if (!this.name) throw new TypeError('Propety \'name\' is required');
return {
type: ApplicationCommandTypes.Message,
@ -87,10 +87,10 @@ export class ChatInputApplicationCommandBuilder extends ApplicationCommandBuilde
type: ApplicationCommandTypes.ChatInput = ApplicationCommandTypes.ChatInput;
toJSON(): CreateApplicationCommand {
if (!this.type) throw new TypeError("Propety 'type' is required");
if (!this.name) throw new TypeError("Propety 'name' is required");
if (!this.type) throw new TypeError('Propety \'type\' is required');
if (!this.name) throw new TypeError('Propety \'name\' is required');
if (!this.description) {
throw new TypeError("Propety 'description' is required");
throw new TypeError('Propety \'description\' is required');
}
return {

View File

@ -1,5 +1,5 @@
import { ApplicationCommandOptionTypes, type ChannelTypes, type Localization } from "../../../../discordeno/mod.ts";
import { ApplicationCommandOptionChoice } from "../../interactions/BaseInteraction.ts";
import { ApplicationCommandOptionTypes, type ChannelTypes, type Localization } from '../../../../discordeno/mod.ts';
import { ApplicationCommandOptionChoice } from '../../interactions/BaseInteraction.ts';
export class ChoiceBuilder {
name?: string;
@ -16,8 +16,8 @@ export class ChoiceBuilder {
}
toJSON(): ApplicationCommandOptionChoice {
if (!this.name) throw new TypeError("Property 'name' is required");
if (!this.value) throw new TypeError("Property 'value' is required");
if (!this.name) throw new TypeError('Property \'name\' is required');
if (!this.value) throw new TypeError('Property \'value\' is required');
return {
name: this.name,
@ -56,10 +56,10 @@ export class OptionBuilder {
}
toJSON(): ApplicationCommandOption {
if (!this.type) throw new TypeError("Property 'type' is required");
if (!this.name) throw new TypeError("Property 'name' is required");
if (!this.type) throw new TypeError('Property \'type\' is required');
if (!this.name) throw new TypeError('Property \'name\' is required');
if (!this.description) {
throw new TypeError("Property 'description' is required");
throw new TypeError('Property \'description\' is required');
}
const applicationCommandOption: ApplicationCommandOption = {
@ -261,18 +261,18 @@ export class OptionBased {
// deno-lint-ignore ban-types
static applyTo(klass: Function, ignore: Array<keyof OptionBased> = []): void {
const methods: Array<keyof OptionBased> = [
"addOption",
"addNestedOption",
"addStringOption",
"addIntegerOption",
"addNumberOption",
"addBooleanOption",
"addSubCommand",
"addSubCommandGroup",
"addUserOption",
"addChannelOption",
"addRoleOption",
"addMentionableOption",
'addOption',
'addNestedOption',
'addStringOption',
'addIntegerOption',
'addNumberOption',
'addBooleanOption',
'addSubCommand',
'addSubCommandGroup',
'addUserOption',
'addChannelOption',
'addRoleOption',
'addMentionableOption',
];
for (const method of methods) {
@ -296,10 +296,10 @@ export class OptionBuilderNested extends OptionBuilder {
}
override toJSON(): ApplicationCommandOption {
if (!this.type) throw new TypeError("Property 'type' is required");
if (!this.name) throw new TypeError("Property 'name' is required");
if (!this.type) throw new TypeError('Property \'type\' is required');
if (!this.name) throw new TypeError('Property \'name\' is required');
if (!this.description) {
throw new TypeError("Property 'description' is required");
throw new TypeError('Property \'description\' is required');
}
return {

View File

@ -1,8 +1,8 @@
/** Types */
import type { Model } from "./Base.ts";
import type { Snowflake } from "../Snowflake.ts";
import type { Session } from "../Session.ts";
import type { PermissionsOverwrites } from "../Util.ts";
import type { Model } from './Base.ts';
import type { Snowflake } from '../Snowflake.ts';
import type { Session } from '../Session.ts';
import type { PermissionsOverwrites } from '../Util.ts';
/** External from vendor */
import {
@ -17,19 +17,19 @@ import {
GatewayOpcodes,
TargetTypes,
VideoQualityModes,
} from "../../discordeno/mod.ts";
} from '../../discordeno/mod.ts';
/** Functions and others */
import { calculateShardId } from "../../discordeno/gateway/calculateShardId.ts";
import { urlToBase64 } from "../util/urlToBase64.ts";
import { calculateShardId } from '../../discordeno/gateway/calculateShardId.ts';
import { urlToBase64 } from '../util/urlToBase64.ts';
/** Classes and routes */
import * as Routes from "../Routes.ts";
import Message, { CreateMessage, EditMessage, EmojiResolvable } from "./Message.ts";
import Invite from "./Invite.ts";
import Webhook from "./Webhook.ts";
import User from "./User.ts";
import ThreadMember from "./ThreadMember.ts";
import * as Routes from '../Routes.ts';
import Message, { CreateMessage, EditMessage, EmojiResolvable } from './Message.ts';
import Invite from './Invite.ts';
import Webhook from './Webhook.ts';
import User from './User.ts';
import ThreadMember from './ThreadMember.ts';
export abstract class BaseChannel implements Model {
constructor(session: Session, data: DiscordChannel) {
@ -147,19 +147,19 @@ export class TextChannel {
// deno-lint-ignore ban-types
static applyTo(klass: Function, ignore: Array<keyof TextChannel> = []): void {
const methods: Array<keyof TextChannel> = [
"fetchPins",
"createInvite",
"fetchMessages",
"sendTyping",
"pinMessage",
"unpinMessage",
"addReaction",
"removeReaction",
"nukeReactions",
"fetchPins",
"sendMessage",
"editMessage",
"createWebhook",
'fetchPins',
'createInvite',
'fetchMessages',
'sendTyping',
'pinMessage',
'unpinMessage',
'addReaction',
'removeReaction',
'nukeReactions',
'fetchPins',
'sendMessage',
'editMessage',
'createWebhook',
];
for (const method of methods) {
@ -172,7 +172,7 @@ export class TextChannel {
async fetchPins(): Promise<Message[] | []> {
const messages = await this.session.rest.runMethod<DiscordMessage[]>(
this.session.rest,
"GET",
'GET',
Routes.CHANNEL_PINS(this.id),
);
return messages[0] ? messages.map((x: DiscordMessage) => new Message(this.session, x)) : [];
@ -181,7 +181,7 @@ export class TextChannel {
async createInvite(options?: DiscordInviteOptions): Promise<Invite> {
const invite = await this.session.rest.runMethod<DiscordInvite>(
this.session.rest,
"POST",
'POST',
Routes.CHANNEL_INVITES(this.id),
options
? {
@ -200,10 +200,10 @@ export class TextChannel {
}
async fetchMessages(options?: Routes.GetMessagesOptions): Promise<Message[] | []> {
if (options?.limit! > 100) throw Error("Values must be between 0-100");
if (options?.limit! > 100) throw Error('Values must be between 0-100');
const messages = await this.session.rest.runMethod<DiscordMessage[]>(
this.session.rest,
"GET",
'GET',
Routes.CHANNEL_MESSAGES(this.id, options),
);
return messages[0] ? messages.map((x) => new Message(this.session, x)) : [];
@ -212,7 +212,7 @@ export class TextChannel {
async sendTyping(): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"POST",
'POST',
Routes.CHANNEL_TYPING(this.id),
);
}
@ -280,7 +280,7 @@ export class TextChannel {
async createWebhook(options: CreateWebhook): Promise<Webhook> {
const webhook = await this.session.rest.runMethod<DiscordWebhook>(
this.session.rest,
"POST",
'POST',
Routes.CHANNEL_WEBHOOKS(this.id),
{
name: options.name,
@ -379,7 +379,7 @@ export class GuildChannel extends BaseChannel implements Model {
async fetchInvites(): Promise<Invite[]> {
const invites = await this.session.rest.runMethod<DiscordInviteMetadata[]>(
this.session.rest,
"GET",
'GET',
Routes.CHANNEL_INVITES(this.id),
);
@ -394,22 +394,22 @@ export class GuildChannel extends BaseChannel implements Model {
): Promise<Channel> {
const channel = await this.session.rest.runMethod<DiscordChannel>(
this.session.rest,
"PATCH",
'PATCH',
Routes.CHANNEL(this.id),
{
name: options.name,
type: "type" in options ? options.type : undefined,
type: 'type' in options ? options.type : undefined,
position: options.position,
topic: "topic" in options ? options.topic : undefined,
nsfw: "nfsw" in options ? options.nfsw : undefined,
rate_limit_per_user: "rateLimitPerUser" in options ? options.rateLimitPerUser : undefined,
bitrate: "bitrate" in options ? options.bitrate : undefined,
user_limit: "userLimit" in options ? options.userLimit : undefined,
topic: 'topic' in options ? options.topic : undefined,
nsfw: 'nfsw' in options ? options.nfsw : undefined,
rate_limit_per_user: 'rateLimitPerUser' in options ? options.rateLimitPerUser : undefined,
bitrate: 'bitrate' in options ? options.bitrate : undefined,
user_limit: 'userLimit' in options ? options.userLimit : undefined,
permissions_overwrites: options.permissionOverwrites,
parent_id: "parentId" in options ? options.parentId : undefined,
rtc_region: "rtcRegion" in options ? options.rtcRegion : undefined,
video_quality_mode: "videoQualityMode" in options ? options.videoQualityMode : undefined,
default_auto_archive_duration: "defaultAutoArchiveDuration" in options
parent_id: 'parentId' in options ? options.parentId : undefined,
rtc_region: 'rtcRegion' in options ? options.rtcRegion : undefined,
video_quality_mode: 'videoQualityMode' in options ? options.videoQualityMode : undefined,
default_auto_archive_duration: 'defaultAutoArchiveDuration' in options
? options.defaultAutoArchiveDuration
: undefined,
},
@ -418,25 +418,25 @@ export class GuildChannel extends BaseChannel implements Model {
}
async getArchivedThreads(
options: Routes.ListArchivedThreads & { type: "public" | "private" | "privateJoinedThreads" },
options: Routes.ListArchivedThreads & { type: 'public' | 'private' | 'privateJoinedThreads' },
): Promise<ReturnThreadsArchive> {
let func: (channelId: Snowflake, options: Routes.ListArchivedThreads) => string;
switch (options.type) {
case "public":
case 'public':
func = Routes.THREAD_ARCHIVED_PUBLIC;
break;
case "private":
case 'private':
func = Routes.THREAD_START_PRIVATE;
break;
case "privateJoinedThreads":
case 'privateJoinedThreads':
func = Routes.THREAD_ARCHIVED_PRIVATE_JOINED;
break;
}
const { threads, members, has_more } = await this.session.rest.runMethod<DiscordListArchivedThreads>(
this.session.rest,
"GET",
'GET',
func(this.id, options),
);
@ -454,8 +454,8 @@ export class GuildChannel extends BaseChannel implements Model {
async createThread(options: ThreadCreateOptions): Promise<ThreadChannel> {
const thread = await this.session.rest.runMethod<DiscordChannel>(
this.session.rest,
"POST",
"messageId" in options
'POST',
'messageId' in options
? Routes.THREAD_START_PUBLIC(this.id, options.messageId)
: Routes.THREAD_START_PRIVATE(this.id),
{
@ -541,7 +541,7 @@ export class DMChannel extends BaseChannel implements Model {
async close(): Promise<DMChannel> {
const channel = await this.session.rest.runMethod<DiscordChannel>(
this.session.rest,
"DELETE",
'DELETE',
Routes.CHANNEL(this.id),
);
@ -549,7 +549,7 @@ export class DMChannel extends BaseChannel implements Model {
}
}
export interface DMChannel extends Omit<TextChannel, "type">, Omit<BaseChannel, "type"> {}
export interface DMChannel extends Omit<TextChannel, 'type'>, Omit<BaseChannel, 'type'> {}
TextChannel.applyTo(DMChannel);
@ -632,7 +632,7 @@ export class ThreadChannel extends GuildChannel implements Model {
async joinThread(): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"PUT",
'PUT',
Routes.THREAD_ME(this.id),
);
}
@ -640,7 +640,7 @@ export class ThreadChannel extends GuildChannel implements Model {
async addToThread(guildMemberId: Snowflake): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"PUT",
'PUT',
Routes.THREAD_USER(this.id, guildMemberId),
);
}
@ -648,7 +648,7 @@ export class ThreadChannel extends GuildChannel implements Model {
async leaveToThread(guildMemberId: Snowflake): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.THREAD_USER(this.id, guildMemberId),
);
}
@ -664,7 +664,7 @@ export class ThreadChannel extends GuildChannel implements Model {
async fetchMembers(): Promise<ThreadMember[]> {
const members = await this.session.rest.runMethod<DiscordThreadMember[]>(
this.session.rest,
"GET",
'GET',
Routes.THREAD_MEMBERS(this.id),
);
@ -672,7 +672,7 @@ export class ThreadChannel extends GuildChannel implements Model {
}
}
export interface ThreadChannel extends Omit<GuildChannel, "type">, Omit<TextChannel, "type"> {}
export interface ThreadChannel extends Omit<GuildChannel, 'type'>, Omit<TextChannel, 'type'> {}
TextChannel.applyTo(ThreadChannel);
@ -730,7 +730,7 @@ export class ChannelFactory {
case ChannelTypes.GuildStageVoice:
return new StageChannel(session, channel, channel.guild_id!);
default:
throw new Error("Channel was not implemented");
throw new Error('Channel was not implemented');
}
}
@ -753,7 +753,7 @@ export class ChannelFactory {
if (textBasedChannels.includes(channel.type)) {
return new TextChannel(session, channel);
}
throw new Error("Channel was not implemented");
throw new Error('Channel was not implemented');
}
}
}

View File

@ -1,12 +1,12 @@
import type { Session } from "../../Session.ts";
import type { DiscordComponent, DiscordInputTextComponent } from "../../../discordeno/mod.ts";
import type { ActionRowComponent, Component } from "./Component.ts";
import { ButtonStyles, MessageComponentTypes } from "../../../discordeno/mod.ts";
import BaseComponent from "./Component.ts";
import Button from "./ButtonComponent.ts";
import LinkButton from "./LinkButtonComponent.ts";
import SelectMenu from "./SelectMenuComponent.ts";
import InputText from "./TextInputComponent.ts";
import type { Session } from '../../Session.ts';
import type { DiscordComponent, DiscordInputTextComponent } from '../../../discordeno/mod.ts';
import type { ActionRowComponent, Component } from './Component.ts';
import { ButtonStyles, MessageComponentTypes } from '../../../discordeno/mod.ts';
import BaseComponent from './Component.ts';
import Button from './ButtonComponent.ts';
import LinkButton from './LinkButtonComponent.ts';
import SelectMenu from './SelectMenuComponent.ts';
import InputText from './TextInputComponent.ts';
export class ActionRow extends BaseComponent implements ActionRowComponent {
constructor(session: Session, data: DiscordComponent) {
@ -26,7 +26,7 @@ export class ActionRow extends BaseComponent implements ActionRowComponent {
case MessageComponentTypes.InputText:
return new InputText(session, component as DiscordInputTextComponent);
case MessageComponentTypes.ActionRow:
throw new Error("Cannot have an action row inside an action row");
throw new Error('Cannot have an action row inside an action row');
}
});
}

View File

@ -1,9 +1,9 @@
import type { Session } from "../../Session.ts";
import type { ButtonStyles, DiscordComponent } from "../../../discordeno/mod.ts";
import type { ButtonComponent } from "./Component.ts";
import { MessageComponentTypes } from "../../../discordeno/mod.ts";
import BaseComponent from "./Component.ts";
import Emoji from "../Emoji.ts";
import type { Session } from '../../Session.ts';
import type { ButtonStyles, DiscordComponent } from '../../../discordeno/mod.ts';
import type { ButtonComponent } from './Component.ts';
import { MessageComponentTypes } from '../../../discordeno/mod.ts';
import BaseComponent from './Component.ts';
import Emoji from '../Emoji.ts';
export class Button extends BaseComponent implements ButtonComponent {
constructor(session: Session, data: DiscordComponent) {

View File

@ -1,5 +1,5 @@
import type Emoji from "../Emoji.ts";
import { ButtonStyles, MessageComponentTypes, TextStyles } from "../../../discordeno/mod.ts";
import type Emoji from '../Emoji.ts';
import { ButtonStyles, MessageComponentTypes, TextStyles } from '../../../discordeno/mod.ts';
export class BaseComponent {
constructor(type: MessageComponentTypes) {

View File

@ -1,12 +1,12 @@
import type { Session } from "../../Session.ts";
import type { DiscordComponent, DiscordInputTextComponent } from "../../../discordeno/mod.ts";
import type { Component } from "./Component.ts";
import { ButtonStyles, MessageComponentTypes } from "../../../discordeno/mod.ts";
import ActionRow from "./ActionRowComponent.ts";
import Button from "./ButtonComponent.ts";
import LinkButton from "./ButtonComponent.ts";
import SelectMenu from "./SelectMenuComponent.ts";
import TextInput from "./TextInputComponent.ts";
import type { Session } from '../../Session.ts';
import type { DiscordComponent, DiscordInputTextComponent } from '../../../discordeno/mod.ts';
import type { Component } from './Component.ts';
import { ButtonStyles, MessageComponentTypes } from '../../../discordeno/mod.ts';
import ActionRow from './ActionRowComponent.ts';
import Button from './ButtonComponent.ts';
import LinkButton from './ButtonComponent.ts';
import SelectMenu from './SelectMenuComponent.ts';
import TextInput from './TextInputComponent.ts';
export class ComponentFactory {
/**

View File

@ -1,9 +1,9 @@
import type { Session } from "../../Session.ts";
import type { ButtonStyles, DiscordComponent } from "../../../discordeno/mod.ts";
import type { LinkButtonComponent } from "./Component.ts";
import { MessageComponentTypes } from "../../../discordeno/mod.ts";
import BaseComponent from "./Component.ts";
import Emoji from "../Emoji.ts";
import type { Session } from '../../Session.ts';
import type { ButtonStyles, DiscordComponent } from '../../../discordeno/mod.ts';
import type { LinkButtonComponent } from './Component.ts';
import { MessageComponentTypes } from '../../../discordeno/mod.ts';
import BaseComponent from './Component.ts';
import Emoji from '../Emoji.ts';
export class LinkButton extends BaseComponent implements LinkButtonComponent {
constructor(session: Session, data: DiscordComponent) {

View File

@ -1,9 +1,9 @@
import type { Session } from "../../Session.ts";
import type { DiscordComponent } from "../../../discordeno/mod.ts";
import type { SelectMenuComponent, SelectMenuOption } from "./Component.ts";
import { MessageComponentTypes } from "../../../discordeno/mod.ts";
import BaseComponent from "./Component.ts";
import Emoji from "../Emoji.ts";
import type { Session } from '../../Session.ts';
import type { DiscordComponent } from '../../../discordeno/mod.ts';
import type { SelectMenuComponent, SelectMenuOption } from './Component.ts';
import { MessageComponentTypes } from '../../../discordeno/mod.ts';
import BaseComponent from './Component.ts';
import Emoji from '../Emoji.ts';
export class SelectMenu extends BaseComponent implements SelectMenuComponent {
constructor(session: Session, data: DiscordComponent) {

View File

@ -1,8 +1,8 @@
import type { Session } from "../../Session.ts";
import type { DiscordInputTextComponent } from "../../../discordeno/mod.ts";
import type { TextInputComponent } from "./Component.ts";
import { MessageComponentTypes, TextStyles } from "../../../discordeno/mod.ts";
import BaseComponent from "./Component.ts";
import type { Session } from '../../Session.ts';
import type { DiscordInputTextComponent } from '../../../discordeno/mod.ts';
import type { TextInputComponent } from './Component.ts';
import { MessageComponentTypes, TextStyles } from '../../../discordeno/mod.ts';
import BaseComponent from './Component.ts';
export class TextInput extends BaseComponent implements TextInputComponent {
constructor(session: Session, data: DiscordInputTextComponent) {

View File

@ -1,5 +1,5 @@
import type { Model } from "./Base.ts";
import type { Session } from "../Session.ts";
import type { Model } from './Base.ts';
import type { Session } from '../Session.ts';
import type {
ChannelTypes,
DefaultMessageNotificationLevels,
@ -16,20 +16,20 @@ import type {
SystemChannelFlags,
VerificationLevels,
VideoQualityModes,
} from "../../discordeno/mod.ts";
import type { ImageFormat, ImageSize } from "../Util.ts";
import { GuildFeatures, PremiumTiers } from "../../discordeno/mod.ts";
import { Snowflake } from "../Snowflake.ts";
import Util from "../Util.ts";
import * as Routes from "../Routes.ts";
import WelcomeScreen from "./WelcomeScreen.ts";
import { GuildChannel, ReturnThreadsArchive, ThreadChannel } from "./channels.ts";
import ThreadMember from "./ThreadMember.ts";
import Member from "./Member.ts";
import Role from "./Role.ts";
import GuildEmoji from "./GuildEmoji.ts";
import { urlToBase64 } from "../util/urlToBase64.ts";
import Invite from "./Invite.ts";
} from '../../discordeno/mod.ts';
import type { ImageFormat, ImageSize } from '../Util.ts';
import { GuildFeatures, PremiumTiers } from '../../discordeno/mod.ts';
import { Snowflake } from '../Snowflake.ts';
import Util from '../Util.ts';
import * as Routes from '../Routes.ts';
import WelcomeScreen from './WelcomeScreen.ts';
import { GuildChannel, ReturnThreadsArchive, ThreadChannel } from './channels.ts';
import ThreadMember from './ThreadMember.ts';
import Member from './Member.ts';
import Role from './Role.ts';
import GuildEmoji from './GuildEmoji.ts';
import { urlToBase64 } from '../util/urlToBase64.ts';
import Invite from './Invite.ts';
/** BaseGuild */
/**
@ -242,7 +242,7 @@ export interface GuildCreateOptionsChannel {
userLimit?: number;
rtcRegion?: string | null;
videoQualityMode?: VideoQualityModes;
permissionOverwrites?: MakeRequired<Partial<DiscordOverwrite>, "id">[];
permissionOverwrites?: MakeRequired<Partial<DiscordOverwrite>, 'id'>[];
rateLimitPerUser?: number;
}
@ -391,7 +391,7 @@ export class Guild extends BaseGuild implements Model {
async editBotNickname(options: { nick: string | null; reason?: string }): Promise<(string | undefined)> {
const result = await this.session.rest.runMethod<{ nick?: string } | undefined>(
this.session.rest,
"PATCH",
'PATCH',
Routes.USER_NICK(this.id),
options,
);
@ -400,13 +400,13 @@ export class Guild extends BaseGuild implements Model {
}
async createEmoji(options: CreateGuildEmoji): Promise<GuildEmoji> {
if (options.image && !options.image.startsWith("data:image/")) {
if (options.image && !options.image.startsWith('data:image/')) {
options.image = await urlToBase64(options.image);
}
const emoji = await this.session.rest.runMethod<DiscordEmoji>(
this.session.rest,
"POST",
'POST',
Routes.GUILD_EMOJIS(this.id),
options,
);
@ -417,7 +417,7 @@ export class Guild extends BaseGuild implements Model {
async deleteEmoji(id: Snowflake, { reason }: { reason?: string } = {}): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.GUILD_EMOJI(this.id, id),
{ reason },
);
@ -426,7 +426,7 @@ export class Guild extends BaseGuild implements Model {
async editEmoji(id: Snowflake, options: ModifyGuildEmoji): Promise<GuildEmoji> {
const emoji = await this.session.rest.runMethod<DiscordEmoji>(
this.session.rest,
"PATCH",
'PATCH',
Routes.GUILD_EMOJI(this.id, id),
options,
);
@ -438,7 +438,7 @@ export class Guild extends BaseGuild implements Model {
let icon: string | undefined;
if (options.iconHash) {
if (typeof options.iconHash === "string") {
if (typeof options.iconHash === 'string') {
icon = options.iconHash;
} else {
icon = Util.iconBigintToHash(options.iconHash);
@ -447,7 +447,7 @@ export class Guild extends BaseGuild implements Model {
const role = await this.session.rest.runMethod<DiscordRole>(
this.session.rest,
"PUT",
'PUT',
Routes.GUILD_ROLES(this.id),
{
name: options.name,
@ -463,13 +463,13 @@ export class Guild extends BaseGuild implements Model {
}
async deleteRole(roleId: Snowflake): Promise<void> {
await this.session.rest.runMethod<undefined>(this.session.rest, "DELETE", Routes.GUILD_ROLE(this.id, roleId));
await this.session.rest.runMethod<undefined>(this.session.rest, 'DELETE', Routes.GUILD_ROLE(this.id, roleId));
}
async editRole(roleId: Snowflake, options: ModifyGuildRole): Promise<Role> {
const role = await this.session.rest.runMethod<DiscordRole>(
this.session.rest,
"PATCH",
'PATCH',
Routes.GUILD_ROLE(this.id, roleId),
{
name: options.name,
@ -485,7 +485,7 @@ export class Guild extends BaseGuild implements Model {
async addRole(memberId: Snowflake, roleId: Snowflake, { reason }: { reason?: string } = {}): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"PUT",
'PUT',
Routes.GUILD_MEMBER_ROLE(this.id, memberId, roleId),
{ reason },
);
@ -494,7 +494,7 @@ export class Guild extends BaseGuild implements Model {
async removeRole(memberId: Snowflake, roleId: Snowflake, { reason }: { reason?: string } = {}): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.GUILD_MEMBER_ROLE(this.id, memberId, roleId),
{ reason },
);
@ -506,7 +506,7 @@ export class Guild extends BaseGuild implements Model {
async moveRoles(options: ModifyRolePositions[]): Promise<Role[]> {
const roles = await this.session.rest.runMethod<DiscordRole[]>(
this.session.rest,
"PATCH",
'PATCH',
Routes.GUILD_ROLES(this.id),
options,
);
@ -517,7 +517,7 @@ export class Guild extends BaseGuild implements Model {
async deleteInvite(inviteCode: string): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.INVITE(inviteCode),
{},
);
@ -526,7 +526,7 @@ export class Guild extends BaseGuild implements Model {
async fetchInvite(inviteCode: string, options: Routes.GetInvite): Promise<Invite> {
const inviteMetadata = await this.session.rest.runMethod<DiscordInviteMetadata>(
this.session.rest,
"GET",
'GET',
Routes.INVITE(inviteCode, options),
);
@ -536,7 +536,7 @@ export class Guild extends BaseGuild implements Model {
async fetchInvites(): Promise<Invite[]> {
const invites = await this.session.rest.runMethod<DiscordInviteMetadata[]>(
this.session.rest,
"GET",
'GET',
Routes.GUILD_INVITES(this.id),
);
@ -549,7 +549,7 @@ export class Guild extends BaseGuild implements Model {
async banMember(memberId: Snowflake, options: CreateGuildBan): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"PUT",
'PUT',
Routes.GUILD_BAN(this.id, memberId),
options
? {
@ -566,7 +566,7 @@ export class Guild extends BaseGuild implements Model {
async kickMember(memberId: Snowflake, { reason }: { reason?: string }): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.GUILD_MEMBER(this.id, memberId),
{ reason },
);
@ -578,7 +578,7 @@ export class Guild extends BaseGuild implements Model {
async unbanMember(memberId: Snowflake): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.GUILD_BAN(this.id, memberId),
);
}
@ -586,7 +586,7 @@ export class Guild extends BaseGuild implements Model {
async editMember(memberId: Snowflake, options: ModifyGuildMember): Promise<Member> {
const member = await this.session.rest.runMethod<DiscordMemberWithUser>(
this.session.rest,
"PATCH",
'PATCH',
Routes.GUILD_MEMBER(this.id, memberId),
{
nick: options.nick,
@ -606,7 +606,7 @@ export class Guild extends BaseGuild implements Model {
async pruneMembers(options: BeginGuildPrune): Promise<number> {
const result = await this.session.rest.runMethod<{ pruned: number }>(
this.session.rest,
"POST",
'POST',
Routes.GUILD_PRUNE(this.id),
{
days: options.days,
@ -621,17 +621,17 @@ export class Guild extends BaseGuild implements Model {
async getPruneCount(): Promise<number> {
const result = await this.session.rest.runMethod<{ pruned: number }>(
this.session.rest,
"GET",
'GET',
Routes.GUILD_PRUNE(this.id),
);
return result.pruned;
}
async getActiveThreads(): Promise<Omit<ReturnThreadsArchive, "hasMore">> {
async getActiveThreads(): Promise<Omit<ReturnThreadsArchive, 'hasMore'>> {
const { threads, members } = await this.session.rest.runMethod<DiscordListActiveThreads>(
this.session.rest,
"GET",
'GET',
Routes.THREAD_ACTIVE(this.id),
);
@ -651,7 +651,7 @@ export class Guild extends BaseGuild implements Model {
async delete(): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.GUILDS(this.id),
);
}
@ -662,7 +662,7 @@ export class Guild extends BaseGuild implements Model {
async leave(): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"DELETE",
'DELETE',
Routes.USER_GUILDS(this.id),
);
}
@ -673,7 +673,7 @@ export class Guild extends BaseGuild implements Model {
* precondition: Bot should be in less than 10 servers
*/
static async create(session: Session, options: GuildCreateOptions): Promise<Guild> {
const guild = await session.rest.runMethod<DiscordGuild>(session.rest, "POST", Routes.GUILDS(), {
const guild = await session.rest.runMethod<DiscordGuild>(session.rest, 'POST', Routes.GUILDS(), {
name: options.name,
afk_channel_id: options.afkChannelId,
afk_timeout: options.afkTimeout,
@ -681,7 +681,7 @@ export class Guild extends BaseGuild implements Model {
explicit_content_filter: options.explicitContentFilter,
system_channel_flags: options.systemChannelFlags,
verification_level: options.verificationLevel,
icon: "iconURL" in options
icon: 'iconURL' in options
? options.iconURL && urlToBase64(options.iconURL)
: options.iconHash && Util.iconBigintToHash(options.iconHash),
channels: options.channels?.map((channel) => ({
@ -736,7 +736,7 @@ export class Guild extends BaseGuild implements Model {
* Edits a guild and returns its data
*/
async edit(options: GuildEditOptions): Promise<Guild> {
const guild = await this.session.rest.runMethod<DiscordGuild>(this.session.rest, "PATCH", Routes.GUILDS(), {
const guild = await this.session.rest.runMethod<DiscordGuild>(this.session.rest, 'PATCH', Routes.GUILDS(), {
name: options.name,
afk_channel_id: options.afkChannelId,
afk_timeout: options.afkTimeout,
@ -744,17 +744,17 @@ export class Guild extends BaseGuild implements Model {
explicit_content_filter: options.explicitContentFilter,
system_channel_flags: options.systemChannelFlags,
verification_level: options.verificationLevel,
icon: "iconURL" in options
icon: 'iconURL' in options
? options.iconURL && urlToBase64(options.iconURL)
: options.iconHash && Util.iconBigintToHash(options.iconHash),
// extra props
splash: "splashURL" in options
splash: 'splashURL' in options
? options.splashURL && urlToBase64(options.splashURL)
: options.iconHash && Util.iconBigintToHash(options.iconHash),
banner: "bannerURL" in options
banner: 'bannerURL' in options
? options.bannerURL && urlToBase64(options.bannerURL)
: options.bannerHash && Util.iconBigintToHash(options.bannerHash),
discovery_splash: "discoverySplashURL" in options
discovery_splash: 'discoverySplashURL' in options
? options.discoverySplashURL && urlToBase64(options.discoverySplashURL)
: options.discoverySplashHash && Util.iconBigintToHash(options.discoverySplashHash),
owner_id: options.ownerId,

View File

@ -1,11 +1,11 @@
import type { Model } from "../Base.ts";
import type { Snowflake } from "../../Snowflake.ts";
import type { Session } from "../../Session.ts";
import type { ApplicationCommandTypes, DiscordInteraction, InteractionTypes } from "../../../discordeno/mod.ts";
import type { ApplicationCommandOptionChoice } from "./BaseInteraction.ts";
import { InteractionResponseTypes } from "../../../discordeno/mod.ts";
import BaseInteraction from "./BaseInteraction.ts";
import * as Routes from "../../Routes.ts";
import type { Model } from '../Base.ts';
import type { Snowflake } from '../../Snowflake.ts';
import type { Session } from '../../Session.ts';
import type { ApplicationCommandTypes, DiscordInteraction, InteractionTypes } from '../../../discordeno/mod.ts';
import type { ApplicationCommandOptionChoice } from './BaseInteraction.ts';
import { InteractionResponseTypes } from '../../../discordeno/mod.ts';
import BaseInteraction from './BaseInteraction.ts';
import * as Routes from '../../Routes.ts';
export class AutoCompleteInteraction extends BaseInteraction implements Model {
constructor(session: Session, data: DiscordInteraction) {
@ -26,7 +26,7 @@ export class AutoCompleteInteraction extends BaseInteraction implements Model {
async respondWithChoices(choices: ApplicationCommandOptionChoice[]): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"POST",
'POST',
Routes.INTERACTION_ID_TOKEN(this.id, this.token),
{
data: { choices },

View File

@ -1,22 +1,22 @@
import type { Model } from "../Base.ts";
import type { Session } from "../../Session.ts";
import type { DiscordInteraction, DiscordMessage, DiscordMessageComponents } from "../../../discordeno/mod.ts";
import type CommandInteraction from "./CommandInteraction.ts";
import type PingInteraction from "./PingInteraction.ts";
import type ComponentInteraction from "./ComponentInteraction.ts";
import type ModalSubmitInteraction from "./ModalSubmitInteraction.ts";
import type AutoCompleteInteraction from "./AutoCompleteInteraction.ts";
import type { CreateMessage } from "../Message.ts";
import type { MessageFlags } from "../../Util.ts";
import type { EditWebhookMessage } from "../Webhook.ts";
import { InteractionResponseTypes, InteractionTypes } from "../../../discordeno/mod.ts";
import { Snowflake } from "../../Snowflake.ts";
import User from "../User.ts";
import Member from "../Member.ts";
import Message from "../Message.ts";
import Permsisions from "../Permissions.ts";
import Webhook from "../Webhook.ts";
import * as Routes from "../../Routes.ts";
import type { Model } from '../Base.ts';
import type { Session } from '../../Session.ts';
import type { DiscordInteraction, DiscordMessage, DiscordMessageComponents } from '../../../discordeno/mod.ts';
import type CommandInteraction from './CommandInteraction.ts';
import type PingInteraction from './PingInteraction.ts';
import type ComponentInteraction from './ComponentInteraction.ts';
import type ModalSubmitInteraction from './ModalSubmitInteraction.ts';
import type AutoCompleteInteraction from './AutoCompleteInteraction.ts';
import type { CreateMessage } from '../Message.ts';
import type { MessageFlags } from '../../Util.ts';
import type { EditWebhookMessage } from '../Webhook.ts';
import { InteractionResponseTypes, InteractionTypes } from '../../../discordeno/mod.ts';
import { Snowflake } from '../../Snowflake.ts';
import User from '../User.ts';
import Member from '../Member.ts';
import Message from '../Message.ts';
import Permsisions from '../Permissions.ts';
import Webhook from '../Webhook.ts';
import * as Routes from '../../Routes.ts';
/**
* @link https://discord.com/developers/docs/interactions/slash-commands#interaction-response
@ -30,7 +30,7 @@ export interface InteractionResponse {
* @link https://discord.com/developers/docs/interactions/slash-commands#interaction-response-interactionapplicationcommandcallbackdata
*/
export interface InteractionApplicationCommandCallbackData
extends Pick<CreateMessage, "allowedMentions" | "content" | "embeds" | "files"> {
extends Pick<CreateMessage, 'allowedMentions' | 'content' | 'embeds' | 'files'> {
customId?: string;
title?: string;
components?: DiscordMessageComponents;
@ -124,7 +124,7 @@ export abstract class BaseInteraction implements Model {
async editReply(options: EditWebhookMessage & { messageId?: Snowflake }): Promise<Message | undefined> {
const message = await this.session.rest.runMethod<DiscordMessage | undefined>(
this.session.rest,
"PATCH",
'PATCH',
options.messageId
? Routes.WEBHOOK_MESSAGE(this.id, this.token, options.messageId)
: Routes.WEBHOOK_MESSAGE_ORIGINAL(this.id, this.token),
@ -217,8 +217,8 @@ export abstract class BaseInteraction implements Model {
async respond(
resp: InteractionResponse | { with: InteractionApplicationCommandCallbackData },
): Promise<Message | undefined> {
const options = "with" in resp ? resp.with : resp.data;
const type = "type" in resp ? resp.type : InteractionResponseTypes.ChannelMessageWithSource;
const options = 'with' in resp ? resp.with : resp.data;
const type = 'type' in resp ? resp.type : InteractionResponseTypes.ChannelMessageWithSource;
const data = {
content: options?.content,
@ -235,11 +235,11 @@ export abstract class BaseInteraction implements Model {
if (!this.responded) {
await this.session.rest.sendRequest<undefined>(this.session.rest, {
url: Routes.INTERACTION_ID_TOKEN(this.id, this.token),
method: "POST",
method: 'POST',
payload: this.session.rest.createRequestBody(this.session.rest, {
method: "POST",
method: 'POST',
body: { type, data, file: options?.files },
headers: { "Authorization": "" },
headers: { 'Authorization': '' },
}),
});

View File

@ -1,19 +1,19 @@
import type { Model } from "../Base.ts";
import type { Snowflake } from "../../Snowflake.ts";
import type { Session } from "../../Session.ts";
import type { Model } from '../Base.ts';
import type { Snowflake } from '../../Snowflake.ts';
import type { Session } from '../../Session.ts';
import type {
ApplicationCommandTypes,
DiscordInteraction,
DiscordMemberWithUser,
InteractionTypes,
} from "../../../discordeno/mod.ts";
import BaseInteraction from "./BaseInteraction.ts";
import CommandInteractionOptionResolver from "./CommandInteractionOptionResolver.ts";
import Attachment from "../Attachment.ts";
import User from "../User.ts";
import Member from "../Member.ts";
import Message from "../Message.ts";
import Role from "../Role.ts";
} from '../../../discordeno/mod.ts';
import BaseInteraction from './BaseInteraction.ts';
import CommandInteractionOptionResolver from './CommandInteractionOptionResolver.ts';
import Attachment from '../Attachment.ts';
import User from '../User.ts';
import Member from '../Member.ts';
import Message from '../Message.ts';
import Role from '../Role.ts';
export class CommandInteraction extends BaseInteraction implements Model {
constructor(session: Session, data: DiscordInteraction) {

View File

@ -1,5 +1,5 @@
import type { DiscordInteractionDataOption, DiscordInteractionDataResolved } from "../../../discordeno/mod.ts";
import { ApplicationCommandOptionTypes } from "../../../discordeno/mod.ts";
import type { DiscordInteractionDataOption, DiscordInteractionDataResolved } from '../../../discordeno/mod.ts';
import { ApplicationCommandOptionTypes } from '../../../discordeno/mod.ts';
export function transformOasisInteractionDataOption(o: DiscordInteractionDataOption): CommandInteractionOption {
const output: CommandInteractionOption = { ...o, Otherwise: o.value as string | boolean | number | undefined };
@ -37,7 +37,7 @@ export function transformOasisInteractionDataOption(o: DiscordInteractionDataOpt
return output;
}
export interface CommandInteractionOption extends Omit<DiscordInteractionDataOption, "value"> {
export interface CommandInteractionOption extends Omit<DiscordInteractionDataOption, 'value'> {
Attachment?: string;
Boolean?: boolean;
User?: bigint;
@ -96,8 +96,8 @@ export class CommandInteractionOptionResolver {
// pass
}
if (required === true && properties.every((prop) => typeof option[prop] === "undefined")) {
throw new TypeError(`Properties ${properties.join(", ")} are missing in option ${name}`);
if (required === true && properties.every((prop) => typeof option[prop] === 'undefined')) {
throw new TypeError(`Properties ${properties.join(', ')} are missing in option ${name}`);
}
return option;
@ -107,12 +107,12 @@ export class CommandInteractionOptionResolver {
get(name: string | number, required: boolean): CommandInteractionOption | undefined;
get(name: string | number, required?: boolean) {
const option: CommandInteractionOption | undefined = this.hoistedOptions.find((o) =>
typeof name === "number" ? o.name === name.toString() : o.name === name
typeof name === 'number' ? o.name === name.toString() : o.name === name
);
if (!option) {
if (required && name in this.hoistedOptions.map((o) => o.name)) {
throw new TypeError("Option marked as required was undefined");
throw new TypeError('Option marked as required was undefined');
}
return;
@ -128,7 +128,7 @@ export class CommandInteractionOptionResolver {
const option: CommandInteractionOption | void = this.getTypedOption(
name,
ApplicationCommandOptionTypes.String,
["Otherwise"],
['Otherwise'],
required,
);
@ -142,7 +142,7 @@ export class CommandInteractionOptionResolver {
const option: CommandInteractionOption | void = this.getTypedOption(
name,
ApplicationCommandOptionTypes.Number,
["Otherwise"],
['Otherwise'],
required,
);
@ -156,7 +156,7 @@ export class CommandInteractionOptionResolver {
const option: CommandInteractionOption | void = this.getTypedOption(
name,
ApplicationCommandOptionTypes.Integer,
["Otherwise"],
['Otherwise'],
required,
);
@ -170,7 +170,7 @@ export class CommandInteractionOptionResolver {
const option: CommandInteractionOption | void = this.getTypedOption(
name,
ApplicationCommandOptionTypes.Boolean,
["Otherwise"],
['Otherwise'],
required,
);
@ -182,7 +182,7 @@ export class CommandInteractionOptionResolver {
getUser(name: string | number, required?: boolean): bigint | undefined;
getUser(name: string | number, required = false) {
const option: CommandInteractionOption | void = this.getTypedOption(name, ApplicationCommandOptionTypes.User, [
"Otherwise",
'Otherwise',
], required);
return option?.Otherwise ?? undefined;
@ -195,7 +195,7 @@ export class CommandInteractionOptionResolver {
const option: CommandInteractionOption | void = this.getTypedOption(
name,
ApplicationCommandOptionTypes.Channel,
["Otherwise"],
['Otherwise'],
required,
);
@ -209,7 +209,7 @@ export class CommandInteractionOptionResolver {
const option: CommandInteractionOption | void = this.getTypedOption(
name,
ApplicationCommandOptionTypes.Mentionable,
["Otherwise"],
['Otherwise'],
required,
);
@ -221,7 +221,7 @@ export class CommandInteractionOptionResolver {
getRole(name: string | number, required?: boolean): bigint | undefined;
getRole(name: string | number, required = false) {
const option: CommandInteractionOption | void = this.getTypedOption(name, ApplicationCommandOptionTypes.Role, [
"Otherwise",
'Otherwise',
], required);
return option?.Otherwise ?? undefined;
@ -234,7 +234,7 @@ export class CommandInteractionOptionResolver {
const option: CommandInteractionOption | void = this.getTypedOption(
name,
ApplicationCommandOptionTypes.Attachment,
["Otherwise"],
['Otherwise'],
required,
);
@ -246,7 +246,7 @@ export class CommandInteractionOptionResolver {
const focusedOption: CommandInteractionOption | void = this.hoistedOptions.find((option) => option.focused);
if (!focusedOption) {
throw new TypeError("No option found");
throw new TypeError('No option found');
}
return full ? focusedOption : focusedOption.Otherwise;
@ -254,7 +254,7 @@ export class CommandInteractionOptionResolver {
getSubCommand(required = true): (string | CommandInteractionOption[] | undefined)[] {
if (required && !this.#subcommand) {
throw new TypeError("Option marked as required was undefined");
throw new TypeError('Option marked as required was undefined');
}
return [this.#subcommand, this.hoistedOptions];
@ -262,7 +262,7 @@ export class CommandInteractionOptionResolver {
getSubCommandGroup(required = false): (string | CommandInteractionOption[] | undefined)[] {
if (required && !this.#group) {
throw new TypeError("Option marked as required was undefined");
throw new TypeError('Option marked as required was undefined');
}
return [this.#group, this.hoistedOptions];

View File

@ -1,10 +1,10 @@
import type { Model } from "../Base.ts";
import type { Snowflake } from "../../Snowflake.ts";
import type { Session } from "../../Session.ts";
import type { DiscordInteraction, InteractionTypes } from "../../../discordeno/mod.ts";
import { InteractionResponseTypes, MessageComponentTypes } from "../../../discordeno/mod.ts";
import BaseInteraction from "./BaseInteraction.ts";
import Message from "../Message.ts";
import type { Model } from '../Base.ts';
import type { Snowflake } from '../../Snowflake.ts';
import type { Session } from '../../Session.ts';
import type { DiscordInteraction, InteractionTypes } from '../../../discordeno/mod.ts';
import { InteractionResponseTypes, MessageComponentTypes } from '../../../discordeno/mod.ts';
import BaseInteraction from './BaseInteraction.ts';
import Message from '../Message.ts';
export class ComponentInteraction extends BaseInteraction implements Model {
constructor(session: Session, data: DiscordInteraction) {

View File

@ -1,14 +1,14 @@
import type { Session } from "../../Session.ts";
import type { Snowflake } from "../../Snowflake.ts";
import type { DiscordInteraction, DiscordMessageInteraction } from "../../../discordeno/mod.ts";
import { InteractionTypes } from "../../../discordeno/mod.ts";
import User from "../User.ts";
import Member from "../Member.ts";
import CommandInteraction from "./CommandInteraction.ts";
import ComponentInteraction from "./ComponentInteraction.ts";
import PingInteraction from "./PingInteraction.ts";
import AutoCompleteInteraction from "./AutoCompleteInteraction.ts";
import ModalSubmitInteraction from "./ModalSubmitInteraction.ts";
import type { Session } from '../../Session.ts';
import type { Snowflake } from '../../Snowflake.ts';
import type { DiscordInteraction, DiscordMessageInteraction } from '../../../discordeno/mod.ts';
import { InteractionTypes } from '../../../discordeno/mod.ts';
import User from '../User.ts';
import Member from '../Member.ts';
import CommandInteraction from './CommandInteraction.ts';
import ComponentInteraction from './ComponentInteraction.ts';
import PingInteraction from './PingInteraction.ts';
import AutoCompleteInteraction from './AutoCompleteInteraction.ts';
import ModalSubmitInteraction from './ModalSubmitInteraction.ts';
/**
* @link https://discord.com/developers/docs/interactions/receiving-and-responding#message-interaction-object-message-interaction-structure

View File

@ -1,14 +1,14 @@
import type { Model } from "../Base.ts";
import type { Snowflake } from "../../Snowflake.ts";
import type { Session } from "../../Session.ts";
import type { Model } from '../Base.ts';
import type { Snowflake } from '../../Snowflake.ts';
import type { Session } from '../../Session.ts';
import type {
DiscordInteraction,
DiscordMessageComponents,
InteractionTypes,
MessageComponentTypes,
} from "../../../discordeno/mod.ts";
import BaseInteraction from "./BaseInteraction.ts";
import Message from "../Message.ts";
} from '../../../discordeno/mod.ts';
import BaseInteraction from './BaseInteraction.ts';
import Message from '../Message.ts';
export class ModalSubmitInteraction extends BaseInteraction implements Model {
constructor(session: Session, data: DiscordInteraction) {

View File

@ -1,10 +1,10 @@
import type { Model } from "../Base.ts";
import type { Snowflake } from "../../Snowflake.ts";
import type { Session } from "../../Session.ts";
import type { ApplicationCommandTypes, DiscordInteraction, InteractionTypes } from "../../../discordeno/mod.ts";
import { InteractionResponseTypes } from "../../../discordeno/mod.ts";
import BaseInteraction from "./BaseInteraction.ts";
import * as Routes from "../../Routes.ts";
import type { Model } from '../Base.ts';
import type { Snowflake } from '../../Snowflake.ts';
import type { Session } from '../../Session.ts';
import type { ApplicationCommandTypes, DiscordInteraction, InteractionTypes } from '../../../discordeno/mod.ts';
import { InteractionResponseTypes } from '../../../discordeno/mod.ts';
import BaseInteraction from './BaseInteraction.ts';
import * as Routes from '../../Routes.ts';
export class PingInteraction extends BaseInteraction implements Model {
constructor(session: Session, data: DiscordInteraction) {
@ -25,7 +25,7 @@ export class PingInteraction extends BaseInteraction implements Model {
async pong(): Promise<void> {
await this.session.rest.runMethod<undefined>(
this.session.rest,
"POST",
'POST',
Routes.INTERACTION_ID_TOKEN(this.id, this.token),
{
type: InteractionResponseTypes.Pong,

View File

@ -2,7 +2,7 @@
export async function urlToBase64(url: string): Promise<string> {
const buffer = await fetch(url).then((res) => res.arrayBuffer());
const imageStr = encode(buffer);
const type = url.substring(url.lastIndexOf(".") + 1);
const type = url.substring(url.lastIndexOf('.') + 1);
return `data:image/${type};base64,${imageStr}`;
}
@ -38,12 +38,12 @@ const base64abc: string[] = [
* @param data
*/
export function encode(data: ArrayBuffer | string): string {
const uint8: Uint8Array = typeof data === "string"
const uint8: Uint8Array = typeof data === 'string'
? new TextEncoder().encode(data)
: data instanceof Uint8Array
? data
: new Uint8Array(data);
let result = "",
let result = '',
i;
const l: number = uint8.length;
for (i = 2; i < l; i += 3) {
@ -56,14 +56,14 @@ export function encode(data: ArrayBuffer | string): string {
// 1 octet yet to write
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[(uint8[i - 2] & 0x03) << 4];
result += "==";
result += '==';
}
if (i === l) {
// 2 octets yet to write
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
result += base64abc[(uint8[i - 1] & 0x0f) << 2];
result += "=";
result += '=';
}
return result;
}

View File

@ -1,4 +1,4 @@
import type { Session, Snowflake } from "./deps.ts";
import type { Session, Snowflake } from './deps.ts';
export class Collection<V> extends Map<Snowflake, V> {
constructor(session: Session, entries?: Iterable<readonly [Snowflake, V]>) {
@ -28,7 +28,7 @@ export class Collection<V> extends Map<Snowflake, V> {
random(amount: number): V[];
random(amount?: number): V | V[] | undefined {
const arr = [...this.values()];
if (typeof amount === "undefined") return arr[Math.floor(Math.random() * arr.length)];
if (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length) return [];
if (amount && amount > arr.length) amount = arr.length;
return Array.from(

View File

@ -1,18 +1,18 @@
import type { ChannelInGuild, ChannelTypes, ChannelWithMessagesInGuild, DiscordChannel, Snowflake } from "./deps.ts";
import type { CachedMessage } from "./messages.ts";
import type { CachedGuild } from "./guilds.ts";
import type { SessionCache } from "./mod.ts";
import { Collection } from "./Collection.ts";
import { ChannelFactory, DMChannel, textBasedChannels } from "./deps.ts";
import type { ChannelInGuild, ChannelTypes, ChannelWithMessagesInGuild, DiscordChannel, Snowflake } from './deps.ts';
import type { CachedMessage } from './messages.ts';
import type { CachedGuild } from './guilds.ts';
import type { SessionCache } from './mod.ts';
import { Collection } from './Collection.ts';
import { ChannelFactory, DMChannel, textBasedChannels } from './deps.ts';
export interface CachedGuildChannel extends Omit<ChannelWithMessagesInGuild, "type"> {
export interface CachedGuildChannel extends Omit<ChannelWithMessagesInGuild, 'type'> {
type: ChannelTypes;
messages: Collection<CachedMessage>;
guild: CachedGuild;
guildId: Snowflake;
}
export interface CachedGuildChannel extends Omit<ChannelInGuild, "type"> {
export interface CachedGuildChannel extends Omit<ChannelInGuild, 'type'> {
type: ChannelTypes;
guild: CachedGuild;
guildId: Snowflake;

View File

@ -1,2 +1,2 @@
export * from "../biscuit/mod.ts";
export * from "../discordeno/mod.ts";
export * from '../biscuit/mod.ts';
export * from '../discordeno/mod.ts';

View File

@ -1,12 +1,12 @@
import type { DiscordGuild, DiscordMemberWithUser } from "./deps.ts";
import type { SessionCache } from "./mod.ts";
import type { CachedMember } from "./members.ts";
import type { CachedUser } from "./users.ts";
import type { CachedGuildChannel } from "./channels.ts";
import { ChannelFactory, Guild, Member } from "./deps.ts";
import { Collection } from "./Collection.ts";
import type { DiscordGuild, DiscordMemberWithUser } from './deps.ts';
import type { SessionCache } from './mod.ts';
import type { CachedMember } from './members.ts';
import type { CachedUser } from './users.ts';
import type { CachedGuildChannel } from './channels.ts';
import { ChannelFactory, Guild, Member } from './deps.ts';
import { Collection } from './Collection.ts';
export interface CachedGuild extends Omit<Guild, "members" | "channels"> {
export interface CachedGuild extends Omit<Guild, 'members' | 'channels'> {
channels: Collection<CachedGuildChannel>;
members: Collection<CachedMember>;
}

View File

@ -1,9 +1,9 @@
import type { DiscordMemberWithUser, Snowflake } from "./deps.ts";
import type { SessionCache } from "./mod.ts";
import type { CachedUser } from "./users.ts";
import { Member } from "./deps.ts";
import type { DiscordMemberWithUser, Snowflake } from './deps.ts';
import type { SessionCache } from './mod.ts';
import type { CachedUser } from './users.ts';
import { Member } from './deps.ts';
export interface CachedMember extends Omit<Member, "user"> {
export interface CachedMember extends Omit<Member, 'user'> {
userId: Snowflake;
user?: CachedUser;
}

View File

@ -6,13 +6,13 @@ import type {
DiscordMessageReactionRemove,
DiscordMessageReactionRemoveAll,
Snowflake,
} from "./deps.ts";
import type { CachedUser } from "./users.ts";
import type { SessionCache } from "./mod.ts";
import { Emoji, GuildEmoji, Message, MessageReaction } from "./deps.ts";
import { memberBootstrapper } from "./members.ts";
} from './deps.ts';
import type { CachedUser } from './users.ts';
import type { SessionCache } from './mod.ts';
import { Emoji, GuildEmoji, Message, MessageReaction } from './deps.ts';
import { memberBootstrapper } from './members.ts';
export interface CachedMessage extends Omit<Message, "author"> {
export interface CachedMessage extends Omit<Message, 'author'> {
authorId: Snowflake;
author?: CachedUser;
}
@ -27,7 +27,7 @@ export function messageBootstrapper(cache: SessionCache, message: DiscordMessage
if (cache.dms.has(message.channel_id)) {
// is dm
cache.dms.retrieve(message.channel_id, (dm) => {
dm.messages[partial ? "updateFields" : "set"](
dm.messages[partial ? 'updateFields' : 'set'](
message.id,
Object.assign(
new Message(cache.session, message),
@ -44,7 +44,7 @@ export function messageBootstrapper(cache: SessionCache, message: DiscordMessage
// is not dm
cache.guilds.retrieve(message.guild_id!, (guild) =>
guild.channels.retrieve(message.channel_id, (dm) => {
dm.messages[partial ? "updateFields" : "set"](
dm.messages[partial ? 'updateFields' : 'set'](
message.id,
Object.assign(
new Message(cache.session, message),

46
packages/cache/mod.ts vendored
View File

@ -1,15 +1,15 @@
import type { Emoji, Session, SymCache } from "./deps.ts";
import type { CachedGuild } from "./guilds.ts";
import type { CachedUser } from "./users.ts";
import type { CachedDMChannel } from "./channels.ts";
import { Collection } from "./Collection.ts";
import { memberBootstrapper } from "./members.ts";
import { userBootstrapper } from "./users.ts";
import { channelBootstrapper } from "./channels.ts";
import { guildBootstrapper } from "./guilds.ts";
import { messageBootstrapper, reactionBootstrapper, reactionBootstrapperDeletions } from "./messages.ts";
import type { Emoji, Session, SymCache } from './deps.ts';
import type { CachedGuild } from './guilds.ts';
import type { CachedUser } from './users.ts';
import type { CachedDMChannel } from './channels.ts';
import { Collection } from './Collection.ts';
import { memberBootstrapper } from './members.ts';
import { userBootstrapper } from './users.ts';
import { channelBootstrapper } from './channels.ts';
import { guildBootstrapper } from './guilds.ts';
import { messageBootstrapper, reactionBootstrapper, reactionBootstrapperDeletions } from './messages.ts';
export const cache_sym = Symbol("@cache");
export const cache_sym = Symbol('@cache');
export interface SessionCache extends SymCache {
guilds: Collection<CachedGuild>;
@ -29,7 +29,7 @@ export function enableCache(session: Session): SessionCache {
session,
};
session.on("raw", (data) => {
session.on('raw', (data) => {
// deno-lint-ignore no-explicit-any
const raw = data.d as any;
@ -38,38 +38,38 @@ export function enableCache(session: Session): SessionCache {
switch (data.t) {
// TODO: add more events
// for now users have to use the bootstrappers that are not implemented yet
case "MESSAGE_CREATE":
case 'MESSAGE_CREATE':
messageBootstrapper(cache, raw, false);
break;
case "MESSAGE_UPDATE":
case 'MESSAGE_UPDATE':
messageBootstrapper(cache, raw, !raw.edited_timestamp);
break;
case "CHANNEL_CREATE":
case 'CHANNEL_CREATE':
channelBootstrapper(cache, raw);
break;
case "GUILD_MEMBER_ADD":
case 'GUILD_MEMBER_ADD':
memberBootstrapper(cache, raw, raw.guild_id);
break;
case "GUILD_CREATE":
case 'GUILD_CREATE':
guildBootstrapper(cache, raw);
break;
case "GUILD_DELETE":
case 'GUILD_DELETE':
cache.guilds.delete(raw.id);
break;
case "MESSAGE_REACTION_ADD":
case 'MESSAGE_REACTION_ADD':
reactionBootstrapper(cache, raw, false);
break;
case "MESSAGE_REACTION_REMOVE":
case 'MESSAGE_REACTION_REMOVE':
reactionBootstrapper(cache, raw, false);
break;
case "MESSAGE_REACTION_REMOVE_ALL":
case 'MESSAGE_REACTION_REMOVE_ALL':
reactionBootstrapperDeletions(cache, raw);
break;
case "READY":
case 'READY':
userBootstrapper(cache, raw.user);
break;
default:
session.emit("debug", `NOT CACHED: ${JSON.stringify(raw)}`);
session.emit('debug', `NOT CACHED: ${JSON.stringify(raw)}`);
}
});

View File

@ -1,6 +1,6 @@
import type { DiscordUser } from "./deps.ts";
import type { SessionCache } from "./mod.ts";
import { User } from "./deps.ts";
import type { DiscordUser } from './deps.ts';
import type { SessionCache } from './mod.ts';
import { User } from './deps.ts';
export type CachedUser = User;

View File

@ -1,4 +1,4 @@
import { GatewayManager } from "./manager/gatewayManager.ts";
import { GatewayManager } from './manager/gatewayManager.ts';
export function calculateShardId(gateway: GatewayManager, guildId: bigint) {
if (gateway.manager.totalShards === 1) return 0;

View File

@ -1,4 +1,4 @@
import { GatewayManager } from "./gatewayManager.ts";
import { GatewayManager } from './gatewayManager.ts';
/** Handler used to determine max number of shards to use based upon the max concurrency. */
export function calculateTotalShards(gateway: GatewayManager): number {

View File

@ -1,4 +1,4 @@
import { GatewayManager } from "./gatewayManager.ts";
import { GatewayManager } from './gatewayManager.ts';
export function calculateWorkerId(manager: GatewayManager, shardId: number) {
// Ignore decimal numbers.

View File

@ -1,10 +1,10 @@
import { DiscordGatewayPayload } from "../../types/discord.ts";
import { GatewayBot, PickPartial } from "../../types/shared.ts";
import { LeakyBucket } from "../../util/bucket.ts";
import { CreateShard, createShard } from "../shard/createShard.ts";
import { Shard, ShardGatewayConfig } from "../shard/types.ts";
import { calculateTotalShards } from "./calculateTotalShards.ts";
import { calculateWorkerId } from "./calculateWorkerId.ts";
import { DiscordGatewayPayload } from '../../types/discord.ts';
import { GatewayBot, PickPartial } from '../../types/shared.ts';
import { LeakyBucket } from '../../util/bucket.ts';
import { CreateShard, createShard } from '../shard/createShard.ts';
import { Shard, ShardGatewayConfig } from '../shard/types.ts';
import { calculateTotalShards } from './calculateTotalShards.ts';
import { calculateWorkerId } from './calculateWorkerId.ts';
// import {
// markNewGuildShardId,
// resharder,
@ -12,11 +12,11 @@ import { calculateWorkerId } from "./calculateWorkerId.ts";
// resharderIsPending,
// reshardingEditGuildShardIds,
// } from "./resharder.ts";
import { spawnShards } from "./spawnShards.ts";
import { prepareBuckets } from "./prepareBuckets.ts";
import { tellWorkerToIdentify } from "./tellWorkerToIdentify.ts";
import { createShardManager, ShardManager } from "./shardManager.ts";
import { stop } from "./stop.ts";
import { spawnShards } from './spawnShards.ts';
import { prepareBuckets } from './prepareBuckets.ts';
import { tellWorkerToIdentify } from './tellWorkerToIdentify.ts';
import { createShardManager, ShardManager } from './shardManager.ts';
import { stop } from './stop.ts';
export type GatewayManager = ReturnType<typeof createGatewayManager>;
@ -27,7 +27,7 @@ export type GatewayManager = ReturnType<typeof createGatewayManager>;
* bots.
*/
export function createGatewayManager(
options: PickPartial<CreateGatewayManager, "handleDiscordPayload" | "gatewayBot" | "gatewayConfig">,
options: PickPartial<CreateGatewayManager, 'handleDiscordPayload' | 'gatewayBot' | 'gatewayConfig'>,
) {
const prepareBucketsOverwritten = options.prepareBuckets ?? prepareBuckets;
const spawnShardsOverwritten = options.spawnShards ?? spawnShards;
@ -222,10 +222,10 @@ export interface CreateGatewayManager {
/** Important data which is used by the manager to connect shards to the gateway. */
gatewayBot: GatewayBot;
gatewayConfig: PickPartial<ShardGatewayConfig, "token">;
gatewayConfig: PickPartial<ShardGatewayConfig, 'token'>;
/** Options which are used to create a new shard. */
createShardOptions?: Omit<CreateShard, "id" | "totalShards" | "requestIdentify" | "gatewayConfig">;
createShardOptions?: Omit<CreateShard, 'id' | 'totalShards' | 'requestIdentify' | 'gatewayConfig'>;
/** Stored as bucketId: { workers: [workerId, [ShardIds]], createNextShard: boolean } */
buckets: Map<
@ -276,19 +276,19 @@ export interface CreateGatewayManager {
}
export type GatewayDebugEvents =
| "GW ERROR"
| "GW CLOSED"
| "GW CLOSED_RECONNECT"
| "GW RAW"
| "GW RECONNECT"
| "GW INVALID_SESSION"
| "GW RESUMED"
| "GW RESUMING"
| "GW IDENTIFYING"
| "GW RAW_SEND"
| "GW MAX REQUESTS"
| "GW DEBUG"
| "GW HEARTBEATING"
| "GW HEARTBEATING_STARTED"
| "GW HEARTBEATING_DETAILS"
| "GW HEARTBEATING_CLOSED";
| 'GW ERROR'
| 'GW CLOSED'
| 'GW CLOSED_RECONNECT'
| 'GW RAW'
| 'GW RECONNECT'
| 'GW INVALID_SESSION'
| 'GW RESUMED'
| 'GW RESUMING'
| 'GW IDENTIFYING'
| 'GW RAW_SEND'
| 'GW MAX REQUESTS'
| 'GW DEBUG'
| 'GW HEARTBEATING'
| 'GW HEARTBEATING_STARTED'
| 'GW HEARTBEATING_DETAILS'
| 'GW HEARTBEATING_CLOSED';

View File

@ -1,8 +1,8 @@
export * from "./calculateTotalShards.ts";
export * from "./calculateWorkerId.ts";
export * from "./gatewayManager.ts";
export * from "./prepareBuckets.ts";
export * from "./shardManager.ts";
export * from "./spawnShards.ts";
export * from "./stop.ts";
export * from "./tellWorkerToIdentify.ts";
export * from './calculateTotalShards.ts';
export * from './calculateWorkerId.ts';
export * from './gatewayManager.ts';
export * from './prepareBuckets.ts';
export * from './shardManager.ts';
export * from './spawnShards.ts';
export * from './stop.ts';
export * from './tellWorkerToIdentify.ts';

View File

@ -1,5 +1,5 @@
import { createLeakyBucket } from "../../util/bucket.ts";
import { GatewayManager } from "./gatewayManager.ts";
import { createLeakyBucket } from '../../util/bucket.ts';
import { GatewayManager } from './gatewayManager.ts';
export function prepareBuckets(gateway: GatewayManager) {
for (let i = 0; i < gateway.gatewayBot.sessionStartLimit.maxConcurrency; ++i) {

View File

@ -1,5 +1,5 @@
import { GatewayBot } from "../../types/shared.ts";
import { createGatewayManager, GatewayManager } from "./gatewayManager.ts";
import { GatewayBot } from '../../types/shared.ts';
import { createGatewayManager, GatewayManager } from './gatewayManager.ts';
export type Resharder = ReturnType<typeof activateResharder>;
@ -118,7 +118,7 @@ export interface ActivateResharderOptions {
/** Handler that by default will check to see if resharding should occur. Can be overridden if you have multiple servers and you want to communicate through redis pubsub or whatever you prefer. */
export function activate(resharder: Resharder): void {
if (resharder.intervalId !== undefined) {
throw new Error("[RESHARDER] Cannot activate the resharder more than one time.");
throw new Error('[RESHARDER] Cannot activate the resharder more than one time.');
}
resharder.intervalId = setInterval(async () => {
@ -173,7 +173,7 @@ export async function reshard(resharder: Resharder, gatewayBot: GatewayBot) {
gateway.handleDiscordPayload = oldHandler;
oldGateway.handleDiscordPayload = function (og, data, shardId) {
// ALLOW EXCEPTION FOR CHUNKING TO PREVENT REQUESTS FREEZING
if (data.t !== "GUILD_MEMBERS_CHUNK") return;
if (data.t !== 'GUILD_MEMBERS_CHUNK') return;
oldHandler(og, data, shardId);
};
@ -181,7 +181,7 @@ export async function reshard(resharder: Resharder, gatewayBot: GatewayBot) {
clearInterval(timer);
await gateway.resharding.editGuildShardIds();
await gateway.resharding.closeOldShards(oldGateway);
gateway.debug("GW DEBUG", "[Resharding] Complete.");
gateway.debug('GW DEBUG', '[Resharding] Complete.');
resolve(gateway);
}, 30000);
}) as Promise<GatewayManager>;
@ -291,7 +291,7 @@ export async function resharderCloseOldShards(oldGateway: GatewayManager) {
return oldGateway.closeWS(
shard.ws,
3066,
"Shard has been resharded. Closing shard since it has no queue.",
'Shard has been resharded. Closing shard since it has no queue.',
);
}
@ -300,7 +300,7 @@ export async function resharderCloseOldShards(oldGateway: GatewayManager) {
oldGateway.closeWS(
shard.ws,
3066,
"Shard has been resharded. Delayed closing shard since it had a queue.",
'Shard has been resharded. Delayed closing shard since it had a queue.',
);
}, 300000);
});

View File

@ -1,7 +1,7 @@
import { DiscordGatewayPayload } from "../../types/discord.ts";
import { PickPartial } from "../../types/shared.ts";
import { CreateShard, createShard } from "../shard/createShard.ts";
import { Shard, ShardGatewayConfig } from "../shard/types.ts";
import { DiscordGatewayPayload } from '../../types/discord.ts';
import { PickPartial } from '../../types/shared.ts';
import { CreateShard, createShard } from '../shard/createShard.ts';
import { Shard, ShardGatewayConfig } from '../shard/types.ts';
// TODO: debug
@ -100,9 +100,9 @@ export interface CreateShardManager {
// PROPERTIES
// ----------
/** Options which are used to create a new Shard. */
createShardOptions?: Omit<CreateShard, "id" | "totalShards" | "requestIdentify" | "gatewayConfig">;
createShardOptions?: Omit<CreateShard, 'id' | 'totalShards' | 'requestIdentify' | 'gatewayConfig'>;
/** Gateway configuration which is used when creating a Shard. */
gatewayConfig: PickPartial<ShardGatewayConfig, "token">;
gatewayConfig: PickPartial<ShardGatewayConfig, 'token'>;
/** Ids of the Shards which should be managed. */
shardIds: number[];
/** Total amount of Shard used by the bot. */

View File

@ -1,8 +1,8 @@
import { GatewayIntents } from "../../types/shared.ts";
import { createLeakyBucket } from "../../util/bucket.ts";
import { createShard } from "../shard/createShard.ts";
import { Shard } from "../shard/types.ts";
import { createGatewayManager, GatewayManager } from "./gatewayManager.ts";
import { GatewayIntents } from '../../types/shared.ts';
import { createLeakyBucket } from '../../util/bucket.ts';
import { createShard } from '../shard/createShard.ts';
import { Shard } from '../shard/types.ts';
import { createGatewayManager, GatewayManager } from './gatewayManager.ts';
/** Begin spawning shards. */
export function spawnShards(gateway: GatewayManager) {

View File

@ -1,5 +1,5 @@
import { delay } from "../../util/delay.ts";
import { GatewayManager } from "./gatewayManager.ts";
import { delay } from '../../util/delay.ts';
import { GatewayManager } from './gatewayManager.ts';
export async function stop(gateway: GatewayManager, code: number, reason: string) {
gateway.manager.shards.forEach((shard) => shard.close(code, reason));

View File

@ -1,6 +1,6 @@
import { GatewayIntents } from "../../types/shared.ts";
import { createShard } from "../shard/createShard.ts";
import { GatewayManager } from "./gatewayManager.ts";
import { GatewayIntents } from '../../types/shared.ts';
import { createShard } from '../shard/createShard.ts';
import { GatewayManager } from './gatewayManager.ts';
/** Allows users to hook in and change to communicate to different workers across different servers or anything they like. For example using redis pubsub to talk to other servers. */
export async function tellWorkerToIdentify(

View File

@ -1,2 +1,2 @@
export * from "./manager/mod.ts";
export * from "./shard/mod.ts";
export * from './manager/mod.ts';
export * from './shard/mod.ts';

View File

@ -1,4 +1,4 @@
import { Shard } from "./types.ts";
import { Shard } from './types.ts';
export function calculateSafeRequests(shard: Shard) {
// * 2 adds extra safety layer for discords OP 1 requests that we need to respond to

View File

@ -1,4 +1,4 @@
import { Shard } from "./types.ts";
import { Shard } from './types.ts';
export function close(shard: Shard, code: number, reason: string): void {
if (shard.socket?.readyState !== WebSocket.OPEN) return;

View File

@ -1,4 +1,4 @@
import { Shard, ShardState } from "./types.ts";
import { Shard, ShardState } from './types.ts';
// TODO: Remove code marked WSL GATEWAY PATCH once a bug in bun is fixed:
// `https://github.com/Jarred-Sumner/bun/issues/521`

View File

@ -1,5 +1,5 @@
import { identify } from "./identify.ts";
import { handleMessage } from "./handleMessage.ts";
import { identify } from './identify.ts';
import { handleMessage } from './handleMessage.ts';
import {
DEFAULT_HEARTBEAT_INTERVAL,
GATEWAY_RATE_LIMIT_RESET_INTERVAL,
@ -11,21 +11,21 @@ import {
ShardSocketCloseCodes,
ShardSocketRequest,
ShardState,
} from "./types.ts";
import { startHeartbeating } from "./startHeartbeating.ts";
import { stopHeartbeating } from "./stopHeartbeating.ts";
import { resume } from "./resume.ts";
import { createLeakyBucket, LeakyBucket } from "../../util/bucket.ts";
import { calculateSafeRequests } from "./calculateSafeRequests.ts";
import { send } from "./send.ts";
import { handleClose } from "./handleClose.ts";
import { connect } from "./connect.ts";
import { close } from "./close.ts";
import { shutdown } from "./shutdown.ts";
import { isOpen } from "./isOpen.ts";
import { DiscordGatewayPayload, DiscordStatusUpdate } from "../../types/discord.ts";
import { GatewayIntents, PickPartial } from "../../types/shared.ts";
import { API_VERSION } from "../../util/constants.ts";
} from './types.ts';
import { startHeartbeating } from './startHeartbeating.ts';
import { stopHeartbeating } from './stopHeartbeating.ts';
import { resume } from './resume.ts';
import { createLeakyBucket, LeakyBucket } from '../../util/bucket.ts';
import { calculateSafeRequests } from './calculateSafeRequests.ts';
import { send } from './send.ts';
import { handleClose } from './handleClose.ts';
import { connect } from './connect.ts';
import { close } from './close.ts';
import { shutdown } from './shutdown.ts';
import { isOpen } from './isOpen.ts';
import { DiscordGatewayPayload, DiscordStatusUpdate } from '../../types/discord.ts';
import { GatewayIntents, PickPartial } from '../../types/shared.ts';
import { API_VERSION } from '../../util/constants.ts';
// TODO: debug
// TODO: function overwrite
@ -59,12 +59,12 @@ export function createShard(
compress: options.gatewayConfig.compress ?? false,
intents: options.gatewayConfig.intents ?? 0,
properties: {
os: options.gatewayConfig?.properties?.os ?? "linux",
browser: options.gatewayConfig?.properties?.browser ?? "Discordeno",
device: options.gatewayConfig?.properties?.device ?? "Discordeno",
os: options.gatewayConfig?.properties?.os ?? 'linux',
browser: options.gatewayConfig?.properties?.browser ?? 'Discordeno',
device: options.gatewayConfig?.properties?.device ?? 'Discordeno',
},
token: options.gatewayConfig.token,
url: options.gatewayConfig.url ?? "wss://gateway.discord.gg",
url: options.gatewayConfig.url ?? 'wss://gateway.discord.gg',
version: options.gatewayConfig.version ?? API_VERSION,
} as ShardGatewayConfig,
/** This contains all the heartbeat information */
@ -201,7 +201,7 @@ export function createShard(
* This is used to resolve internal waiting states.
* Mapped by SelectedEvents => ResolveFunction
*/
resolves: new Map<"READY" | "RESUMED" | "INVALID_SESSION", (payload: DiscordGatewayPayload) => void>(),
resolves: new Map<'READY' | 'RESUMED' | 'INVALID_SESSION', (payload: DiscordGatewayPayload) => void>(),
/** @private Internal shard function.
* Only use this function if you know what you are doing.
@ -228,7 +228,7 @@ export interface CreateShard {
id: number;
/** Gateway configuration for the shard. */
gatewayConfig: PickPartial<ShardGatewayConfig, "token">;
gatewayConfig: PickPartial<ShardGatewayConfig, 'token'>;
/** The total amount of shards which are used to communicate with Discord. */
totalShards: number;
@ -329,5 +329,5 @@ export interface CreateShard {
/** This is used to resolve internal waiting states.
* Mapped by SelectedEvents => ResolveFunction
*/
resolves?: Shard["resolves"];
resolves?: Shard['resolves'];
}

View File

@ -1 +1 @@
export { inflate as decompressWith } from "../../zlib.js";
export { inflate as decompressWith } from '../../zlib.js';

View File

@ -1,5 +1,5 @@
import { GatewayCloseEventCodes } from "../../types/shared.ts";
import { Shard, ShardSocketCloseCodes, ShardState } from "./types.ts";
import { GatewayCloseEventCodes } from '../../types/shared.ts';
import { Shard, ShardSocketCloseCodes, ShardState } from './types.ts';
export async function handleClose(shard: Shard, close: CloseEvent): Promise<void> {
// gateway.debug("GW CLOSED", { shardId, payload: event });
@ -47,7 +47,7 @@ export async function handleClose(shard: Shard, close: CloseEvent): Promise<void
shard.state = ShardState.Offline;
shard.events.disconnected?.(shard);
throw new Error(close.reason || "Discord gave no reason! GG! You broke Discord!");
throw new Error(close.reason || 'Discord gave no reason! GG! You broke Discord!');
}
// Gateway connection closes on which a resume is allowed.
case GatewayCloseEventCodes.UnknownError:

View File

@ -1,9 +1,9 @@
import { DiscordGatewayPayload, DiscordHello, DiscordReady } from "../../types/discord.ts";
import { GatewayOpcodes } from "../../types/shared.ts";
import { createLeakyBucket } from "../../util/bucket.ts";
import { delay } from "../../util/delay.ts";
import { decompressWith } from "./deps.ts";
import { GATEWAY_RATE_LIMIT_RESET_INTERVAL, Shard, ShardState } from "./types.ts";
import { DiscordGatewayPayload, DiscordHello, DiscordReady } from '../../types/discord.ts';
import { GatewayOpcodes } from '../../types/shared.ts';
import { createLeakyBucket } from '../../util/bucket.ts';
import { delay } from '../../util/delay.ts';
import { decompressWith } from './deps.ts';
import { GATEWAY_RATE_LIMIT_RESET_INTERVAL, Shard, ShardState } from './types.ts';
const decoder = new TextDecoder();
@ -17,7 +17,7 @@ export async function handleMessage(shard: Shard, message_: MessageEvent<any>):
}
// Safeguard incase decompression failed to make a string.
if (typeof message !== "string") return;
if (typeof message !== 'string') return;
const messageData = JSON.parse(message) as DiscordGatewayPayload;
// gateway.debug("GW RAW", { shardId, payload: messageData });
@ -96,8 +96,8 @@ export async function handleMessage(shard: Shard, message_: MessageEvent<any>):
// Reference: https://discord.com/developers/docs/topics/gateway#resuming
await delay(Math.floor((Math.random() * 4 + 1) * 1000));
shard.resolves.get("INVALID_SESSION")?.(messageData);
shard.resolves.delete("INVALID_SESSION");
shard.resolves.get('INVALID_SESSION')?.(messageData);
shard.resolves.delete('INVALID_SESSION');
// When resumable is false we need to re-identify
if (!resumable) {
@ -113,7 +113,7 @@ export async function handleMessage(shard: Shard, message_: MessageEvent<any>):
}
}
if (messageData.t === "RESUMED") {
if (messageData.t === 'RESUMED') {
// gateway.debug("GW RESUMED", { shardId });
shard.state = ShardState.Connected;
@ -122,10 +122,10 @@ export async function handleMessage(shard: Shard, message_: MessageEvent<any>):
// Continue the requests which have been queued since the shard went offline.
shard.offlineSendQueue.map((resolve) => resolve());
shard.resolves.get("RESUMED")?.(messageData);
shard.resolves.delete("RESUMED");
shard.resolves.get('RESUMED')?.(messageData);
shard.resolves.delete('RESUMED');
} // Important for future resumes.
else if (messageData.t === "READY") {
else if (messageData.t === 'READY') {
const payload = messageData.d as DiscordReady;
shard.sessionId = payload.session_id;
@ -135,8 +135,8 @@ export async function handleMessage(shard: Shard, message_: MessageEvent<any>):
// Important when this is a re-identify
shard.offlineSendQueue.map((resolve) => resolve());
shard.resolves.get("READY")?.(messageData);
shard.resolves.delete("READY");
shard.resolves.get('READY')?.(messageData);
shard.resolves.delete('READY');
}
// Update the sequence number if it is present

View File

@ -1,12 +1,12 @@
import { GatewayOpcodes } from "../../types/shared.ts";
import { Shard, ShardSocketCloseCodes, ShardState } from "./types.ts";
import { GatewayOpcodes } from '../../types/shared.ts';
import { Shard, ShardSocketCloseCodes, ShardState } from './types.ts';
export async function identify(shard: Shard): Promise<void> {
// A new identify has been requested even though there is already a connection open.
// Therefore we need to close the old connection and heartbeating before creating a new one.
if (shard.state === ShardState.Connected) {
// console.log("CLOSING EXISTING SHARD: #" + shard.id);
shard.close(ShardSocketCloseCodes.ReIdentifying, "Re-identifying closure of old connection.");
shard.close(ShardSocketCloseCodes.ReIdentifying, 'Re-identifying closure of old connection.');
}
shard.state = ShardState.Identifying;
@ -35,15 +35,15 @@ export async function identify(shard: Shard): Promise<void> {
}, true);
return new Promise((resolve) => {
shard.resolves.set("READY", () => {
shard.resolves.set('READY', () => {
shard.events.identified?.(shard);
resolve();
});
// When identifying too fast,
// Discord sends an invalid session payload.
// This can safely be ignored though and the shard starts a new identify action.
shard.resolves.set("INVALID_SESSION", () => {
shard.resolves.delete("READY");
shard.resolves.set('INVALID_SESSION', () => {
shard.resolves.delete('READY');
resolve();
});
});

View File

@ -1,4 +1,4 @@
import { Shard } from "./types.ts";
import { Shard } from './types.ts';
export function isOpen(shard: Shard): boolean {
return shard.socket?.readyState === WebSocket.OPEN;

View File

@ -1,14 +1,14 @@
export * from "./calculateSafeRequests.ts";
export * from "./close.ts";
export * from "./connect.ts";
export * from "./createShard.ts";
export * from "./handleClose.ts";
export * from "./handleMessage.ts";
export * from "./identify.ts";
export * from "./isOpen.ts";
export * from "./resume.ts";
export * from "./send.ts";
export * from "./shutdown.ts";
export * from "./startHeartbeating.ts";
export * from "./stopHeartbeating.ts";
export * from "./types.ts";
export * from './calculateSafeRequests.ts';
export * from './close.ts';
export * from './connect.ts';
export * from './createShard.ts';
export * from './handleClose.ts';
export * from './handleMessage.ts';
export * from './identify.ts';
export * from './isOpen.ts';
export * from './resume.ts';
export * from './send.ts';
export * from './shutdown.ts';
export * from './startHeartbeating.ts';
export * from './stopHeartbeating.ts';
export * from './types.ts';

View File

@ -1,5 +1,5 @@
import { GatewayOpcodes } from "../../types/shared.ts";
import { Shard, ShardSocketCloseCodes, ShardState } from "./types.ts";
import { GatewayOpcodes } from '../../types/shared.ts';
import { Shard, ShardSocketCloseCodes, ShardState } from './types.ts';
export async function resume(shard: Shard): Promise<void> {
// gateway.debug("GW RESUMING", { shardId });
@ -8,7 +8,7 @@ export async function resume(shard: Shard): Promise<void> {
if (shard.isOpen()) {
shard.close(
ShardSocketCloseCodes.ResumeClosingOldConnection,
"Reconnecting the shard, closing old connection.",
'Reconnecting the shard, closing old connection.',
);
}
@ -39,12 +39,12 @@ export async function resume(shard: Shard): Promise<void> {
}, true);
return new Promise((resolve) => {
shard.resolves.set("RESUMED", () => resolve());
shard.resolves.set('RESUMED', () => resolve());
// If it is attempted to resume with an invalid session id,
// Discord sends an invalid session payload
// Not erroring here since it is easy that this happens, also it would be not catchable
shard.resolves.set("INVALID_SESSION", () => {
shard.resolves.delete("RESUMED");
shard.resolves.set('INVALID_SESSION', () => {
shard.resolves.delete('RESUMED');
resolve();
});
});

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