cleanup cleanup cleanup on isle dd (#2792)

* cleanup cleanup cleanup on isle dd

* fix: rest manager import in test
This commit is contained in:
Skillz4Killz
2023-02-25 20:11:15 -06:00
committed by GitHub
parent b82dafd173
commit 3bbb03b8e3
173 changed files with 13719 additions and 9270 deletions
+75 -75
View File
@@ -1,4 +1,4 @@
import type { CreateGatewayManagerOptions, GatewayManager, Shard } from '@discordeno/gateway'
import type { CreateGatewayManagerOptions, GatewayManager, DiscordenoShard } from '@discordeno/gateway'
import { createGatewayManager, ShardSocketCloseCodes } from '@discordeno/gateway'
import type { CreateRestManagerOptions, RestManager } from '@discordeno/rest'
import { createRestManager } from '@discordeno/rest'
@@ -61,22 +61,22 @@ import { createLogger } from '@discordeno/utils'
*/
export function createBot(options: CreateBotOptions): Bot {
if (!options.rest) options.rest = { token: options.token }
if (!options.gateway) options.gateway = { token: options.token, events: {} };
if (!options.gateway) options.gateway = { token: options.token, events: {} }
if (!options.gateway.events.message) {
options.gateway.events.message = async (shard, data) => {
// TRIGGER RAW EVENT
bot.events.raw?.(data, shard)
// TRIGGER RAW EVENT
bot.events.raw?.(data, shard)
if (!data.t) return
if (!data.t) return
// RUN DISPATCH CHECK
await bot.events.dispatchRequirements?.(data, shard)
bot.events[
data.t.toLowerCase().replace(/_([a-z])/g, function (g) {
return g[1].toUpperCase()
}) as keyof EventHandlers
// @ts-expect-error as any gets removed by linter
]?.(data.d, shard)
// RUN DISPATCH CHECK
await bot.events.dispatchRequirements?.(data, shard)
bot.events[
data.t.toLowerCase().replace(/_([a-z])/g, function (g) {
return g[1].toUpperCase()
}) as keyof EventHandlers
// @ts-expect-error as any gets removed by linter
]?.(data.d, shard)
}
}
@@ -134,68 +134,68 @@ export interface Bot {
export interface EventHandlers {
// Custom events here
dispatchRequirements: (payload: Camelize<DiscordGatewayPayload>, shard: Shard) => unknown
raw: (payload: Camelize<DiscordGatewayPayload>, shard: Shard) => unknown
dispatchRequirements: (payload: Camelize<DiscordGatewayPayload>, shard: DiscordenoShard) => unknown
raw: (payload: Camelize<DiscordGatewayPayload>, shard: DiscordenoShard) => unknown
// Gateway events below this
applicationCommandPermissionsUpdate: (payload: Camelize<DiscordGuildApplicationCommandPermissions>, shard: Shard) => unknown
auditLogEntryCreate: (payload: Camelize<DiscordAuditLogEntry>, shard: Shard) => unknown
autoModerationRuleCreate: (payload: Camelize<DiscordAutoModerationRule>, shard: Shard) => unknown
autoModerationRuleUpdate: (payload: Camelize<DiscordAutoModerationRule>, shard: Shard) => unknown
autoModerationRuleDelete: (payload: Camelize<DiscordAutoModerationRule>, shard: Shard) => unknown
autoModerationActionExecution: (payload: Camelize<DiscordAutoModerationActionExecution>, shard: Shard) => unknown
channelCreate: (payload: Camelize<DiscordChannel>, shard: Shard) => unknown
channelUpdate: (payload: Camelize<DiscordChannel>, shard: Shard) => unknown
channelDelete: (payload: Camelize<DiscordChannel>, shard: Shard) => unknown
channelPinsUpdate: (payload: Camelize<DiscordChannelPinsUpdate>, shard: Shard) => unknown
threadCreate: (payload: Camelize<DiscordChannel>, shard: Shard) => unknown
threadUpdate: (payload: Camelize<DiscordChannel>, shard: Shard) => unknown
threadDelete: (payload: Camelize<DiscordChannel>, shard: Shard) => unknown
threadListSync: (payload: Camelize<DiscordThreadListSync>, shard: Shard) => unknown
threadMemberUpdate: (payload: Camelize<DiscordThreadMemberUpdate>, shard: Shard) => unknown
threadMembersUpdate: (payload: Camelize<DiscordThreadMembersUpdate>, shard: Shard) => unknown
guildCreate: (payload: Camelize<DiscordGuild>, shard: Shard) => unknown
guildUpdate: (payload: Camelize<DiscordGuild>, shard: Shard) => unknown
guildDelete: (payload: Camelize<DiscordUnavailableGuild>, shard: Shard) => unknown
guildBanAdd: (payload: Camelize<DiscordGuildBanAddRemove>, shard: Shard) => unknown
guildBanRemove: (payload: Camelize<DiscordGuildBanAddRemove>, shard: Shard) => unknown
guildEmojisUpdate: (payload: Camelize<DiscordGuildEmojisUpdate>, shard: Shard) => unknown
guildStickersUpdate: (payload: Camelize<DiscordGuildStickersUpdate>, shard: Shard) => unknown
guildIntegrationsUpdate: (payload: Camelize<DiscordIntegrationCreateUpdate>, shard: Shard) => unknown
guildMemberAdd: (payload: Camelize<DiscordGuildMemberAdd>, shard: Shard) => unknown
guildMemberRemove: (payload: Camelize<DiscordGuildMemberRemove>, shard: Shard) => unknown
guildMemberUpdate: (payload: Camelize<DiscordGuildMemberUpdate>, shard: Shard) => unknown
guildMembersChunk: (payload: Camelize<DiscordGuildMembersChunk>, shard: Shard) => unknown
guildRoleCreate: (payload: Camelize<DiscordGuildRoleCreate>, shard: Shard) => unknown
guildRoleUpdate: (payload: Camelize<DiscordGuildRoleUpdate>, shard: Shard) => unknown
guildRoleDelete: (payload: Camelize<DiscordGuildRoleDelete>, shard: Shard) => unknown
guildScheduledEventCreate: (payload: Camelize<DiscordScheduledEvent>, shard: Shard) => unknown
guildScheduledEventUpdate: (payload: Camelize<DiscordScheduledEvent>, shard: Shard) => unknown
guildScheduledEventDelete: (payload: Camelize<DiscordScheduledEvent>, shard: Shard) => unknown
guildScheduledEventUserAdd: (payload: Camelize<DiscordScheduledEventUserAdd>, shard: Shard) => unknown
guildScheduledEventUserRemove: (payload: Camelize<DiscordScheduledEventUserRemove>, shard: Shard) => unknown
integrationCreate: (payload: Camelize<DiscordIntegrationCreateUpdate>, shard: Shard) => unknown
integrationUpdate: (payload: Camelize<DiscordIntegrationCreateUpdate>, shard: Shard) => unknown
integrationDelete: (payload: Camelize<DiscordIntegrationDelete>, shard: Shard) => unknown
interactionCreate: (payload: Camelize<DiscordInteraction>, shard: Shard) => unknown
inviteCreate: (payload: Camelize<DiscordInviteCreate>, shard: Shard) => unknown
inviteDelete: (payload: Camelize<DiscordInviteDelete>, shard: Shard) => unknown
messageCreate: (payload: Camelize<DiscordMessage>, shard: Shard) => unknown
messageUpdate: (payload: Camelize<DiscordMessage>, shard: Shard) => unknown
messageDelete: (payload: Camelize<DiscordMessageDelete>, shard: Shard) => unknown
messageDeleteBulk: (payload: Camelize<DiscordMessageDeleteBulk>, shard: Shard) => unknown
messageReactionAdd: (payload: Camelize<DiscordMessageReactionAdd>, shard: Shard) => unknown
messageReactionRemove: (payload: Camelize<DiscordMessageReactionRemove>, shard: Shard) => unknown
messageReactionRemoveAll: (payload: Camelize<DiscordMessageReactionRemoveAll>, shard: Shard) => unknown
messageReactionRemoveEmoji: (payload: Camelize<DiscordMessageReactionRemoveEmoji>, shard: Shard) => unknown
presenceUpdate: (payload: Camelize<DiscordPresenceUpdate>, shard: Shard) => unknown
ready: (payload: Camelize<DiscordReady>, shard: Shard) => unknown
stageInstanceCreate: (payload: Camelize<DiscordStageInstance>, shard: Shard) => unknown
stageInstanceUpdate: (payload: Camelize<DiscordStageInstance>, shard: Shard) => unknown
stageInstanceDelete: (payload: Camelize<DiscordStageInstance>, shard: Shard) => unknown
typingStart: (payload: Camelize<DiscordTypingStart>, shard: Shard) => unknown
userUpdate: (payload: Camelize<DiscordUser>, shard: Shard) => unknown
voiceStateUpdate: (payload: Camelize<DiscordVoiceState>, shard: Shard) => unknown
voiceServerUpdate: (payload: Camelize<DiscordVoiceServerUpdate>, shard: Shard) => unknown
webhooksUpdate: (payload: Camelize<DiscordWebhookUpdate>, shard: Shard) => unknown
applicationCommandPermissionsUpdate: (payload: Camelize<DiscordGuildApplicationCommandPermissions>, shard: DiscordenoShard) => unknown
auditLogEntryCreate: (payload: Camelize<DiscordAuditLogEntry>, shard: DiscordenoShard) => unknown
autoModerationRuleCreate: (payload: Camelize<DiscordAutoModerationRule>, shard: DiscordenoShard) => unknown
autoModerationRuleUpdate: (payload: Camelize<DiscordAutoModerationRule>, shard: DiscordenoShard) => unknown
autoModerationRuleDelete: (payload: Camelize<DiscordAutoModerationRule>, shard: DiscordenoShard) => unknown
autoModerationActionExecution: (payload: Camelize<DiscordAutoModerationActionExecution>, shard: DiscordenoShard) => unknown
channelCreate: (payload: Camelize<DiscordChannel>, shard: DiscordenoShard) => unknown
channelUpdate: (payload: Camelize<DiscordChannel>, shard: DiscordenoShard) => unknown
channelDelete: (payload: Camelize<DiscordChannel>, shard: DiscordenoShard) => unknown
channelPinsUpdate: (payload: Camelize<DiscordChannelPinsUpdate>, shard: DiscordenoShard) => unknown
threadCreate: (payload: Camelize<DiscordChannel>, shard: DiscordenoShard) => unknown
threadUpdate: (payload: Camelize<DiscordChannel>, shard: DiscordenoShard) => unknown
threadDelete: (payload: Camelize<DiscordChannel>, shard: DiscordenoShard) => unknown
threadListSync: (payload: Camelize<DiscordThreadListSync>, shard: DiscordenoShard) => unknown
threadMemberUpdate: (payload: Camelize<DiscordThreadMemberUpdate>, shard: DiscordenoShard) => unknown
threadMembersUpdate: (payload: Camelize<DiscordThreadMembersUpdate>, shard: DiscordenoShard) => unknown
guildCreate: (payload: Camelize<DiscordGuild>, shard: DiscordenoShard) => unknown
guildUpdate: (payload: Camelize<DiscordGuild>, shard: DiscordenoShard) => unknown
guildDelete: (payload: Camelize<DiscordUnavailableGuild>, shard: DiscordenoShard) => unknown
guildBanAdd: (payload: Camelize<DiscordGuildBanAddRemove>, shard: DiscordenoShard) => unknown
guildBanRemove: (payload: Camelize<DiscordGuildBanAddRemove>, shard: DiscordenoShard) => unknown
guildEmojisUpdate: (payload: Camelize<DiscordGuildEmojisUpdate>, shard: DiscordenoShard) => unknown
guildStickersUpdate: (payload: Camelize<DiscordGuildStickersUpdate>, shard: DiscordenoShard) => unknown
guildIntegrationsUpdate: (payload: Camelize<DiscordIntegrationCreateUpdate>, shard: DiscordenoShard) => unknown
guildMemberAdd: (payload: Camelize<DiscordGuildMemberAdd>, shard: DiscordenoShard) => unknown
guildMemberRemove: (payload: Camelize<DiscordGuildMemberRemove>, shard: DiscordenoShard) => unknown
guildMemberUpdate: (payload: Camelize<DiscordGuildMemberUpdate>, shard: DiscordenoShard) => unknown
guildMembersChunk: (payload: Camelize<DiscordGuildMembersChunk>, shard: DiscordenoShard) => unknown
guildRoleCreate: (payload: Camelize<DiscordGuildRoleCreate>, shard: DiscordenoShard) => unknown
guildRoleUpdate: (payload: Camelize<DiscordGuildRoleUpdate>, shard: DiscordenoShard) => unknown
guildRoleDelete: (payload: Camelize<DiscordGuildRoleDelete>, shard: DiscordenoShard) => unknown
guildScheduledEventCreate: (payload: Camelize<DiscordScheduledEvent>, shard: DiscordenoShard) => unknown
guildScheduledEventUpdate: (payload: Camelize<DiscordScheduledEvent>, shard: DiscordenoShard) => unknown
guildScheduledEventDelete: (payload: Camelize<DiscordScheduledEvent>, shard: DiscordenoShard) => unknown
guildScheduledEventUserAdd: (payload: Camelize<DiscordScheduledEventUserAdd>, shard: DiscordenoShard) => unknown
guildScheduledEventUserRemove: (payload: Camelize<DiscordScheduledEventUserRemove>, shard: DiscordenoShard) => unknown
integrationCreate: (payload: Camelize<DiscordIntegrationCreateUpdate>, shard: DiscordenoShard) => unknown
integrationUpdate: (payload: Camelize<DiscordIntegrationCreateUpdate>, shard: DiscordenoShard) => unknown
integrationDelete: (payload: Camelize<DiscordIntegrationDelete>, shard: DiscordenoShard) => unknown
interactionCreate: (payload: Camelize<DiscordInteraction>, shard: DiscordenoShard) => unknown
inviteCreate: (payload: Camelize<DiscordInviteCreate>, shard: DiscordenoShard) => unknown
inviteDelete: (payload: Camelize<DiscordInviteDelete>, shard: DiscordenoShard) => unknown
messageCreate: (payload: Camelize<DiscordMessage>, shard: DiscordenoShard) => unknown
messageUpdate: (payload: Camelize<DiscordMessage>, shard: DiscordenoShard) => unknown
messageDelete: (payload: Camelize<DiscordMessageDelete>, shard: DiscordenoShard) => unknown
messageDeleteBulk: (payload: Camelize<DiscordMessageDeleteBulk>, shard: DiscordenoShard) => unknown
messageReactionAdd: (payload: Camelize<DiscordMessageReactionAdd>, shard: DiscordenoShard) => unknown
messageReactionRemove: (payload: Camelize<DiscordMessageReactionRemove>, shard: DiscordenoShard) => unknown
messageReactionRemoveAll: (payload: Camelize<DiscordMessageReactionRemoveAll>, shard: DiscordenoShard) => unknown
messageReactionRemoveEmoji: (payload: Camelize<DiscordMessageReactionRemoveEmoji>, shard: DiscordenoShard) => unknown
presenceUpdate: (payload: Camelize<DiscordPresenceUpdate>, shard: DiscordenoShard) => unknown
ready: (payload: Camelize<DiscordReady>, shard: DiscordenoShard) => unknown
stageInstanceCreate: (payload: Camelize<DiscordStageInstance>, shard: DiscordenoShard) => unknown
stageInstanceUpdate: (payload: Camelize<DiscordStageInstance>, shard: DiscordenoShard) => unknown
stageInstanceDelete: (payload: Camelize<DiscordStageInstance>, shard: DiscordenoShard) => unknown
typingStart: (payload: Camelize<DiscordTypingStart>, shard: DiscordenoShard) => unknown
userUpdate: (payload: Camelize<DiscordUser>, shard: DiscordenoShard) => unknown
voiceStateUpdate: (payload: Camelize<DiscordVoiceState>, shard: DiscordenoShard) => unknown
voiceServerUpdate: (payload: Camelize<DiscordVoiceServerUpdate>, shard: DiscordenoShard) => unknown
webhooksUpdate: (payload: Camelize<DiscordWebhookUpdate>, shard: DiscordenoShard) => unknown
}
+4 -4
View File
@@ -3,7 +3,7 @@ import { delay, logger } from '@discordeno/utils'
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import { describe, it } from 'mocha'
import type { EventHandlers } from '../../src/bot.js';
import type { EventHandlers } from '../../src/bot.js'
import { createBot } from '../../src/bot.js'
import { token } from './constants.js'
chai.use(chaiAsPromised)
@@ -35,12 +35,12 @@ describe('[Bot] Delete any guild owned guilds', () => {
},
events: {
async guildCreate(payload, shard) {
if (payload.joinedAt && (Date.now() - Date.parse(payload.joinedAt)) < 360000) {
return;
if (payload.joinedAt && Date.now() - Date.parse(payload.joinedAt) < 360000) {
return
}
if (bot.rest.applicationId.toString() === payload.ownerId) {
logger.debug(`Deleting one of the bot created guilds.`, payload.id);
logger.debug(`Deleting one of the bot created guilds.`, payload.id)
await bot.rest.deleteGuild(payload.id)
}
},
+136 -136
View File
@@ -1,140 +1,140 @@
export class Collection<K, V> extends Map<K, V> {
limit: number | undefined;
set(key: K, value: V): this {
// When this collection is limitd make sure we can add first
if ((this.limit ?? this.limit === 0) && this.size >= this.limit) {
return this;
}
return super.set(key, value);
limit: number | undefined
set(key: K, value: V): this {
// When this collection is limitd make sure we can add first
if ((this.limit ?? this.limit === 0) && this.size >= this.limit) {
return this
}
forceSet(key: K, value: V): this {
return super.set(key, value);
}
array(): V[] {
return [...this.values()];
}
/** Retrieve the value of the first element in this collection */
first(): V | undefined {
return this.values().next().value;
}
last(): V | undefined {
return [...this.values()][this.size - 1];
}
random(): V | undefined {
const array = [...this.values()];
return array[Math.floor(Math.random() * array.length)];
}
find(callback: (value: V, key: K) => boolean): V | undefined {
for (const key of this.keys()) {
const value = this.get(key)!;
if (callback(value, key)) return value;
}
}
filter(callback: (value: V, key: K) => boolean, returnArray?: true): V[];
filter(callback: (value: V, key: K) => boolean, returnArray: false): Collection<K, V>;
filter(callback: (value: V, key: K) => boolean, returnArray = true): Collection<K, V> | V[] {
const relevant = new Collection<K, V>();
this.forEach((value, key) => {
if (callback(value, key)) relevant.set(key, value);
});
return returnArray ? relevant.array() : relevant;
}
map<T>(callback: (value: V, key: K) => T): T[] {
const results = [];
for (const key of this.keys()) {
const value = this.get(key)!;
results.push(callback(value, key));
}
return results;
}
some(callback: (value: V, key: K) => boolean): boolean {
for (const key of this.keys()) {
const value = this.get(key)!;
if (callback(value, key)) return true;
}
return false;
}
every(callback: (value: V, key: K) => boolean): boolean {
for (const key of this.keys()) {
const value = this.get(key)!;
if (!callback(value, key)) return false;
}
return true;
}
reduce<T>(callback: (accumulator: T, value: V, key: K) => T, initialValue?: T): T {
let accumulator: T = initialValue!;
for (const key of this.keys()) {
const value = this.get(key)!;
accumulator = callback(accumulator, value, key);
}
return accumulator;
}
/**
* Adds a object to the collection.
* @deprecated Recommend using Collection.set(). Keeping for the sake of Eris API.
* @deprecated extra parameter. No longer used, keeping for sake of Eris API.
*/
add(obj: V & { id: K }, extra?: unknown, replace?: boolean): V {
if (this.limit === 0) return obj;
const existing = this.get(obj.id);
if (existing && !replace) {
return existing;
}
this.set(obj.id, obj);
return obj;
}
remove(obj: { id: K }): V | undefined {
const item = this.get(obj.id);
if (!item) return;
this.delete(obj.id);
return item;
}
update(obj: V & { id: K }, extra?: unknown, replace?: boolean): V {
const item = this.get(obj.id);
if (!item) {
this.set(obj.id, obj);
return obj;
}
// @ts-expect-error some eris magic at play here
item.update?.(obj, extra);
return item;
}
toRecord(): Record<string, V> {
const record: Record<string, V> = {};
for (const [key, value] of this.entries()) {
// @ts-expect-error should work fine
const finalKey = typeof key === 'string' ? key : key.toString();
record[finalKey] = value;
}
return record;
return super.set(key, value)
}
forceSet(key: K, value: V): this {
return super.set(key, value)
}
array(): V[] {
return [...this.values()]
}
/** Retrieve the value of the first element in this collection */
first(): V | undefined {
return this.values().next().value
}
last(): V | undefined {
return [...this.values()][this.size - 1]
}
random(): V | undefined {
const array = [...this.values()]
return array[Math.floor(Math.random() * array.length)]
}
find(callback: (value: V, key: K) => boolean): V | undefined {
for (const key of this.keys()) {
const value = this.get(key)!
if (callback(value, key)) return value
}
}
export default Collection;
filter(callback: (value: V, key: K) => boolean, returnArray?: true): V[]
filter(callback: (value: V, key: K) => boolean, returnArray: false): Collection<K, V>
filter(callback: (value: V, key: K) => boolean, returnArray = true): Collection<K, V> | V[] {
const relevant = new Collection<K, V>()
this.forEach((value, key) => {
if (callback(value, key)) relevant.set(key, value)
})
return returnArray ? relevant.array() : relevant
}
map<T>(callback: (value: V, key: K) => T): T[] {
const results = []
for (const key of this.keys()) {
const value = this.get(key)!
results.push(callback(value, key))
}
return results
}
some(callback: (value: V, key: K) => boolean): boolean {
for (const key of this.keys()) {
const value = this.get(key)!
if (callback(value, key)) return true
}
return false
}
every(callback: (value: V, key: K) => boolean): boolean {
for (const key of this.keys()) {
const value = this.get(key)!
if (!callback(value, key)) return false
}
return true
}
reduce<T>(callback: (accumulator: T, value: V, key: K) => T, initialValue?: T): T {
let accumulator: T = initialValue!
for (const key of this.keys()) {
const value = this.get(key)!
accumulator = callback(accumulator, value, key)
}
return accumulator
}
/**
* Adds a object to the collection.
* @deprecated Recommend using Collection.set(). Keeping for the sake of Eris API.
* @deprecated extra parameter. No longer used, keeping for sake of Eris API.
*/
add(obj: V & { id: K }, extra?: unknown, replace?: boolean): V {
if (this.limit === 0) return obj
const existing = this.get(obj.id)
if (existing && !replace) {
return existing
}
this.set(obj.id, obj)
return obj
}
remove(obj: { id: K }): V | undefined {
const item = this.get(obj.id)
if (!item) return
this.delete(obj.id)
return item
}
update(obj: V & { id: K }, extra?: unknown, replace?: boolean): V {
const item = this.get(obj.id)
if (!item) {
this.set(obj.id, obj)
return obj
}
// @ts-expect-error some eris magic at play here
item.update?.(obj, extra)
return item
}
toRecord(): Record<string, V> {
const record: Record<string, V> = {}
for (const [key, value] of this.entries()) {
// @ts-expect-error should work fine
const finalKey = typeof key === 'string' ? key : key.toString()
record[finalKey] = value
}
return record
}
}
export default Collection
@@ -1,10 +1,9 @@
/* eslint-disable no-useless-call */
/* eslint-disable @typescript-eslint/return-await */
import type { DiscordChannel } from "@discordeno/types"
import type { StageInstanceOptions } from "../../typings.js"
import type StageInstance from "../guilds/StageInstance.js"
import VoiceChannel from "./Voice.js"
import type { DiscordChannel } from '@discordeno/types'
import type { StageInstanceOptions } from '../../typings.js'
import type StageInstance from '../guilds/StageInstance.js'
import VoiceChannel from './Voice.js'
export class StageChannel extends VoiceChannel {
/** The topic of the channel */
@@ -1,9 +1,8 @@
/* eslint-disable no-useless-call */
import type { BigString, DiscordThreadMember } from "@discordeno/types"
import Base from "../../../Base.js"
import type Client from "../../../Client.js"
import type Member from "../../guilds/Member.js"
import type { BigString, DiscordThreadMember } from '@discordeno/types'
import Base from '../../../Base.js'
import type Client from '../../../Client.js'
import type Member from '../../guilds/Member.js'
export class ThreadMember extends Base {
client: Client
@@ -1,26 +1,25 @@
import type { DiscordChannel } from "@discordeno/types";
import type Client from "../../../Client.js";
import ThreadChannel from "./Thread.js";
import type { DiscordChannel } from '@discordeno/types'
import type Client from '../../../Client.js'
import ThreadChannel from './Thread.js'
export class PrivateThreadChannel extends ThreadChannel {
constructor(data: DiscordChannel, client: Client, messageLimit?: number) {
super(data, client, messageLimit);
constructor(data: DiscordChannel, client: Client, messageLimit?: number) {
super(data, client, messageLimit)
this.update(data);
}
this.update(data)
}
update(data: DiscordChannel): void {
if(data.thread_metadata !== undefined) {
this.threadMetadata = {
archiveTimestamp: Date.parse(data.thread_metadata.archive_timestamp),
archived: data.thread_metadata.archived,
autoArchiveDuration: data.thread_metadata.auto_archive_duration,
invitable: data.thread_metadata.invitable,
locked: data.thread_metadata.locked
};
}
update(data: DiscordChannel): void {
if (data.thread_metadata !== undefined) {
this.threadMetadata = {
archiveTimestamp: Date.parse(data.thread_metadata.archive_timestamp),
archived: data.thread_metadata.archived,
autoArchiveDuration: data.thread_metadata.auto_archive_duration,
invitable: data.thread_metadata.invitable,
locked: data.thread_metadata.locked,
}
}
}
}
export default PrivateThreadChannel;
export default PrivateThreadChannel
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable no-useless-call */
import Base from '../../Base.js';
import Base from '../../Base.js'
import type { DiscordStageInstance } from '@discordeno/types'
import type Client from '../../Client.js'
@@ -1,7 +1,6 @@
import type { DiscordUnavailableGuild } from "@discordeno/types"
import Base from "../../Base.js"
import type Client from "../../Client.js"
import type { DiscordUnavailableGuild } from '@discordeno/types'
import Base from '../../Base.js'
import type Client from '../../Client.js'
export class UnavailableGuild extends Base {
/** Whether or not the guild is unavailable. */
@@ -2,15 +2,15 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable no-useless-call */
/* eslint-disable @typescript-eslint/return-await */
import { ApplicationCommandTypes, InteractionResponseTypes } from '@discordeno/types';
import { ApplicationCommandTypes, InteractionResponseTypes } from '@discordeno/types'
import Collection from '../../Collection.js';
import Channel from '../channels/Channel.js';
import Member from '../guilds/Member.js';
import Role from '../guilds/Role.js';
import Message from '../Message.js';
import User from '../users/User.js';
import Interaction from './Interaction.js';
import Collection from '../../Collection.js'
import Channel from '../channels/Channel.js'
import Member from '../guilds/Member.js'
import Role from '../guilds/Role.js'
import Message from '../Message.js'
import User from '../users/User.js'
import Interaction from './Interaction.js'
import type {
BigString,
@@ -1,7 +1,6 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import type { DiscordVoiceState } from "@discordeno/types"
import { ToggleBitfield } from "./Toggle.js"
import type { DiscordVoiceState } from '@discordeno/types'
import { ToggleBitfield } from './Toggle.js'
export const VoiceStateToggle = {
/** Whether this user is deafened by the server */
@@ -1,7 +1,6 @@
import type { PremiumTypes, DiscordUser } from "@discordeno/types"
import type Client from "../../Client.js"
import User from "./User.js"
import type { PremiumTypes, DiscordUser } from '@discordeno/types'
import type Client from '../../Client.js'
import User from './User.js'
export class ExtendedUser extends User {
email?: string | null
+1 -1
View File
@@ -4,7 +4,7 @@
/* eslint-disable @typescript-eslint/no-dynamic-delete */
/* eslint-disable @typescript-eslint/restrict-plus-operands */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { Shard as DiscordenoShard, ShardState } from '@discordeno/gateway'
import { DiscordenoShard, ShardState } from '@discordeno/gateway'
import type { DiscordGuildStickersUpdate, DiscordThreadMemberUpdate } from '@discordeno/types'
import {
ActivityTypes,
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable @typescript-eslint/no-var-requires */
import { EventEmitter } from "node:events"
import { EventEmitter } from 'node:events'
class BrowserWebSocketError extends Error {
static CONNECTING: 0 = 0
@@ -49,7 +49,7 @@ class BrowserWebSocket extends EventEmitter {
}
static set CONNECTING(state: number) {
BrowserWebSocket.CONNECTING = state;
BrowserWebSocket.CONNECTING = state
}
static get OPEN() {
@@ -57,7 +57,7 @@ class BrowserWebSocket extends EventEmitter {
}
static set OPEN(state: number) {
BrowserWebSocket.OPEN = state;
BrowserWebSocket.OPEN = state
}
static get CLOSING() {
@@ -65,7 +65,7 @@ class BrowserWebSocket extends EventEmitter {
}
static set CLOSING(state: number) {
BrowserWebSocket.CLOSING = state;
BrowserWebSocket.CLOSING = state
}
static get CLOSED() {
@@ -73,7 +73,7 @@ class BrowserWebSocket extends EventEmitter {
}
static set CLOSED(state: number) {
BrowserWebSocket.CLOSED = state;
BrowserWebSocket.CLOSED = state
}
close(code?: number, reason?: string) {
+1 -1
View File
@@ -2,6 +2,6 @@ import { describe, it } from 'mocha'
describe('index.ts', () => {
it('will import without error', async () => {
await import('../src/index.js')
await import('../src/index.js')
})
})
+1 -1
View File
@@ -53,7 +53,7 @@ This WS service is meant for ADVANCED DEVELOPERS ONLY!
```ts
createGatewayManager({
// TODO: (docs) Fill this out
});
})
```
## API/Docs
+3 -3
View File
@@ -16,7 +16,7 @@ import type { RequestMemberRequest } from './manager.js'
import type { BotStatusUpdate, ShardEvents, ShardGatewayConfig, ShardHeart, ShardSocketRequest, StatusUpdate, UpdateVoiceState } from './types.js'
import { ShardSocketCloseCodes, ShardState } from './types.js'
export class Shard {
export class DiscordenoShard {
/** The id of the shard */
id: number
/** The connection config details that this shard will used to connect to discord. */
@@ -105,7 +105,7 @@ export class Shard {
}
/** Connect the shard with the gateway and start heartbeating. This will not identify the shard to the gateway. */
async connect(): Promise<Shard> {
async connect(): Promise<DiscordenoShard> {
// Only set the shard to `Connecting` state,
// if the connection request does not come from an identify or resume action.
if (![ShardState.Identifying, ShardState.Resuming].includes(this.state)) {
@@ -750,4 +750,4 @@ export interface ShardCreateOptions {
events: ShardEvents
}
export default Shard
export default DiscordenoShard
+1 -1
View File
@@ -173,7 +173,7 @@ export interface StatusUpdate {
// /** Unix time (in milliseconds) of when the client went idle, or null if the client is not idle */
// since: number | null;
/** The user's activities */
activities?: Camelize<Array<Omit<DiscordActivity, "created_at">>>
activities?: Camelize<Array<Omit<DiscordActivity, 'created_at'>>>
/** The user's new status */
status: keyof typeof PresenceStatus
// /** Whether or not the client is afk */
+1 -1
View File
@@ -3,4 +3,4 @@ export * from './typings/routes.js'
export * from './invalidBucket.js'
export * from './manager.js'
export * from './queue.js'
export * from './types.js'
export * from './types.js'
+2 -4
View File
@@ -7,9 +7,7 @@ import { delay, logger } from '@discordeno/utils'
* @param options The options used to configure this bucket.
* @returns RefillingBucket
*/
export function createInvalidRequestBucket (
options: InvalidRequestBucketOptions
): InvalidRequestBucket {
export function createInvalidRequestBucket(options: InvalidRequestBucketOptions): InvalidRequestBucket {
const bucket: InvalidRequestBucket = {
current: options.current ?? 0,
max: options.max ?? 10000,
@@ -87,7 +85,7 @@ export function createInvalidRequestBucket (
bucket.timeoutId = undefined
}, bucket.interval)
}
}
},
}
return bucket
+13 -7
View File
@@ -14,7 +14,7 @@ import {
isGetMessagesLimit,
logger,
processReactionString,
urlToBase64
urlToBase64,
} from '@discordeno/utils'
import { createInvalidRequestBucket } from './invalidBucket.js'
@@ -22,9 +22,11 @@ import { Queue } from './queue.js'
import type {
BigString,
Camelize, DiscordApplication,
Camelize,
DiscordApplication,
DiscordApplicationCommand,
DiscordApplicationCommandPermissions, DiscordAuditLog,
DiscordApplicationCommandPermissions,
DiscordAuditLog,
DiscordAutoModerationRule,
DiscordBan,
DiscordChannel,
@@ -43,7 +45,8 @@ import type {
DiscordListArchivedThreads,
DiscordMember,
DiscordMemberWithUser,
DiscordMessage, DiscordPrunedCount,
DiscordMessage,
DiscordPrunedCount,
DiscordRole,
DiscordScheduledEvent,
DiscordStageInstance,
@@ -55,8 +58,11 @@ import type {
DiscordVanityUrl,
DiscordVoiceRegion,
DiscordWebhook,
DiscordWelcomeScreen, GetMessagesOptions, GetScheduledEventUsers, MfaLevels,
ModifyGuildTemplate
DiscordWelcomeScreen,
GetMessagesOptions,
GetScheduledEventUsers,
MfaLevels,
ModifyGuildTemplate,
} from '@discordeno/types'
import type { CreateRestManagerOptions, RestManager, SendRequestOptions } from './types.js'
@@ -873,7 +879,7 @@ export function createRestManager(options: CreateRestManagerOptions): RestManage
rest.invalidBucket.handleCompletedRequest(response.status, response.headers.get('X-RateLimit-Scope') === 'shared')
const resetAfter = response.headers.get('x-ratelimit-reset-after')
logger.warn(`Request to ${url} was rate limited. Reset after ${resetAfter} seconds.`,);
logger.warn(`Request to ${url} was rate limited. Reset after ${resetAfter} seconds.`)
if (resetAfter) await delay(Number(resetAfter) * 1000)
// process the response to prevent mem leak
await response.json()
+96 -1
View File
@@ -1,4 +1,99 @@
import type { ApplicationCommandPermissions, AtLeastOne, BeginGuildPrune, BigString, Camelize, CreateApplicationCommand, CreateAutoModerationRuleOptions, CreateChannelInvite, CreateForumPostWithMessage, CreateGuild, CreateGuildBan, CreateGuildChannel, CreateGuildEmoji, CreateGuildFromTemplate, CreateGuildRole, CreateGuildStickerOptions, CreateMessageOptions, CreateScheduledEvent, CreateStageInstance, CreateTemplate, DeleteWebhookMessageOptions, DiscordActiveThreads, DiscordApplication, DiscordApplicationCommand, DiscordApplicationCommandPermissions, DiscordArchivedThreads, DiscordAuditLog, DiscordAutoModerationRule, DiscordBan, DiscordChannel, DiscordEmoji, DiscordFollowedChannel, DiscordGetGatewayBot, DiscordGuild, DiscordGuildPreview, DiscordGuildWidget, DiscordGuildWidgetSettings, DiscordIntegration, DiscordInvite, DiscordInviteMetadata, DiscordMember, DiscordMemberWithUser, DiscordMessage, DiscordModifyGuildWelcomeScreen, DiscordPrunedCount, DiscordRole, DiscordScheduledEvent, DiscordStageInstance, DiscordSticker, DiscordStickerPack, DiscordTemplate, DiscordThreadMember, DiscordUser, DiscordVanityUrl, DiscordVoiceRegion, DiscordWebhook, DiscordWelcomeScreen, EditAutoModerationRuleOptions, EditBotMemberOptions, EditChannelPermissionOverridesOptions, EditGuildRole, EditGuildStickerOptions, EditMessage, EditOwnVoiceState, EditScheduledEvent, EditStageInstanceOptions, EditUserVoiceState, ExecuteWebhook, GetBans, GetGuildAuditLog, GetGuildPruneCountQuery, GetInvite, GetMessagesOptions, GetReactions, GetScheduledEvents, GetScheduledEventUsers, GetWebhookMessageOptions, InteractionCallbackData, InteractionResponse, ListArchivedThreads, ListGuildMembers, MfaLevels, ModifyChannel, ModifyGuild, ModifyGuildChannelPositions, ModifyGuildEmoji, ModifyGuildMember, ModifyGuildTemplate, ModifyRolePositions, ModifyWebhook, SearchMembers, StartThreadWithMessage, StartThreadWithoutMessage, WithReason } from "@discordeno/types"
import type {
ApplicationCommandPermissions,
AtLeastOne,
BeginGuildPrune,
BigString,
Camelize,
CreateApplicationCommand,
CreateAutoModerationRuleOptions,
CreateChannelInvite,
CreateForumPostWithMessage,
CreateGuild,
CreateGuildBan,
CreateGuildChannel,
CreateGuildEmoji,
CreateGuildFromTemplate,
CreateGuildRole,
CreateGuildStickerOptions,
CreateMessageOptions,
CreateScheduledEvent,
CreateStageInstance,
CreateTemplate,
DeleteWebhookMessageOptions,
DiscordActiveThreads,
DiscordApplication,
DiscordApplicationCommand,
DiscordApplicationCommandPermissions,
DiscordArchivedThreads,
DiscordAuditLog,
DiscordAutoModerationRule,
DiscordBan,
DiscordChannel,
DiscordEmoji,
DiscordFollowedChannel,
DiscordGetGatewayBot,
DiscordGuild,
DiscordGuildPreview,
DiscordGuildWidget,
DiscordGuildWidgetSettings,
DiscordIntegration,
DiscordInvite,
DiscordInviteMetadata,
DiscordMember,
DiscordMemberWithUser,
DiscordMessage,
DiscordModifyGuildWelcomeScreen,
DiscordPrunedCount,
DiscordRole,
DiscordScheduledEvent,
DiscordStageInstance,
DiscordSticker,
DiscordStickerPack,
DiscordTemplate,
DiscordThreadMember,
DiscordUser,
DiscordVanityUrl,
DiscordVoiceRegion,
DiscordWebhook,
DiscordWelcomeScreen,
EditAutoModerationRuleOptions,
EditBotMemberOptions,
EditChannelPermissionOverridesOptions,
EditGuildRole,
EditGuildStickerOptions,
EditMessage,
EditOwnVoiceState,
EditScheduledEvent,
EditStageInstanceOptions,
EditUserVoiceState,
ExecuteWebhook,
GetBans,
GetGuildAuditLog,
GetGuildPruneCountQuery,
GetInvite,
GetMessagesOptions,
GetReactions,
GetScheduledEvents,
GetScheduledEventUsers,
GetWebhookMessageOptions,
InteractionCallbackData,
InteractionResponse,
ListArchivedThreads,
ListGuildMembers,
MfaLevels,
ModifyChannel,
ModifyGuild,
ModifyGuildChannelPositions,
ModifyGuildEmoji,
ModifyGuildMember,
ModifyGuildTemplate,
ModifyRolePositions,
ModifyWebhook,
SearchMembers,
StartThreadWithMessage,
StartThreadWithoutMessage,
WithReason,
} from '@discordeno/types'
import type { InvalidRequestBucket } from './invalidBucket.js'
import type { Queue } from './queue.js'
import type { RestRoutes } from './typings/routes.js'
+56 -96
View File
@@ -1,9 +1,5 @@
import type { Camelize, DiscordChannel, DiscordGuild } from '@discordeno/types'
import {
AutoModerationActionType,
AutoModerationEventTypes,
AutoModerationTriggerTypes
} from '@discordeno/types'
import { AutoModerationActionType, AutoModerationEventTypes, AutoModerationTriggerTypes } from '@discordeno/types'
import { expect } from 'chai'
import { e2ecache, rest } from './utils.js'
@@ -18,7 +14,7 @@ before(async () => {
after(async () => {
if (rest.invalidBucket.timeoutId) clearTimeout(rest.invalidBucket.timeoutId)
if (e2ecache.guild.id && !e2ecache.deletedGuild) {
e2ecache.deletedGuild = true;
e2ecache.deletedGuild = true
await rest.deleteGuild(e2ecache.guild.id)
}
})
@@ -30,13 +26,13 @@ describe('[automod] Run automod tests', async () => {
eventType: AutoModerationEventTypes.MessageSend,
triggerType: AutoModerationTriggerTypes.Keyword,
triggerMetadata: {
keywordFilter: ['iblamewolf']
keywordFilter: ['iblamewolf'],
},
actions: [
{
type: AutoModerationActionType.BlockMessage
}
]
type: AutoModerationActionType.BlockMessage,
},
],
})
expect(rule.id).to.be.exist
@@ -45,20 +41,12 @@ describe('[automod] Run automod tests', async () => {
expect(fetchedRule.id).to.be.exist
expect(fetchedRule.name).to.equal(rule.name)
expect(fetchedRule.eventType).to.equal(
AutoModerationEventTypes.MessageSend
)
expect(fetchedRule.triggerType).to.equal(
AutoModerationTriggerTypes.Keyword
)
expect(fetchedRule.triggerMetadata?.keywordFilter?.[0]).to.equal(
'iblamewolf'
)
expect(fetchedRule.eventType).to.equal(AutoModerationEventTypes.MessageSend)
expect(fetchedRule.triggerType).to.equal(AutoModerationTriggerTypes.Keyword)
expect(fetchedRule.triggerMetadata?.keywordFilter?.[0]).to.equal('iblamewolf')
expect(fetchedRule.actions).to.be.exist
expect(fetchedRule.actions[0]).to.be.exist
expect(fetchedRule.actions[0].type).to.equal(
AutoModerationActionType.BlockMessage
)
expect(fetchedRule.actions[0].type).to.equal(AutoModerationActionType.BlockMessage)
await rest.deleteAutomodRule(e2ecache.guild.id, rule.id)
})
@@ -69,16 +57,16 @@ describe('[automod] Run automod tests', async () => {
eventType: AutoModerationEventTypes.MessageSend,
triggerType: AutoModerationTriggerTypes.Keyword,
triggerMetadata: {
keywordFilter: ['iblamewolf']
keywordFilter: ['iblamewolf'],
},
actions: [
{
type: AutoModerationActionType.Timeout,
metadata: {
durationSeconds: 10
}
}
]
durationSeconds: 10,
},
},
],
})
expect(rule.id).to.be.exist
@@ -87,20 +75,12 @@ describe('[automod] Run automod tests', async () => {
expect(fetchedRule.id).to.be.exist
expect(fetchedRule.name).to.equal(rule.name)
expect(fetchedRule.eventType).to.equal(
AutoModerationEventTypes.MessageSend
)
expect(fetchedRule.triggerType).to.equal(
AutoModerationTriggerTypes.Keyword
)
expect(fetchedRule.triggerMetadata?.keywordFilter?.[0]).to.equal(
'iblamewolf'
)
expect(fetchedRule.eventType).to.equal(AutoModerationEventTypes.MessageSend)
expect(fetchedRule.triggerType).to.equal(AutoModerationTriggerTypes.Keyword)
expect(fetchedRule.triggerMetadata?.keywordFilter?.[0]).to.equal('iblamewolf')
expect(fetchedRule.actions).to.be.exist
expect(fetchedRule.actions[0]).to.be.exist
expect(fetchedRule.actions[0].type).to.equal(
AutoModerationActionType.Timeout
)
expect(fetchedRule.actions[0].type).to.equal(AutoModerationActionType.Timeout)
expect(fetchedRule.actions[0].metadata?.durationSeconds).to.equal(10)
await rest.deleteAutomodRule(e2ecache.guild.id, rule.id)
@@ -112,19 +92,19 @@ describe('[automod] Run automod tests', async () => {
eventType: AutoModerationEventTypes.MessageSend,
triggerType: AutoModerationTriggerTypes.Keyword,
triggerMetadata: {
keywordFilter: ['iblamewolf']
keywordFilter: ['iblamewolf'],
},
actions: [
{
type: AutoModerationActionType.BlockMessage
type: AutoModerationActionType.BlockMessage,
},
{
type: AutoModerationActionType.Timeout,
metadata: {
durationSeconds: 10
}
}
]
durationSeconds: 10,
},
},
],
})
expect(rule.id).to.be.exist
@@ -137,7 +117,7 @@ describe('[automod] Run automod tests', async () => {
beforeEach(async () => {
channel = await rest.createChannel(e2ecache.guild.id, {
name: 'test'
name: 'test',
})
})
@@ -151,16 +131,16 @@ describe('[automod] Run automod tests', async () => {
eventType: AutoModerationEventTypes.MessageSend,
triggerType: AutoModerationTriggerTypes.Keyword,
triggerMetadata: {
keywordFilter: ['iblamewolf']
keywordFilter: ['iblamewolf'],
},
actions: [
{
type: AutoModerationActionType.SendAlertMessage,
metadata: {
channelId: channel.id
}
}
]
channelId: channel.id,
},
},
],
})
expect(rule.id).to.be.exist
@@ -169,20 +149,12 @@ describe('[automod] Run automod tests', async () => {
expect(fetchedRule.id).to.be.exist
expect(fetchedRule.name).to.equal(rule.name)
expect(fetchedRule.eventType).to.equal(
AutoModerationEventTypes.MessageSend
)
expect(fetchedRule.triggerType).to.equal(
AutoModerationTriggerTypes.Keyword
)
expect(fetchedRule.triggerMetadata?.keywordFilter?.[0]).to.equal(
'iblamewolf'
)
expect(fetchedRule.eventType).to.equal(AutoModerationEventTypes.MessageSend)
expect(fetchedRule.triggerType).to.equal(AutoModerationTriggerTypes.Keyword)
expect(fetchedRule.triggerMetadata?.keywordFilter?.[0]).to.equal('iblamewolf')
expect(fetchedRule.actions).to.be.exist
expect(fetchedRule.actions[0]).to.be.exist
expect(fetchedRule.actions[0].type).to.equal(
AutoModerationActionType.SendAlertMessage
)
expect(fetchedRule.actions[0].type).to.equal(AutoModerationActionType.SendAlertMessage)
expect(fetchedRule.actions[0].metadata?.channelId).to.equal(channel.id)
await rest.deleteAutomodRule(e2ecache.guild.id, rule.id)
@@ -194,22 +166,22 @@ describe('[automod] Run automod tests', async () => {
eventType: AutoModerationEventTypes.MessageSend,
triggerType: AutoModerationTriggerTypes.Keyword,
triggerMetadata: {
keywordFilter: ['iblamewolf']
keywordFilter: ['iblamewolf'],
},
actions: [
{
type: AutoModerationActionType.SendAlertMessage,
metadata: {
channelId: channel.id
}
channelId: channel.id,
},
},
{
type: AutoModerationActionType.Timeout,
metadata: {
durationSeconds: 10
}
}
]
durationSeconds: 10,
},
},
],
})
expect(rule.id).to.be.exist
@@ -223,25 +195,25 @@ describe('[automod] Run automod tests', async () => {
eventType: AutoModerationEventTypes.MessageSend,
triggerType: AutoModerationTriggerTypes.Keyword,
triggerMetadata: {
keywordFilter: ['iblamewolf']
keywordFilter: ['iblamewolf'],
},
actions: [
{
type: AutoModerationActionType.BlockMessage
type: AutoModerationActionType.BlockMessage,
},
{
type: AutoModerationActionType.SendAlertMessage,
metadata: {
channelId: channel.id
}
channelId: channel.id,
},
},
{
type: AutoModerationActionType.Timeout,
metadata: {
durationSeconds: 10
}
}
]
durationSeconds: 10,
},
},
],
})
expect(rule.id).to.be.exist
@@ -250,30 +222,18 @@ describe('[automod] Run automod tests', async () => {
const fetchedRule = await rest.getAutomodRule(e2ecache.guild.id, rule.id)
expect(fetchedRule.id).to.be.exist
expect(fetchedRule.name).to.equal(rule.name)
expect(fetchedRule.eventType).to.equal(
AutoModerationEventTypes.MessageSend
)
expect(fetchedRule.triggerType).to.equal(
AutoModerationTriggerTypes.Keyword
)
expect(fetchedRule.triggerMetadata?.keywordFilter?.[0]).to.equal(
'iblamewolf'
)
expect(fetchedRule.eventType).to.equal(AutoModerationEventTypes.MessageSend)
expect(fetchedRule.triggerType).to.equal(AutoModerationTriggerTypes.Keyword)
expect(fetchedRule.triggerMetadata?.keywordFilter?.[0]).to.equal('iblamewolf')
expect(fetchedRule.actions).to.be.exist
expect(fetchedRule.actions[0]).to.be.exist
expect(fetchedRule.actions[1].metadata).to.be.exist
expect(fetchedRule.actions[2].metadata).to.be.exist
expect(fetchedRule.actions[1].metadata.channelId).to.equal(channel.id)
expect(fetchedRule.actions[2].metadata.durationSeconds).to.equal(10)
expect(fetchedRule.actions[0].type).to.equal(
AutoModerationActionType.BlockMessage
)
expect(fetchedRule.actions[1].type).to.equal(
AutoModerationActionType.SendAlertMessage
)
expect(fetchedRule.actions[2].type).to.equal(
AutoModerationActionType.Timeout
)
expect(fetchedRule.actions[0].type).to.equal(AutoModerationActionType.BlockMessage)
expect(fetchedRule.actions[1].type).to.equal(AutoModerationActionType.SendAlertMessage)
expect(fetchedRule.actions[2].type).to.equal(AutoModerationActionType.Timeout)
await rest.deleteAutomodRule(e2ecache.guild.id, rule.id)
})
+10 -14
View File
@@ -22,7 +22,7 @@ before(async () => {
after(async () => {
if (rest.invalidBucket.timeoutId) clearTimeout(rest.invalidBucket.timeoutId)
if (e2ecache.guild.id && !e2ecache.deletedGuild) {
e2ecache.deletedGuild = true;
e2ecache.deletedGuild = true
await rest.deleteGuild(e2ecache.guild.id)
}
})
@@ -37,9 +37,9 @@ describe('[member] Member tests', async () => {
it('Gets a member list and checks if the bot is in the member list', async () => {
const members = await rest.getMembers(e2ecache.communityGuildId, {
limit: 10
limit: 10,
})
expect(members.some(m => m.user.id === rest.applicationId.toString())).to.equal(true)
expect(members.some((m) => m.user.id === rest.applicationId.toString())).to.equal(true)
})
// fetch a single member by id
@@ -64,7 +64,7 @@ describe('[member] Member tests', async () => {
// ban member from guild with a reason
it('ban member from guild with a reason', async () => {
await rest.banMember(e2ecache.communityGuildId, ianID, {
reason: 'Blame Wolf'
reason: 'Blame Wolf',
})
expect(await rest.getBan(e2ecache.communityGuildId, ianID)).to.exist
})
@@ -72,7 +72,7 @@ describe('[member] Member tests', async () => {
// ban member from guild and delete messages
it('ban member from guild and delete messages', async () => {
await rest.banMember(e2ecache.communityGuildId, ltsID, {
deleteMessageSeconds: 604800
deleteMessageSeconds: 604800,
})
expect(await rest.getBan(e2ecache.communityGuildId, ltsID)).to.exist
})
@@ -85,13 +85,9 @@ describe('[member] Member tests', async () => {
// unban member from guild
it('unban member from guild', async () => {
await Promise.all([
rest.unbanMember(e2ecache.communityGuildId, wolfID),
rest.unbanMember(e2ecache.communityGuildId, ianID)
])
await Promise.all([rest.unbanMember(e2ecache.communityGuildId, wolfID), rest.unbanMember(e2ecache.communityGuildId, ianID)])
await expect(rest.getBan(e2ecache.communityGuildId, wolfID)).to.eventually
.rejected
await expect(rest.getBan(e2ecache.communityGuildId, wolfID)).to.eventually.rejected
})
})
@@ -99,13 +95,13 @@ describe('[member] Member tests', async () => {
it("Edit a bot's nickname", async () => {
const nick = 'lts20050703'
const member = await rest.editBotMember(e2ecache.communityGuildId, {
nick
nick,
})
expect(member.nick).to.equal(nick)
// Change nickname back
const member2 = await rest.editBotMember(e2ecache.communityGuildId, {
nick: null
nick: null,
})
expect(member2.nick).to.null
})
@@ -119,7 +115,7 @@ describe('[member] Member tests', async () => {
expect(channel?.id).to.exist
const message = await rest.sendMessage(channel.id, {
content: 'https://i.imgur.com/doG55NR.png'
content: 'https://i.imgur.com/doG55NR.png',
})
expect(message?.content).to.exist
})
+51 -29
View File
@@ -13,7 +13,7 @@ before(async () => {
after(async () => {
if (rest.invalidBucket.timeoutId) clearTimeout(rest.invalidBucket.timeoutId)
if (e2ecache.guild.id && !e2ecache.deletedGuild) {
e2ecache.deletedGuild = true;
e2ecache.deletedGuild = true
await rest.deleteGuild(e2ecache.guild.id)
}
})
@@ -26,51 +26,73 @@ describe('[rest] Message related tests', () => {
})
it('With an image', async () => {
const image = await fetch("https://cdn.discordapp.com/avatars/270010330782892032/d031ea881688526d1ae235fd2843e53c.jpg?size=2048").then(async res => await res.blob()).catch(()=> undefined)
const image = await fetch('https://cdn.discordapp.com/avatars/270010330782892032/d031ea881688526d1ae235fd2843e53c.jpg?size=2048')
.then(async (res) => await res.blob())
.catch(() => undefined)
expect(image).to.not.be.undefined
if (!image) throw new Error("Was not able to fetch the image.")
if (!image) throw new Error('Was not able to fetch the image.')
const message = await rest.sendMessage('1041029705790402611', { file: { blob: image, name: "gamer" }})
const message = await rest.sendMessage('1041029705790402611', { file: { blob: image, name: 'gamer' } })
expect(message.attachments.length).to.be.greaterThan(0)
const [attachment] = message.attachments
expect(attachment.filename).to.be.equal("gamer")
expect(attachment.filename).to.be.equal('gamer')
})
})
describe('Rate limit manager testing', () => {
it('Send 10 messages to 1 channel', async () => {
await Promise.all([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(async (i) => {
await rest.sendMessage('1041029705790402611', { content: `10 messages to 1 channel testing rate limit manager ${i}` })
}))
await Promise.all(
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(async (i) => {
await rest.sendMessage('1041029705790402611', { content: `10 messages to 1 channel testing rate limit manager ${i}` })
}),
)
})
// TODO: Make this dynamic when we can create channels
const spamChannelIds = [
'1041029705790402611', '1041029706838966393',
'1041029707459731586', '1041029708004995199',
'1041029708453789766', '1041029709049385010',
'1041029709632377003', '1041029710227976313',
'1041029710764834856', '1041029711414956202',
'1041029712153149524', '1041029712933306459',
'1041029713566646313', '1041029714254508042',
'1041029714921406555', '1041029716334870629',
'1041029717127614636', '1041029717689647114',
'1041029718603997214', '1041029719925215302',
'1041029721179308082', '1041029721988812860',
'1041029722466943037', '1041029723217743964',
'1041029723872034826', '1041029724492804156',
'1041029725117743144', '1041029725818212474',
'1041029726531227741', '1041029727231684638'
'1041029705790402611',
'1041029706838966393',
'1041029707459731586',
'1041029708004995199',
'1041029708453789766',
'1041029709049385010',
'1041029709632377003',
'1041029710227976313',
'1041029710764834856',
'1041029711414956202',
'1041029712153149524',
'1041029712933306459',
'1041029713566646313',
'1041029714254508042',
'1041029714921406555',
'1041029716334870629',
'1041029717127614636',
'1041029717689647114',
'1041029718603997214',
'1041029719925215302',
'1041029721179308082',
'1041029721988812860',
'1041029722466943037',
'1041029723217743964',
'1041029723872034826',
'1041029724492804156',
'1041029725117743144',
'1041029725818212474',
'1041029726531227741',
'1041029727231684638',
]
it('Send 10 messages to 10 channels', async () => {
await Promise.all(spamChannelIds.map(async (channelId) => {
await Promise.all([...Array(10).keys()].map(async (_, index) => {
await rest.sendMessage(channelId, { content: `testing rate limit manager ${index}` })
}))
}))
await Promise.all(
spamChannelIds.map(async (channelId) => {
await Promise.all(
[...Array(10).keys()].map(async (_, index) => {
await rest.sendMessage(channelId, { content: `testing rate limit manager ${index}` })
}),
)
}),
)
})
})
})
+5 -5
View File
@@ -90,7 +90,7 @@ describe('[role] Role tests', async () => {
it('Edit the roles hoist', async () => {
expect(role.hoist).to.equal(false)
const edited = await rest.editRole(e2ecache.guild.id, role.id, {
hoist: true
hoist: true,
})
expect(edited.hoist).to.equal(true)
})
@@ -100,7 +100,7 @@ describe('[role] Role tests', async () => {
await rest.editRole(e2ecache.guild.id, role.id, { hoist: true })
const edited = await rest.editRole(e2ecache.guild.id, role.id, {
hoist: false
hoist: false,
})
expect(edited.hoist).to.equal(false)
})
@@ -108,7 +108,7 @@ describe('[role] Role tests', async () => {
// Edit the roles mentionable
it('Edit the roles mentionable', async () => {
const edited = await rest.editRole(e2ecache.guild.id, role.id, {
mentionable: true
mentionable: true,
})
expect(edited.mentionable).to.equal(true)
})
@@ -116,10 +116,10 @@ describe('[role] Role tests', async () => {
// Make mentionable false
it('Make mentionable false', async () => {
await rest.editRole(e2ecache.guild.id, role.id, {
mentionable: true
mentionable: true,
})
const edited = await rest.editRole(e2ecache.guild.id, role.id, {
mentionable: false
mentionable: false,
})
expect(edited.mentionable).to.equal(false)
})
+1 -1
View File
@@ -14,5 +14,5 @@ rest.deleteQueueDelay = 10000
export const e2ecache = {
guild: await rest.createGuild({ name: 'ddenotester' }),
deletedGuild: false,
communityGuildId: E2E_TEST_GUILD_ID
communityGuildId: E2E_TEST_GUILD_ID,
}
+1 -1
View File
@@ -1,7 +1,7 @@
import { expect } from 'chai'
import { afterEach, beforeEach, describe, it } from 'mocha'
import sinon from 'sinon'
import type { RestManager } from '../../src/manager.js'
import type { RestManager } from '../../src/types.js'
import { createRestManager } from '../../src/manager.js'
import { fakeToken as token } from '../constants.js'
+5 -9
View File
@@ -103,28 +103,24 @@ Have your cache setup in any way you like. Redis, PGSQL or any cache layer you w
Here is a minimal example to get started with:
```typescript
import {
createBot,
Intents,
startBot,
} from "https://deno.land/x/discordeno@13.0.0/mod.ts";
import { createBot, Intents, startBot } from 'https://deno.land/x/discordeno@13.0.0/mod.ts'
const bot = createBot({
token: process.env.DISCORD_TOKEN,
intents: Intents.Guilds | Intents.GuildMessages,
events: {
ready() {
console.log("Successfully connected to gateway");
console.log('Successfully connected to gateway')
},
},
});
})
// Another way to do events
bot.events.messageCreate = function (b, message) {
// Process the message here with your command handler.
};
}
await startBot(bot);
await startBot(bot)
```
### Tools
+4 -572
View File
@@ -77,50 +77,6 @@ export interface DiscordUser {
banner?: string
}
// /** https://discord.com/developers/docs/resources/user#connection-object */
// export interface DiscordConnection {
// /** id of the connection account */
// id: string
// /** The username of the connection account */
// name: string
// /** The service of the connection (twitch, youtube) */
// type: DiscordConnectionServices
// /** Whether the connection is revoked */
// revoked?: boolean
// /** Whether the connection is verified */
// verified: boolean
// /** Whether friend sync is enabled for this connection */
// friend_sync: boolean
// /** Whether activities related to this connection will be shown in presence updates */
// show_activity: boolean
// /** Visibility of this connection */
// visibility: VisibilityTypes
// /** An array of partial server integrations */
// integrations?: DiscordIntegration[]
// /** Whether this connection has a corresponding third party OAuth2 token. */
// two_way_link: boolean
// }
// /** https://discord.com/developers/docs/resources/user#connection-object-services */
// export type DiscordConnectionServices =
// | 'battlenet'
// | 'ebay'
// | 'epicgames'
// | 'facebook'
// | 'github'
// | 'leagueoflegends'
// | 'playstation'
// | 'reddit'
// | 'riotgames'
// | 'spotify'
// | 'skype'
// | 'steam'
// | 'twitch'
// | 'twitter'
// | 'xbox'
// | 'youtube'
/** https://discord.com/developers/docs/resources/guild#integration-object-integration-structure */
export interface DiscordIntegration {
/** Integration Id */
@@ -613,7 +569,6 @@ export interface DiscordGuild {
presences?: Array<Partial<DiscordPresenceUpdate>>
/** Banner hash */
banner: string | null
// TODO: Can be optimized to a number but is it worth it?
/** The preferred locale of a Community guild; used in server discovery and notices from Discord; defaults to "en-US" */
preferred_locale: string
/** The id of the channel where admins and moderators of Community guilds receive notices from Discord */
@@ -851,11 +806,6 @@ export interface DiscordThreadMetadata {
create_timestamp?: string | null
}
// export interface DiscordThreadMemberBase {
// /** Any user-thread settings, currently only used for notifications */
// flags: number
// }
export interface DiscordThreadMember {
/** Any user-thread settings, currently only used for notifications */
flags: number
@@ -867,13 +817,6 @@ export interface DiscordThreadMember {
join_timestamp: string
}
// export interface DiscordThreadMemberGuildCreate {
// /** Any user-thread settings, currently only used for notifications */
// flags: number
// /** The time the current user last joined the thread */
// join_timestamp: string
// }
/** https://discord.com/developers/docs/topics/gateway-events#activity-object */
export interface DiscordActivity {
/** The activity's name */
@@ -1376,27 +1319,6 @@ export interface DiscordInteractionDataOption {
focused?: boolean
}
// export interface DiscordInteractionDataResolved {
// /** The Ids and Message objects */
// messages?: Record<string, DiscordMessage>
// /** The Ids and User objects */
// users?: Record<string, DiscordUser>
// /** The Ids and partial Member objects */
// members?: Record<
// string,
// Omit<DiscordInteractionMember, 'user' | 'deaf' | 'mute'>
// >
// /** The Ids and Role objects */
// roles?: Record<string, DiscordRole>
// /** The Ids and partial Channel objects */
// channels?: Record<
// string,
// Pick<DiscordChannel, 'id' | 'name' | 'type' | 'permissions'>
// >
// /** The Ids and attachments objects */
// attachments?: Record<string, DiscordAttachment>
// }
export interface DiscordListActiveThreads {
/** The active threads */
threads: DiscordChannel[]
@@ -1483,7 +1405,6 @@ export enum AutoModerationTriggerTypes {
}
export interface DiscordAutoModerationRuleTriggerMetadata {
// TODO: discord is considering renaming this before release
/** The keywords needed to match. Only present when TriggerType.Keyword */
keyword_filter?: string[]
/** The pre-defined lists of words to match from. Only present when TriggerType.KeywordPreset */
@@ -2010,39 +1931,6 @@ export interface DiscordGuildPreview {
stickers: DiscordSticker[]
}
// export interface DiscordDiscoveryCategory {
// /** Numeric id of the category */
// id: number
// /** The name of this category, in multiple languages */
// name: DiscordDiscoveryName
// /** Whether this category can be set as a guild's primary category */
// is_primary: boolean
// }
// export interface DiscordDiscoveryName {
// /** The name in English */
// default: string
// /** The name in other languages */
// localizations?: Record<string, string>
// }
// export interface DiscordDiscoveryMetadata {
// /** The guild Id */
// guild_id: string
// /** The id of the primary discovery category set for this guild */
// primary_category_id: number
// /** Up to 10 discovery search keywords set for this guild */
// keywords: string[] | null
// /** Whether guild info is shown when custom emojis from this guild are clicked */
// emoji_discoverability_enabled: boolean
// /** When the server's partner application was accepted or denied, for applications via Server Settings */
// partner_actioned_timestamp: string | null
// /** When the server applied for partnership, if it has a pending application */
// partner_application_timestamp: string | null
// /** Ids of up to 5 discovery subcategories set for this guild */
// category_ids: number[]
// }
/** https://discord.com/developers/docs/resources/channel#followed-channel-object */
export interface DiscordFollowedChannel {
/** Source message id */
@@ -2081,48 +1969,6 @@ export interface DiscordGuildMembersChunk {
nonce?: string
}
// export interface DiscordComponent {
// /** component type */
// type: MessageComponentTypes
// /** a developer-defined identifier for the component, max 100 characters */
// custom_id?: string
// /** whether the component is disabled, default false */
// disabled?: boolean
// /** For different styles/colors of the buttons */
// style?: ButtonStyles | TextStyles
// /** text that appears on the button (max 80 characters) */
// label?: string
// /** the dev-define value of the option, max 100 characters for select or 4000 for input. */
// value?: string
// /** Emoji object that includes fields of name, id, and animated supporting unicode and custom emojis. */
// emoji?: {
// /** Emoji id */
// id?: string
// /** Emoji name */
// name?: string
// /** Whether this emoji is animated */
// animated?: boolean
// }
// /** optional url for link-style buttons that can navigate a user to the web. Only type 5 Link buttons can have a url */
// url?: string
// /** The choices! Maximum of 25 items. */
// options?: DiscordSelectOption[]
// /** A custom placeholder text if nothing is selected. Maximum 150 characters. */
// placeholder?: string
// /** The minimum number of items that must be selected. Default 1. Between 1-25. */
// min_values?: number
// /** The maximum number of items that can be selected. Default 1. Between 1-25. */
// max_values?: number
// /** The minimum input length for a text input. Between 0-4000. */
// min_length?: number
// /** The maximum input length for a text input. Between 1-4000. */
// max_length?: number
// /** a list of child components */
// components?: DiscordComponent[]
// /** whether this component is required to be filled, default true */
// required?: boolean
// }
/** https://discord.com/developers/docs/topics/gateway#channel-pins-update */
export interface DiscordChannelPinsUpdate {
/** The id of the guild */
@@ -2355,13 +2201,6 @@ export interface DiscordGuildStickersUpdate {
stickers: DiscordSticker[]
}
// export interface DiscordAddGuildDiscoverySubcategory {
// /** The guild Id of the subcategory was added to */
// guild_id: string
// /** The Id of the subcategory added */
// category_id: number
// }
/** https://discord.com/developers/docs/topics/gateway#guild-member-update */
export interface DiscordGuildMemberUpdate {
/** The id of the guild */
@@ -2391,12 +2230,6 @@ export interface DiscordGuildMemberUpdate {
/** https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all */
export interface DiscordMessageReactionRemoveAll extends Pick<DiscordMessageReactionAdd, 'channel_id' | 'message_id' | 'guild_id'> {}
// // TODO: add docs link
// export interface DiscordValidateDiscoverySearchTerm {
// /** Whether the provided term is valid */
// valid: boolean
// }
/** https://discord.com/developers/docs/topics/gateway#guild-role-update */
export interface DiscordGuildRoleUpdate {
/** The id of the guild */
@@ -2480,23 +2313,6 @@ export interface DiscordInstallParams {
permissions: string
}
// export interface DiscordInteractionResponse {
// type: InteractionResponseTypes
// data?: DiscordInteractionCallbackData
// }
// export interface DiscordInteractionCallbackData {
// tts?: boolean
// title?: string
// flags?: number
// content?: string
// choices?: DiscordApplicationCommandOptionChoice[]
// custom_id?: string
// embeds?: DiscordEmbed[]
// allowed_mentions?: DiscordAllowedMentions
// components?: DiscordComponent[]
// }
export interface DiscordForumTag {
/** The id of the tag */
id: string
@@ -2517,42 +2333,6 @@ export interface DiscordDefaultReactionEmoji {
emoji_name: string | null
}
// export interface DiscordCreateAutomoderationRule {
// /** The name of the rule. */
// name: string
// /** The type of event to trigger the rule on. */
// event_type: AutoModerationEventTypes
// /** The type of trigger to use for the rule. */
// trigger_type: AutoModerationTriggerTypes
// /** The metadata to use for the trigger. */
// trigger_metadata: DiscordAutoModerationRuleTriggerMetadata
// /** The actions that will trigger for this rule */
// actions: DiscordAutoModerationAction[]
// /** Whether the rule should be enabled, true by default. */
// enabled?: boolean
// /** The role ids that should not be effected by the rule */
// exempt_roles?: string[]
// /** The channel ids that should not be effected by the rule. */
// exempt_channels?: string[]
// }
// export interface DiscordModifyAutomoderationRule {
// /** The name of the rule. */
// name: string
// /** The type of event to trigger the rule on. */
// event_type: AutoModerationEventTypes
// /** The metadata to use for the trigger. */
// trigger_metadata: DiscordAutoModerationRuleTriggerMetadata
// /** The actions that will trigger for this rule */
// actions: DiscordAutoModerationAction[]
// /** Whether the rule should be enabled, true by default. */
// enabled?: boolean
// /** The role ids that should not be effected by the rule */
// exempt_roles?: string[]
// /** The channel ids that should not be effected by the rule. */
// exempt_channels?: string[]
// }
export interface DiscordModifyChannel {
/** 1-100 character channel name */
name?: string
@@ -2679,26 +2459,6 @@ export interface DiscordCreateGuildChannel {
default_sort_order?: SortOrderTypes | null
}
// export interface DiscordBulkDeleteMessages {
// messages: string[]
// }
// /** https://discord.com/developers/docs/resources/channel#edit-message-json-params */
// export interface DiscordEditMessage {
// /** The new message contents (up to 2000 characters) */
// content?: string | null
// /** Embedded `rich` content (up to 6000 characters) */
// embeds?: DiscordEmbed[] | null
// /** Edit the flags of the message (only `SUPPRESS_EMBEDS` can currently be set/unset) */
// flags?: 4 | null
// /** Allowed mentions for the message */
// allowed_mentions?: DiscordAllowedMentions
// /** When specified (adding new attachments), attachments which are not provided in this list will be removed. */
// attachments?: DiscordAttachment[]
// /** The components you would like to have sent in this message */
// components?: DiscordMessageComponents
// }
export interface DiscordCreateMessage {
/** The message contents (up to 2000 characters) */
content?: string
@@ -2707,9 +2467,9 @@ export interface DiscordCreateMessage {
/** true if this is a TTS message */
tts?: boolean
/** Embedded `rich` content (up to 6000 characters) */
// embeds?: DiscordEmbed[]
embeds?: DiscordEmbed[]
/** Allowed mentions for the message */
// allowed_mentions?: DiscordAllowedMentions
allowed_mentions?: DiscordAllowedMentions
/** Include to make your message a reply */
message_reference?: {
/** id of the originating message */
@@ -2725,166 +2485,11 @@ export interface DiscordCreateMessage {
fail_if_not_exists: boolean
}
/** The components you would like to have sent in this message */
// components?: DiscordMessageComponents
components?: DiscordMessageComponents
/** IDs of up to 3 stickers in the server to send in the message */
stickerIds?: [string] | [string, string] | [string, string, string]
}
// export interface DiscordCreateScheduledEvent {
// /** the channel id of the scheduled event. */
// channel_id?: string
// /** location of the event. Required for events with `entityType: ScheduledEventEntityType.External` */
// location?: string
// /** the name of the scheduled event */
// name: string
// /** the description of the scheduled event */
// description: string
// /** the time the scheduled event will start */
// scheduled_start_time: string
// /** the time the scheduled event will end if it does end. Required for events with `entityType: ScheduledEventEntityType.External` */
// scheduled_end_time?: string
// /** the privacy level of the scheduled event */
// privacy_level?: ScheduledEventPrivacyLevel
// /** the type of hosting entity associated with a scheduled event */
// entity_type: ScheduledEventEntityType
// }
// export interface DiscordEditScheduledEvent {
// /** the channel id of the scheduled event. null if switching to external event. */
// channel_id: string | null
// /** location of the event */
// location?: string
// /** the name of the scheduled event */
// name: string
// /** the description of the scheduled event */
// description?: string
// /** the time the scheduled event will start */
// scheduled_start_time: string
// /** the time the scheduled event will end if it does end. */
// scheduled_end_time?: string
// /** the privacy level of the scheduled event */
// privacy_level: ScheduledEventPrivacyLevel
// /** the type of hosting entity associated with a scheduled event */
// entity_type: ScheduledEventEntityType
// /** the status of the scheduled event */
// status: ScheduledEventStatus
// }
// export interface DiscordCreateChannelInvite {
// /** Duration of invite in seconds before expiry, or 0 for never. Between 0 and 604800 (7 days). Default: 86400 (24 hours) */
// max_age?: number
// /** Max number of users or 0 for unlimited. Between 0 and 100. Default: 0 */
// max_uses?: number
// /** Whether this invite only grants temporary membership. Default: false */
// temporary?: boolean
// /** If true, don't try to reuse similar invite (useful for creating many unique one time use invites). Default: false */
// unique?: boolean
// /** The type of target for this voice channel invite */
// target_type?: TargetTypes
// /** The id of the user whose stream to display for this invite, required if `target_type` is 1, the user must be streaming in the channel */
// target_user_id?: string
// /** The id of the embedded application to open for this invite, required if `target_type` is 2, the application must have the `EMBEDDED` flag */
// target_application_id?: string
// }
// /** https://discord.com/developers/docs/resources/guild#update-current-user-voice-state */
// export interface DiscordEditOwnVoiceState {
// /** The id of the channel the user is currently in */
// channel_id: string
// /** Toggles the user's suppress state */
// suppress?: boolean
// /** Sets the user's request to speak */
// request_to_speak_timestamp?: number | null
// }
// /** https://discord.com/developers/docs/resources/guild#update-user-voice-state */
// export interface DiscordEditUserVoiceState {
// /** The id of the channel the user is currently in */
// channel_id: string
// /** Toggles the user's suppress state */
// suppress?: boolean
// /** The user id to target */
// user_id: string
// }
// export interface DiscordEditGuildWidgetSettings {
// /** Whether or not the widget is enabled. */
// enabled: boolean
// /** The channel id if any for this widget. */
// channel_id?: string | null
// }
// /** https://discord.com/developers/docs/resources/guild#create-guild */
// export interface DiscordCreateGuild {
// /** Name of the guild (1-100 characters) */
// name: string
// /** Base64 128x128 image for the guild icon */
// icon?: string
// /** Verification level */
// verification_level?: VerificationLevels
// /** Default message notification level */
// default_message_notifications?: DefaultMessageNotificationLevels
// /** Explicit content filter level */
// explicit_content_filter?: ExplicitContentFilterLevels
// /** New guild roles (first role is the everyone role) */
// roles?: DiscordRole[]
// /** New guild's channels */
// channels?: Array<Partial<DiscordChannel>>
// /** Id for afk channel */
// afk_channel_id?: string
// /** Afk timeout in seconds */
// afk_timeout?: number
// /** The id of the channel where guild notices such as welcome messages and boost events are posted */
// system_channel_id?: string
// /** System channel flags */
// system_channel_flags?: SystemChannelFlags
// }
// /** https://discord.com/developers/docs/resources/guild#modify-guild */
// export interface DiscordModifyGuild {
// /** Guild name */
// name?: string
// /** Verification level */
// verification_level?: VerificationLevels | null
// /** Default message notification filter level */
// default_message_notifications?: DefaultMessageNotificationLevels | null
// /** Explicit content filter level */
// explicit_content_filter?: ExplicitContentFilterLevels | null
// /** Id for afk channel */
// afk_channel_id?: string | null
// /** Afk timeout in seconds */
// afk_timeout?: number
// /** Base64 1024x1024 png/jpeg/gif image for the guild icon (can be animated gif when the server has the `ANIMATED_ICON` feature) */
// icon?: string | null
// /** User id to transfer guild ownership to (must be owner) */
// owner_id?: string
// /** Base64 16:9 png/jpeg image for the guild splash (when the server has `INVITE_SPLASH` feature) */
// splash?: string | null
// /** Base64 16:9 png/jpeg image for the guild discovery spash (when the server has the `DISCOVERABLE` feature) */
// discovery_splash?: string | null
// /** Base64 16:9 png/jpeg image for the guild banner (when the server has BANNER feature) */
// banner?: string | null
// /** The id of the channel where guild notices such as welcome messages and boost events are posted */
// system_channel_id?: string | null
// /** System channel flags */
// system_channel_flags?: SystemChannelFlags
// /** The id of the channel where Community guilds display rules and/or guidelines */
// rules_channel_id?: string | null
// /** The id of the channel where admins and moderators of Community guilds receive notices from Discord */
// public_updates_channel_id?: string | null
// /** The preferred locale of a Community guild used in server discovery and notices from Discord; defaults to "en-US" */
// preferred_locale?: string | null
// /** Enabled guild features */
// features?: GuildFeatures[]
// /** Whether the guild's boost progress bar should be enabled */
// premium_progress_bar_enabled?: boolean
// }
// export interface DiscordEditGuildMFALevel {
// /** The level to set for the guilds mfa level. */
// level: MfaLevels
// }
/** https://discord.com/developers/docs/resources/guild#modify-guild-welcome-screen */
export interface DiscordModifyGuildWelcomeScreen {
/** Whether the welcome screen is enabled */
@@ -2895,31 +2500,6 @@ export interface DiscordModifyGuildWelcomeScreen {
description?: string | null
}
// export interface DiscordStartThreadWithMessage {
// /** 1-100 character thread name */
// name: string
// /** Duration in minutes to automatically archive the thread after recent activity */
// auto_archive_duration: 60 | 1440 | 4320 | 10080
// /** Amount of seconds a user has to wait before sending another message (0-21600) */
// rate_limit_per_user?: number | null
// }
// export interface DiscordStartThreadWithoutMessage {
// /** 1-100 character thread name */
// name: string
// /** Duration in minutes to automatically archive the thread after recent activity */
// auto_archive_duration: 60 | 1440 | 4320 | 10080
// /** Amount of seconds a user has to wait before sending another message (0-21600) */
// rate_limit_per_user?: number | null
// /** the type of thread to create */
// type:
// | ChannelTypes.AnnouncementThread
// | ChannelTypes.PublicThread
// | ChannelTypes.PrivateThread
// /** whether non-moderators can add other non-moderators to a thread; only available when creating a private thread */
// invitable?: boolean
// }
export interface DiscordFollowAnnouncementChannel {
/** The id of the channel to send announcements to. */
webhook_channel_id: string
@@ -2946,113 +2526,6 @@ export interface DiscordModifyGuildChannelPositions {
parent_id?: string | null
}
// /** https://discord.com/developers/docs/resources/guild#create-guild-ban */
// export interface DiscordCreateGuildBan {
// /** Number of seconds to delete messages for, between 0 and 604800 (7 days) */
// delete_message_seconds?: number
// }
// export interface DiscordEditBotMemberOptions {
// nick?: string | null
// }
// /** https://discord.com/developers/docs/resources/guild#modify-guild-member */
// export interface DiscordModifyGuildMember {
// /** Value to set users nickname to. Requires the `MANAGE_NICKNAMES` permission */
// nick?: string | null
// /** Array of role ids the member is assigned. Requires the `MANAGE_ROLES` permission */
// roles?: string[] | null
// /** Whether the user is muted in voice channels. Will throw a 400 if the user is not in a voice channel. Requires the `MUTE_MEMBERS` permission */
// mute?: boolean | null
// /** Whether the user is deafened in voice channels. Will throw a 400 if the user is not in a voice channel. Requires the `MOVE_MEMBERS` permission */
// deaf?: boolean | null
// /** Id of channel to move user to (if they are connected to voice). Requires the `MOVE_MEMBERS` permission */
// channel_id?: string | null
// /** when the user's timeout will expire and the user will be able to communicate in the guild again (up to 28 days in the future), set to null to remove timeout. Requires the `MODERATE_MEMBERS` permission */
// communication_disabled_until?: number | null
// }
// export interface DiscordGetDMChannel {
// /** The user id */
// recipient_id: string
// }
// /** https://discord.com/developers/docs/resources/guild#begin-guild-prune */
// export interface DiscordBeginGuildPrune {
// /** Number of days to prune (1 or more), default: 7 */
// days?: number
// /** Whether 'pruned' is returned, discouraged for large guilds, default: true */
// compute_prune_count?: boolean
// /** Role(s) ro include, default: none */
// include_roles?: string[]
// }
// export interface DiscordCreateGuildRole {
// /** Name of the role, max 100 characters, default: "new role" */
// name?: string
// /** Bitwise value of the enabled/disabled permissions, default: everyone permissions in guild */
// permissions?: string
// /** RGB color value, default: 0 */
// color?: number
// /** Whether the role should be displayed separately in the sidebar, default: false */
// hoist?: boolean
// /** Whether the role should be mentionable, default: false */
// mentionable?: boolean
// /** The role's unicode emoji (if the guild has the `ROLE_ICONS` feature) */
// unicode_emoji?: string
// /** the role's icon image (if the guild has the `ROLE_ICONS` feature) */
// icon?: string
// }
// export interface DiscordEditGuildRole {
// /** Name of the role, max 100 characters, default: "new role" */
// name?: string
// /** Bitwise value of the enabled/disabled permissions, default: everyone permissions in guild */
// permissions?: string
// /** RGB color value, default: 0 */
// color?: number
// /** Whether the role should be displayed separately in the sidebar, default: false */
// hoist?: boolean
// /** Whether the role should be mentionable, default: false */
// mentionable?: boolean
// /** The role's unicode emoji (if the guild has the `ROLE_ICONS` feature) */
// unicode_emoji?: string
// /** the role's icon image (if the guild has the `ROLE_ICONS` feature) */
// icon?: string
// }
// export interface DiscordModifyRolePositions {
// /** The role id */
// id: string
// /** The sorting position for the role. */
// position?: number | null
// }
// export interface DiscordCreateGuildStickerOptions {
// /** Name of the sticker (2-30 characters) */
// name: string
// /** Description of the sticker (empty or 2-100 characters) */
// description: string
// /** Autocomplete/suggestion tags for the sticker (max 200 characters) */
// tags: string
// }
// export interface DiscordEditGuildStickerOptions {
// /** Name of the sticker (2-30 characters) */
// name?: string
// /** Description of the sticker (empty or 2-100 characters) */
// description?: string | null
// /** Autocomplete/suggestion tags for the sticker (max 200 characters) */
// tags?: string
// }
// export interface DiscordCreateTemplate {
// /** Name which the template should have */
// name: string
// /** Description of the template */
// description?: string
// }
export interface DiscordCreateWebhook {
/** Name of the webhook (1-80 characters) */
name: string
@@ -3060,39 +2533,6 @@ export interface DiscordCreateWebhook {
avatar?: string | null
}
// export interface DiscordModifyWebhook {
// /** The default name of the webhook */
// name?: string
// /** Image for the default webhook avatar */
// avatar?: string | null
// /** The new channel id this webhook should be moved to */
// channel_id?: string
// }
// /** https://discord.com/developers/docs/resources/webhook#execute-webhook */
// export interface DiscordExecuteWebhook {
// /** Waits for server confirmation of message send before response, and returns the created message body (defaults to `false`; when `false` a message that is not saved does not return an error) */
// wait?: boolean
// /** Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived. */
// thread_id?: string
// /** Name of the thread to create (target channel has to be type of forum channel) */
// thread_name?: string
// /** The message contents (up to 2000 characters) */
// content?: string
// /** Override the default username of the webhook */
// username?: string
// /** Override the default avatar of the webhook */
// avatar_url?: string
// /** True if this is a TTS message */
// tts?: boolean
// /** Embedded `rich` content */
// embeds?: DiscordEmbed[]
// /** Allowed mentions for the message */
// allowed_mentions?: DiscordAllowedMentions
// /** the components to include with the message */
// components?: DiscordMessageComponents
// }
/** https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel */
export interface DiscordCreateForumPostWithMessage {
/** 1-100 character channel name */
@@ -3126,14 +2566,6 @@ export interface DiscordCreateForumPostWithMessage {
applied_tags?: string[]
}
// /** https://discord.com/developers/docs/resources/guild-template#modify-guild-template */
// export interface DiscordModifyGuildTemplate {
// /** name of the template (1-100 characters) */
// name?: string
// /** description for the template (0-120 characters) */
// description?: string
// }
export type DiscordArchivedThreads = DiscordActiveThreads & {
hasMore: boolean
}
@@ -3150,4 +2582,4 @@ export interface DiscordVanityUrl {
export interface DiscordPrunedCount {
pruned: number
}
}
-25
View File
@@ -69,19 +69,6 @@ export interface CreateMessageOptions {
/** IDs of up to 3 stickers in the server to send in the message */
stickerIds?: [BigString] | [BigString, BigString] | [BigString, BigString, BigString]
}
// import type {
// AllowedMentionsTypes,
// ApplicationCommandTypes,
// AuditLogEvents,
// BigString,
// ButtonStyles,
// InteractionResponseTypes,
// Localization,
// MessageComponentTypes,
// OverwriteTypes,
// PermissionStrings,
// TextStyles
// } from './shared.js'
export type MessageComponents = ActionRow[]
@@ -296,17 +283,6 @@ export interface OverwriteReadable {
deny?: PermissionStrings[]
}
// export interface GetGatewayBot {
// url: string
// shards: number
// sessionStartLimit: {
// total: number
// remaining: number
// resetAfter: number
// maxConcurrency: number
// }
// }
/** https://discord.com/developers/docs/resources/channel#get-channel-messages-query-string-params */
export interface GetMessagesLimit {
/** Max number of messages to return (1-100) default 50 */
@@ -815,7 +791,6 @@ export interface EditAutoModerationRuleOptions extends WithReason {
triggerMetadata: {
/** The keywords needed to match. Only present when TriggerType.Keyword */
keywordFilter?: string[]
// TODO: This may need a special type or enum
/** The pre-defined lists of words to match from. Only present when TriggerType.KeywordPreset */
presets?: DiscordAutoModerationRuleTriggerMetadataPresets[]
/** The substrings which will exempt from triggering the preset trigger type. Only present when TriggerType.KeywordPreset */
+3 -578
View File
@@ -7,14 +7,6 @@ export enum PresenceStatus {
offline,
}
// /* https://discord.com/developers/docs/resources/channel#message-object-message-flags */
// export enum ApplicationCommandFlags {
// /** Do not include any embeds when serialising this message */
// SuppressEmbeds = 1 << 2,
// /** Only visible to the user who invoked the interaction */
// Ephemeral = 1 << 6,
// }
/** https://discord.com/developers/docs/resources/user#user-object-premium-types */
export enum PremiumTypes {
None,
@@ -57,14 +49,6 @@ export enum IntegrationExpireBehaviors {
Kick,
}
// /** https://discord.com/developers/docs/resources/user#connection-object-visibility-types */
// export enum VisibilityTypes {
// /** Invisible to everyone except the user themselves */
// None,
// /** Visible to everyone */
// Everyone,
// }
/** https://discord.com/developers/docs/topics/teams#data-models-membership-state-enum */
export enum TeamMembershipStates {
Invited = 1,
@@ -189,18 +173,6 @@ export enum VerificationLevels {
VeryHigh,
}
// /** https://discord.com/developers/docs/topics/permissions#role-object-role-structure */
// export interface BaseRole {
// /** Role name */
// name: string
// /** Integer representation of hexadecimal color code */
// color: number
// /** Position of this role */
// position: number
// /** role unicode emoji */
// unicodeEmoji?: string
// }
/** https://discord.com/developers/docs/resources/guild#guild-object-guild-features */
export enum GuildFeatures {
/** Guild has access to set an invite splash background */
@@ -525,8 +497,6 @@ export enum AuditLogEvents {
}
export enum ScheduledEventPrivacyLevel {
/** the scheduled event is public and available in discovery. DISCORD DEVS DISABLED THIS! WILL ERROR IF USED! */
// Public = 1,
/** the scheduled event is only accessible to guild members */
GuildOnly = 2,
}
@@ -565,19 +535,6 @@ export enum ApplicationCommandPermissionTypes {
Channel,
}
// /** https://discord.com/developers/docs/topics/gateway#activity-object-activity-flags */
// export enum ActivityFlags {
// Instance = 1 << 0,
// Join = 1 << 1,
// Spectate = 1 << 2,
// JoinRequest = 1 << 3,
// Sync = 1 << 4,
// Play = 1 << 5,
// PartyPrivacyFriends = 1 << 6,
// PartyPrivacyVoiceChannel = 1 << 7,
// Embedded = 1 << 8,
// }
/** https://discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags */
export enum BitwisePermissionFlags {
/** Allows creation of instant invites */
@@ -666,314 +623,6 @@ export enum BitwisePermissionFlags {
export type PermissionStrings = keyof typeof BitwisePermissionFlags
// /** https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice */
// export enum VoiceOpcodes {
// /** Begin a voice websocket connection. */
// Identify,
// /** Select the voice protocol. */
// SelectProtocol,
// /** Complete the websocket handshake. */
// Ready,
// /** Keep the websocket connection alive. */
// Heartbeat,
// /** Describe the session. */
// SessionDescription,
// /** Indicate which users are speaking. */
// Speaking,
// /** Sent to acknowledge a received client heartbeat. */
// HeartbeatACK,
// /** Resume a connection. */
// Resume,
// /** Time to wait between sending heartbeats in milliseconds. */
// Hello,
// /** Acknowledge a successful session resume. */
// Resumed,
// /** A client has disconnected from the voice channel */
// ClientDisconnect = 13,
// }
// /** https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice */
// export enum VoiceCloseEventCodes {
// /** You sent an invalid [opcode](https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice-voice-opcodes). */
// UnknownOpcode = 4001,
// /** You sent a invalid payload in your [identifying](https://discord.com/developers/docs/topics/gateway#identify) to the Gateway. */
// FailedToDecodePayload,
// /** You sent a payload before [identifying](https://discord.com/developers/docs/topics/gateway#identify) with the Gateway. */
// NotAuthenticated,
// /** The token you sent in your [identify](https://discord.com/developers/docs/topics/gateway#identify) payload is incorrect. */
// AuthenticationFailed,
// /** You sent more than one [identify](https://discord.com/developers/docs/topics/gateway#identify) payload. Stahp. */
// AlreadyAuthenticated,
// /** Your session is no longer valid. */
// SessionNoLongerValid,
// /** Your session has timed out. */
// SessionTimedOut = 4009,
// /** We can't find the server you're trying to connect to. */
// ServerNotFound = 4011,
// /** We didn't recognize the [protocol](https://discord.com/developers/docs/topics/voice-connections#establishing-a-voice-udp-connection-example-select-protocol-payload) you sent. */
// UnknownProtocol,
// /** Channel was deleted, you were kicked, voice server changed, or the main gateway session was dropped. Should not reconnect. */
// Disconnect = 4014,
// /** The server crashed. Our bad! Try [resuming](https://discord.com/developers/docs/topics/voice-connections#resuming-voice-connection). */
// VoiceServerCrashed,
// /** We didn't recognize your [encryption](https://discord.com/developers/docs/topics/voice-connections#encrypting-and-sending-voice). */
// UnknownEncryptionMode,
// }
// /** https://discord.com/developers/docs/topics/opcodes-and-status-codes#rpc */
// export enum RpcErrorCodes {
// /** An unknown error occurred. */
// UnknownError = 1000,
// /** You sent an invalid payload. */
// InvalidPayload = 4000,
// /** Invalid command name specified. */
// InvalidCommand = 4002,
// /** Invalid guild ID specified. */
// InvalidGuild,
// /** Invalid event name specified. */
// InvalidEvent,
// /** Invalid channel ID specified. */
// InvalidChannel,
// /** You lack permissions to access the given resource. */
// InvalidPermissions,
// /** An invalid OAuth2 application ID was used to authorize or authenticate with. */
// InvalidClientId,
// /** An invalid OAuth2 application origin was used to authorize or authenticate with. */
// InvalidOrigin,
// /** An invalid OAuth2 token was used to authorize or authenticate with. */
// InvalidToken,
// /** The specified user ID was invalid. */
// InvalidUser,
// /** A standard OAuth2 error occurred; check the data object for the OAuth2 error details. */
// OAuth2Error = 5000,
// /** An asynchronous `SELECT_TEXT_CHANNEL`/`SELECT_VOICE_CHANNEL` command timed out. */
// SelectChannelTimedOut,
// /** An asynchronous `GET_GUILD` command timed out. */
// GetGuildTimedOut,
// /** You tried to join a user to a voice channel but the user was already in one. */
// SelectVoiceForceRequired,
// /** You tried to capture more than one shortcut key at once. */
// CaptureShortcutAlreadyListening,
// }
// /** https://discord.com/developers/docs/topics/opcodes-and-status-codes#rpc */
// export enum RpcCloseEventCodes {
// /** You connected to the RPC server with an invalid client ID. */
// InvalidClientId = 4000,
// /** You connected to the RPC server with an invalid origin. */
// InvalidOrigin,
// /** You are being rate limited. */
// RateLimited,
// /** The OAuth2 token associated with a connection was revoked, get a new one! */
// TokenRevoked,
// /** The RPC Server version specified in the connection string was not valid. */
// InvalidVersion,
// /** The encoding specified in the connection string was not valid. */
// InvalidEncoding,
// }
// /** https://discord.com/developers/docs/topics/opcodes-and-status-codes#json */
// export enum JsonErrorCodes {
// /** General error (such as a malformed request body, amongst other things) */
// GeneralError,
// UnknownAccount = 10001,
// UnknownApplication,
// UnknownChannel,
// UnknownGuild,
// UnknownIntegration,
// UnknownInvite,
// UnknownMember,
// UnknownMessage,
// UnknownPermissionOverwrite,
// UnknownProvider,
// UnknownRole,
// UnknownToken,
// UnknownUser,
// UnknownEmoji,
// UnknownWebhook,
// UnknownWebhookService,
// UnknownSession = 10020,
// UnknownBan = 10026,
// UnknownSKU,
// UnknownStoreListing,
// UnknownEntitlement,
// UnknownBuild,
// UnknownLobby,
// UnknownBranch,
// UnknownStoreDirectoryLayout,
// UnknownRedistributable = 10036,
// UnknownGiftCode = 10038,
// UnknownStream = 10049,
// UnknownPremiumServerSubscribeCooldown,
// UnknownGuildTemplate = 10057,
// UnknownDiscoveryCategory = 10059,
// UnknownSticker,
// UnknownInteraction = 10062,
// UnknownApplicationCommand = 10063,
// UnknownVoiceState = 10065,
// UnknownApplicationCommandPermissions,
// UnknownStageInstance,
// UnknownGuildMemberVerificationForm,
// UnknownGuildWelcomeScreen,
// UnknownGuildScheduledEvent,
// UnknownGuildScheduledEventUser,
// UnknownTag = 10087,
// BotsCannotUseThisEndpoint = 20001,
// OnlyBotsCanUseThisEndpoint,
// ExplicitContentCannotBeSentToTheDesiredRecipient = 20009,
// YouAreNotAuthorizedToPerformThisActionOnThisApplication = 20012,
// ThisActionCannotBePerformedDueToSlowmodeRateLimit = 20016,
// OnlyTheOwnerOfThisAccountCanPerformThisAction = 20018,
// ThisMessageCannotBeEditedDueToAnnouncementRateLimits = 20022,
// UnderMinimumAge = 20024,
// TheChannelYouAreWritingHasHitTheWriteRateLimit = 20028,
// TheWriteActionYouArePerformingOnTheServerHasHitTheWriteRateLimit,
// YourStageTopicOrServerNameOrServerDescriptionOrChannelNamesContainsWordsThatAreNotAllowedForPublicStages = 20031,
// GuildPremiumSubscriptionLevelTooLow = 20035,
// MaximumNumberOfGuildsReached = 30001,
// MaximumNumberOfFriendsReached,
// MaximumNumberOfPinsReachedForTheChannel,
// MaximumNumberOfRecipientsReached,
// MaximumNumberOfGuildRolesReached,
// MaximumNumberOfWebhooksReached = 30007,
// MaximumNumberOfEmojisReached,
// MaximumNumberOfReactionsReached = 30010,
// MaximumNumberOfGuildChannelsReached = 30013,
// MaximumNumberOfAttachmentsInAMessageReached = 30015,
// MaximumNumberOfInvitesReached,
// MaximumNumberOfAnimatedEmojisReached = 30018,
// MaximumNumberOfServerMembersReached,
// MaximumNumberOfServerCategoriesHasBeenReached = 30030,
// GuildAlreadyHasTemplate,
// MaximumNumbersOfApplicationCommandsReached,
// MaxNumberOfThreadParticipantsHasBeenReached,
// MaxNumberOfDailyApplicationCommandCreatesHasBeenReached,
// MaximumNumberOfBansForNonGuildMembersHaveBeenExceeded,
// MaximumNumberOfBansFetchesHasBeenReached = 30037,
// MaximumNumberOfUncompletedGuildScheduledEventsReached = 30038,
// MaximumNumberOfStickersReached = 30039,
// MaximumNumberOfPruneRequestsHasBeenReachedTryAgainLater,
// MaximumNumberOfGuildWidgetSettingsUpdatesHasBeenReachedTryAgainLater = 30042,
// MaximumNumberOfEditsToMessagesOlderThan1HourReachedTryAgainLater = 30046,
// MaximumNumberOfPinnedThreadsInAForumChannelHasBeenReached,
// MaxiumNumberOfTagsInAForumChannelHasBeenReached,
// BitrateIsTooHighForChannelOfThisType = 30052,
// UnauthorizedProvideAValidTokenAndTryAgain = 40001,
// YouNeedToVerifyYourAccountInOrderToPerformThisAction,
// YouAreOpeningDirectMessagesTooFast,
// SendMessagesHasBeenTemporarilyDisabled,
// RequestEntityTooLargeTrySendingSomethingSmallerInSize,
// ThisFeatureHasBeenTemporarilyDisabledServerSide,
// ThisUserBannedFromThisGuild,
// ConnectionHasBeenRevoked = 40012,
// TargetUserIsNotConnectedToVoice = 40032,
// ThisMessageHasAlreadyBeenCrossposted,
// AnApplicationCommandWithThatNameAlreadyExists = 40041,
// ApplicationInteractionFailedToSend = 40043,
// InteractionHasAlreadyBeenAcknowledged = 40060,
// MissingAccess = 50001,
// InvalidAccountType,
// CannotExecuteActionOnADMChannel,
// GuildWidgetDisabled,
// CannotEditMessageAuthoredByAnotherUser,
// CannotSendAnEmptyMessage,
// CannotSendMessagesToThisUser,
// CannotSendMessagesInANonTextChannel,
// ChannelVerificationLevelIsTooHighForYouToGainAccess,
// OAuth2ApplicationDoesNotHaveABot,
// OAuth2ApplicationLimitReached,
// InvalidOAuth2State,
// YouLackPermissionsToPerformThatAction,
// InvalidAuthenticationTokenProvided,
// NoteWasTooLong,
// ProvidedTooFewOrTooManyMessagesToDeleteMustProvideAtLeast2AndFewerThan100MessagesToDelete,
// InvalidMFALevel,
// AMessageCanOnlyBePinnedInTheChannelItWasSentIn = 50019,
// InviteCodeWasEitherInvalidOrTaken,
// CannotExecuteActionOnASystemMessage,
// CannotExecuteActionOnThisChannelType = 50024,
// InvalidOAuth2AccessTokenProvided,
// MissingRequiredOAuth2Scope,
// InvalidWebhookTokenProvided,
// InvalidRole,
// InvalidRecipients = 50033,
// AMessageProvidedWasTooOldToBulkDelete,
// /** Invalid form body (returned for both `application/json` and `multipart/form-data` bodies), or invalid `Content-Type` provided */
// InvalidFormBodyOrContentTypeProvided,
// AnInviteWasAcceptedToAGuildTheApplicationsBotIsNotIn,
// InvalidActivityAction = 50039,
// InvalidApiVersionProvided = 50041,
// FileUploadedExceedsTheMaximumSize = 50045,
// InvalidFileUploaded,
// CannotSelfRedeemThisGift = 50054,
// InvalidGuild,
// InvalidMessageType = 50068,
// PaymentSourceRequiredToRedeemGift = 50070,
// CannotDeleteAChannelRequiredForCommunityGuilds = 50074,
// CannotEditStickersWithinAMessage = 50080,
// InvalidStickerSent,
// TriedToPerformAnOperationOnAnArchivedThreadSuchAsEditingAMessageOrAddingAUserToTheThread = 50083,
// InvalidThreadNotificationSettings,
// BeforeValueIsEarlierThanTheThreadCreationDate,
// CommunityServerChannelsMustBeTextChannels,
// ThisServerIsNotAvailableInYourLocation = 50095,
// ThisServerNeedsMonetizationEnabledInOrderToPerformThisAction = 50097,
// ThisServerNeedsMoreBoostsToPerformThisAction = 50101,
// TheRequestBodyContainsInvalidJSON = 50109,
// OwnershipCannotBeTransferredToABotUser = 50132,
// FailedToResizeAssetBelowTheMaximumSize = 50138,
// UploadedFileNotFound = 50146,
// TwoFactorIsRequiredForThisOperation = 60003,
// NoUsersWithDiscordTagExist = 80004,
// ReactionWasBlocked = 90001,
// ApplicationNotYetAvailable = 110001,
// ApiResourceIsCurrentlyOverloadedTryAgainALittleLater = 130000,
// TheStageIsAlreadyOpen = 150006,
// CannotReplyWithoutPermissionToReadMessageHistory = 160002,
// AThreadHasAlreadyBeenCreatedForThisMessage = 160004,
// ThreadIsLocked = 160005,
// MaximumNumberOfActiveThreadsReached = 160006,
// MaximumNumberOfActiveAnnouncementThreadsReached = 160007,
// InvalidJsonForUploadedLottieFile = 170001,
// UploadedLottiesCannotContainRasterizedImagesSuchAsPngOrJpeg,
// StickerMaximumFramerateExceeded,
// StickerFrameCountExceedsMaximumOf1000Frames,
// LottieAnimationMaximumDimensionsExceeded,
// StickerFrameRateIsEitherTooSmallOrTooLarge,
// StickerAnimationDurationExceedsMaximumOf5Seconds,
// CannotUpdateAFinishedEvent = 180000,
// FailedToCreateStageNeededForStageEvent = 180002,
// MessageWasBlockedByAutomaticModeration = 200000,
// TitleWasBlockedByAutomaticModeration,
// WebhooksCanOnlyCreateThreadsInForumChannels = 220003,
// }
// /** https://discord.com/developers/docs/topics/opcodes-and-status-codes#http */
// export enum HTTPResponseCodes {
// /** The request completed successfully. */
// Ok = 200,
// /** The entity was created successfully. */
// Created,
// /** The request completed successfully but returned no content. */
// NoContent = 204,
// /** The entity was not modified (no action was taken). */
// NotModified = 304,
// /** The request was improperly formatted, or the server couldn't understand it. */
// BadRequest = 400,
// /** The `Authorization` header was missing or invalid. */
// Unauthorized,
// /** The `Authorization` token you passed did not have permission to the resource. */
// Forbidden = 403,
// /** The resource at the location specified doesn't exist. */
// NotFound,
// /** The HTTP method used is not valid for the location specified. */
// MethodNotAllowed,
// /** You are being rate limited, see [Rate Limits](https://discord.com/developers/docs/topics/rate-limits). */
// TooManyRequests = 429,
// /** There was not a gateway available to process your request. Wait a bit and retry. */
// GatewayUnavailable = 502,
// }
/** https://discord.com/developers/docs/topics/opcodes-and-status-codes#opcodes-and-status-codes */
export enum GatewayCloseEventCodes {
/** A normal closure of the gateway. You may attempt to reconnect. */
@@ -1008,12 +657,6 @@ export enum GatewayCloseEventCodes {
DisallowedIntents,
}
// /** https://discord.com/developers/docs/resources/invite#invite-object-invite-target-types */
// export enum InviteTargetTypes {
// Stream = 1,
// EmbeddedApplication,
// }
/** https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes */
export enum GatewayOpcodes {
/** An event was dispatched. */
@@ -1227,8 +870,6 @@ export enum GatewayIntents {
AutoModerationExecution = 1 << 21,
}
// ALIASES JUST FOR BETTER UX IN THIS CASE
/** https://discord.com/developers/docs/topics/gateway#list-of-intents */
export const Intents = GatewayIntents
@@ -1266,129 +907,6 @@ export type ImageFormat = 'jpg' | 'jpeg' | 'png' | 'webp' | 'gif' | 'json'
/** https://discord.com/developers/docs/reference#image-formatting */
export type ImageSize = 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096
// export enum Errors {
// // Bot Role errors
// BOTS_HIGHEST_ROLE_TOO_LOW = 'BOTS_HIGHEST_ROLE_TOO_LOW',
// // Channel Errors
// CHANNEL_NOT_FOUND = 'CHANNEL_NOT_FOUND',
// CHANNEL_NOT_IN_GUILD = 'CHANNEL_NOT_IN_GUILD',
// CHANNEL_NOT_TEXT_BASED = 'CHANNEL_NOT_TEXT_BASED',
// CHANNEL_NOT_STAGE_VOICE = 'CHANNEL_NOT_STAGE_VOICE',
// MESSAGE_MAX_LENGTH = 'MESSAGE_MAX_LENGTH',
// RULES_CHANNEL_CANNOT_BE_DELETED = 'RULES_CHANNEL_CANNOT_BE_DELETED',
// UPDATES_CHANNEL_CANNOT_BE_DELETED = 'UPDATES_CHANNEL_CANNOT_BE_DELETED',
// INVALID_TOPIC_LENGTH = 'INVALID_TOPIC_LENGTH',
// // Guild Errors
// GUILD_NOT_DISCOVERABLE = 'GUILD_NOT_DISCOVERABLE',
// GUILD_WIDGET_NOT_ENABLED = 'GUILD_WIDGET_NOT_ENABLED',
// GUILD_NOT_FOUND = 'GUILD_NOT_FOUND',
// MEMBER_NOT_FOUND = 'MEMBER_NOT_FOUND',
// MEMBER_NOT_IN_VOICE_CHANNEL = 'MEMBER_NOT_IN_VOICE_CHANNEL',
// MEMBER_SEARCH_LIMIT_TOO_HIGH = 'MEMBER_SEARCH_LIMIT_TOO_HIGH',
// MEMBER_SEARCH_LIMIT_TOO_LOW = 'MEMBER_SEARCH_LIMIT_TOO_LOW',
// PRUNE_MAX_DAYS = 'PRUNE_MAX_DAYS',
// ROLE_NOT_FOUND = 'ROLE_NOT_FOUND',
// // Thread errors
// INVALID_THREAD_PARENT_CHANNEL_TYPE = 'INVALID_THREAD_PARENT_CHANNEL_TYPE',
// GUILD_NEWS_CHANNEL_ONLY_SUPPORT_PUBLIC_THREADS = 'GUILD_NEWS_CHANNEL_ONLY_SUPPORT_PUBLIC_THREADS',
// NOT_A_THREAD_CHANNEL = 'NOT_A_THREAD_CHANNEL',
// MISSING_MANAGE_THREADS_AND_NOT_MEMBER = 'MISSING_MANAGE_THREADS_AND_NOT_MEMBER',
// CANNOT_GET_MEMBERS_OF_AN_UNJOINED_PRIVATE_THREAD = 'CANNOT_GET_MEMBERS_OF_AN_UNJOINED_PRIVATE_THREAD',
// HAVE_TO_BE_THE_CREATOR_OF_THE_THREAD_OR_HAVE_MANAGE_THREADS_TO_REMOVE_MEMBERS = 'HAVE_TO_BE_THE_CREATOR_OF_THE_THREAD_OR_HAVE_MANAGE_THREADS_TO_REMOVE_MEMBERS',
// // Message Get Errors
// INVALID_GET_MESSAGES_LIMIT = 'INVALID_GET_MESSAGES_LIMIT',
// // Message Delete Errors
// DELETE_MESSAGES_MIN = 'DELETE_MESSAGES_MIN',
// PRUNE_MIN_DAYS = 'PRUNE_MIN_DAYS',
// // Interaction Errors
// INVALID_SLASH_DESCRIPTION = 'INVALID_SLASH_DESCRIPTION',
// INVALID_SLASH_NAME = 'INVALID_SLASH_NAME',
// INVALID_SLASH_OPTIONS = 'INVALID_SLASH_OPTIONS',
// INVALID_SLASH_OPTIONS_CHOICES = 'INVALID_SLASH_OPTIONS_CHOICES',
// TOO_MANY_SLASH_OPTIONS = 'TOO_MANY_SLASH_OPTIONS',
// INVALID_SLASH_OPTION_CHOICE_NAME = 'INVALID_SLASH_OPTION_CHOICE_NAME',
// INVALID_SLASH_OPTIONS_CHOICE_VALUE_TYPE = 'INVALID_SLASH_OPTIONS_CHOICE_VALUE_TYPE',
// TOO_MANY_SLASH_OPTION_CHOICES = 'TOO_MANY_SLASH_OPTION_CHOICES',
// ONLY_STRING_OR_INTEGER_OPTIONS_CAN_HAVE_CHOICES = 'ONLY_STRING_OR_INTEGER_OPTIONS_CAN_HAVE_CHOICES',
// INVALID_SLASH_OPTION_NAME = 'INVALID_SLASH_OPTION_NAME',
// INVALID_SLASH_OPTION_DESCRIPTION = 'INVALID_SLASH_OPTION_DESCRIPTION',
// INVALID_CONTEXT_MENU_COMMAND_NAME = 'INVALID_CONTEXT_MENU_COMMAND_NAME',
// INVALID_CONTEXT_MENU_COMMAND_DESCRIPTION = 'INVALID_CONTEXT_MENU_COMMAND_DESCRIPTION',
// // Webhook Errors
// INVALID_WEBHOOK_NAME = 'INVALID_WEBHOOK_NAME',
// INVALID_WEBHOOK_OPTIONS = 'INVALID_WEBHOOK_OPTIONS',
// // Permission Errors
// MISSING_ADD_REACTIONS = 'MISSING_ADD_REACTIONS',
// MISSING_ADMINISTRATOR = 'MISSING_ADMINISTRATOR',
// MISSING_ATTACH_FILES = 'MISSING_ATTACH_FILES',
// MISSING_BAN_MEMBERS = 'MISSING_BAN_MEMBERS',
// MISSING_CHANGE_NICKNAME = 'MISSING_CHANGE_NICKNAME',
// MISSING_CONNECT = 'MISSING_CONNECT',
// MISSING_CREATE_INSTANT_INVITE = 'MISSING_CREATE_INSTANT_INVITE',
// MISSING_DEAFEN_MEMBERS = 'MISSING_DEAFEN_MEMBERS',
// MISSING_EMBED_LINKS = 'MISSING_EMBED_LINKS',
// MISSING_INTENT_GUILD_MEMBERS = 'MISSING_INTENT_GUILD_MEMBERS',
// MISSING_KICK_MEMBERS = 'MISSING_KICK_MEMBERS',
// MISSING_MANAGE_CHANNELS = 'MISSING_MANAGE_CHANNELS',
// MISSING_MANAGE_EMOJIS = 'MISSING_MANAGE_EMOJIS',
// MISSING_MANAGE_GUILD = 'MISSING_MANAGE_GUILD',
// MISSING_MANAGE_MESSAGES = 'MISSING_MANAGE_MESSAGES',
// MISSING_MANAGE_NICKNAMES = 'MISSING_MANAGE_NICKNAMES',
// MISSING_MANAGE_ROLES = 'MISSING_MANAGE_ROLES',
// MISSING_MANAGE_WEBHOOKS = 'MISSING_MANAGE_WEBHOOKS',
// MISSING_MENTION_EVERYONE = 'MISSING_MENTION_EVERYONE',
// MISSING_MOVE_MEMBERS = 'MISSING_MOVE_MEMBERS',
// MISSING_MUTE_MEMBERS = 'MISSING_MUTE_MEMBERS',
// MISSING_PRIORITY_SPEAKER = 'MISSING_PRIORITY_SPEAKER',
// MISSING_READ_MESSAGE_HISTORY = 'MISSING_READ_MESSAGE_HISTORY',
// MISSING_SEND_MESSAGES = 'MISSING_SEND_MESSAGES',
// MISSING_SEND_TTS_MESSAGES = 'MISSING_SEND_TTS_MESSAGES',
// MISSING_SPEAK = 'MISSING_SPEAK',
// MISSING_STREAM = 'MISSING_STREAM',
// MISSING_USE_VAD = 'MISSING_USE_VAD',
// MISSING_USE_EXTERNAL_EMOJIS = 'MISSING_USE_EXTERNAL_EMOJIS',
// MISSING_VIEW_AUDIT_LOG = 'MISSING_VIEW_AUDIT_LOG',
// MISSING_VIEW_CHANNEL = 'MISSING_VIEW_CHANNEL',
// MISSING_VIEW_GUILD_INSIGHTS = 'MISSING_VIEW_GUILD_INSIGHTS',
// // User Errors
// NICKNAMES_MAX_LENGTH = 'NICKNAMES_MAX_LENGTH',
// USERNAME_INVALID_CHARACTER = 'USERNAME_INVALID_CHARACTER',
// USERNAME_INVALID_USERNAME = 'USERNAME_INVALID_USERNAME',
// USERNAME_MAX_LENGTH = 'USERNAME_MAX_LENGTH',
// USERNAME_MIN_LENGTH = 'USERNAME_MIN_LENGTH',
// NONCE_TOO_LONG = 'NONCE_TOO_LONG',
// INVITE_MAX_AGE_INVALID = 'INVITE_MAX_AGE_INVALID',
// INVITE_MAX_USES_INVALID = 'INVITE_MAX_USES_INVALID',
// // API Errors
// RATE_LIMIT_RETRY_MAXED = 'RATE_LIMIT_RETRY_MAXED',
// REQUEST_CLIENT_ERROR = 'REQUEST_CLIENT_ERROR',
// REQUEST_SERVER_ERROR = 'REQUEST_SERVER_ERROR',
// REQUEST_UNKNOWN_ERROR = 'REQUEST_UNKNOWN_ERROR',
// // Component Errors
// TOO_MANY_COMPONENTS = 'TOO_MANY_COMPONENTS',
// TOO_MANY_ACTION_ROWS = 'TOO_MANY_ACTION_ROWS',
// LINK_BUTTON_CANNOT_HAVE_CUSTOM_ID = 'LINK_BUTTON_CANNOT_HAVE_CUSTOM_ID',
// COMPONENT_LABEL_TOO_BIG = 'COMPONENT_LABEL_TOO_BIG',
// COMPONENT_CUSTOM_ID_TOO_BIG = 'COMPONENT_CUSTOM_ID_TOO_BIG',
// BUTTON_REQUIRES_CUSTOM_ID = 'BUTTON_REQUIRES_CUSTOM_ID',
// COMPONENT_SELECT_MUST_BE_ALONE = 'COMPONENT_SELECT_MUST_BE_ALONE',
// COMPONENT_PLACEHOLDER_TOO_BIG = 'COMPONENT_PLACEHOLDER_TOO_BIG',
// COMPONENT_SELECT_MIN_VALUE_TOO_LOW = 'COMPONENT_SELECT_MIN_VALUE_TOO_LOW',
// COMPONENT_SELECT_MIN_VALUE_TOO_MANY = 'COMPONENT_SELECT_MIN_VALUE_TOO_MANY',
// COMPONENT_SELECT_MAX_VALUE_TOO_LOW = 'COMPONENT_SELECT_MAX_VALUE_TOO_LOW',
// COMPONENT_SELECT_MAX_VALUE_TOO_MANY = 'COMPONENT_SELECT_MAX_VALUE_TOO_MANY',
// COMPONENT_SELECT_OPTIONS_TOO_LOW = 'COMPONENT_SELECT_OPTIONS_TOO_LOW',
// COMPONENT_SELECT_OPTIONS_TOO_MANY = 'COMPONENT_SELECT_OPTIONS_TOO_MANY',
// SELECT_OPTION_LABEL_TOO_BIG = 'SELECT_OPTION_LABEL_TOO_BIG',
// SELECT_OPTION_VALUE_TOO_BIG = 'SELECT_OPTION_VALUE_TOO_BIG',
// SELECT_OPTION_TOO_MANY_DEFAULTS = 'SELECT_OPTION_TOO_MANY_DEFAULTS',
// COMPONENT_SELECT_MIN_HIGHER_THAN_MAX = 'COMPONENT_SELECT_MIN_HIGHER_THAN_MAX',
// CANNOT_ADD_USER_TO_ARCHIVED_THREADS = 'CANNOT_ADD_USER_TO_ARCHIVED_THREADS',
// CANNOT_LEAVE_ARCHIVED_THREAD = 'CANNOT_LEAVE_ARCHIVED_THREAD',
// CANNOT_REMOVE_FROM_ARCHIVED_THREAD = 'CANNOT_REMOVE_FROM_ARCHIVED_THREAD',
// YOU_CAN_NOT_DM_THE_BOT_ITSELF = 'YOU_CAN_NOT_DM_THE_BOT_ITSELF',
// }
export enum Locales {
Danish = 'da',
German = 'de',
@@ -1424,15 +942,9 @@ export enum Locales {
export type Localization = Partial<Record<Locales, string>>
// UTILS
export type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
U[keyof U]
// export type MakeRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] }
export type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]
export type CamelCase<S extends string> = S extends `${infer T}_${infer U}` ? `${T}${Capitalize<CamelCase<U>>}` : S
export type SnakeCase<S extends string> = S extends `${infer T}${infer U}` ? `${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${SnakeCase<U>}` : S
export type SnakeCase<S extends string> = S extends `${infer T}${infer U}` ? `${T extends Capitalize<T> ? '_' : ''}${Lowercase<T>}${SnakeCase<U>}` : S
export type Camelize<T> = T extends any[]
? T extends Array<Record<any, any>>
@@ -1442,7 +954,7 @@ export type Camelize<T> = T extends any[]
? { [K in keyof T as CamelCase<K & string>]: Camelize<T[K]> }
: T
export type Snakelize<T> = T extends any[]
export type Snakelize<T> = T extends any[]
? T extends Array<Record<any, any>>
? Array<Snakelize<T[number]>>
: T
@@ -1450,91 +962,4 @@ export type Camelize<T> = T extends any[]
? { [K in keyof T as SnakeCase<K & string>]: Snakelize<T[K]> }
: T
// /** Non object primitives */
// export type Primitive =
// | string
// | number
// | symbol
// | bigint
// | boolean
// | undefined
// | null
// // | object <- don't make object a primitive
// /**
// * alternative to 'object' or '{}'
// * @example:
// * export const o: ObjectLiteral = [] as object; // error
// * export const o: object = []; // no error
// */
// export type ObjectLiteral<T = unknown> = {
// [K in PropertyKey]: T;
// }
// /** Array with no utilty methods, aka Object.create(null) */
// export interface ArrayWithNoPrototype<T> {
// [index: number]: T | ArrayWithNoPrototype<T>
// }
// /**
// * Allows any type but T
// * it is recursive
// * @example
// * export type RequestData = Record<string, AnythingBut<bigint>>;
// */
// export type AnythingBut<T> = Exclude<
// | Primitive
// | {
// [K in PropertyKey]: AnythingBut<T>;
// }
// | ArrayWithNoPrototype<
// | Primitive
// | {
// [K in PropertyKey]: AnythingBut<T>;
// }
// >,
// T
// >
// /**
// * object identity type
// */
// export type Id<T> = T extends infer U
// ? {
// [K in keyof U]: U[K];
// }
// : never
// export type KeysWithUndefined<T> = {
// [K in keyof T]-?: undefined extends T[K] ? K : null extends T[K] ? K : never;
// }[keyof T]
// type OptionalizeAux<T extends object> = Id<
// {
// [K in KeysWithUndefined<T>]?: Optionalize<T[K]>;
// } & {
// [K in Exclude<keyof T, KeysWithUndefined<T>>]: T[K] extends ObjectLiteral
// ? Optionalize<T[K]>
// : T[K];
// }
// >
// /**
// * Makes all of properties in T optional when they're null | undefined
// * it is recursive
// */
// export type Optionalize<T> = T extends object
// ? T extends unknown[]
// ? number extends T['length']
// ? T[number] extends object
// ? Array<OptionalizeAux<T[number]>>
// : T
// : Partial<T>
// : OptionalizeAux<T>
// : T
export type PickPartial<T, K extends keyof T> = { [P in keyof T]?: T[P] | undefined } & { [P in K]: T[P] }
// export type OmitFirstFnArg<F> = F extends (x: any, ...args: infer P) => infer R
// ? (...args: P) => R
// : never
+5 -9
View File
@@ -103,28 +103,24 @@ Have your cache setup in any way you like. Redis, PGSQL or any cache layer you w
Here is a minimal example to get started with:
```typescript
import {
createBot,
Intents,
startBot,
} from "https://deno.land/x/discordeno@13.0.0/mod.ts";
import { createBot, Intents, startBot } from 'https://deno.land/x/discordeno@13.0.0/mod.ts'
const bot = createBot({
token: process.env.DISCORD_TOKEN,
intents: Intents.Guilds | Intents.GuildMessages,
events: {
ready() {
console.log("Successfully connected to gateway");
console.log('Successfully connected to gateway')
},
},
});
})
// Another way to do events
bot.events.messageCreate = function (b, message) {
// Process the message here with your command handler.
};
}
await startBot(bot);
await startBot(bot)
```
### Tools
+9 -10
View File
@@ -1,4 +1,4 @@
import type { Camelize, Snakelize } from '@discordeno/types';
import type { Camelize, Snakelize } from '@discordeno/types'
export const camelize = <T>(object: T): Camelize<T> => {
if (Array.isArray(object)) {
@@ -16,7 +16,6 @@ export const camelize = <T>(object: T): Camelize<T> => {
return object as Camelize<T>
}
export const snakelize = <T>(object: T): Snakelize<T> => {
if (Array.isArray(object)) {
return object.map((element) => snakelize(element)) as Snakelize<T>
@@ -25,7 +24,7 @@ export const snakelize = <T>(object: T): Snakelize<T> => {
if (typeof object === 'object' && object !== null) {
const obj = {} as Snakelize<T>
;(Object.keys(object) as Array<keyof T>).forEach((key) => {
// @ts-expect-error js hack
// @ts-expect-error js hack
;(obj[typeof key === 'string' ? camelToSnakeCase(key) : key] as Snakelize<(T & object)[keyof T]>) = snakelize(object[key])
})
@@ -52,16 +51,16 @@ export function snakeToCamelCase(str: string): string {
}
export function camelToSnakeCase(str: string): string {
let result = "";
let result = ''
for (let i = 0, len = str.length; i < len; ++i) {
if (str[i] >= "A" && str[i] <= "Z") {
result += `_${str[i].toLowerCase()}`;
if (str[i] >= 'A' && str[i] <= 'Z') {
result += `_${str[i].toLowerCase()}`
continue;
}
continue
}
result += str[i];
result += str[i]
}
return result;
return result
}
+74 -112
View File
@@ -5,22 +5,22 @@
// on npm.
// https://deno.land/std@0.153.0/fmt/colors.ts?source
const noColor = false;
const noColor = false
interface Code {
open: string;
close: string;
regexp: RegExp;
export interface Code {
open: string
close: string
regexp: RegExp
}
/** RGB 8-bits per channel. Each in range `0->255` or `0x00->0xff` */
interface Rgb {
r: number;
g: number;
b: number;
export interface Rgb {
r: number
g: number
b: number
}
let enabled = !noColor;
let enabled = !noColor
/**
* Set changing text color to enabled or disabled
@@ -28,15 +28,15 @@ let enabled = !noColor;
*/
export function setColorEnabled(value: boolean) {
if (noColor) {
return;
return
}
enabled = value;
enabled = value
}
/** Get whether text color change is enabled or disabled. */
export function getColorEnabled(): boolean {
return enabled;
return enabled
}
/**
@@ -46,10 +46,10 @@ export function getColorEnabled(): boolean {
*/
function code(open: number[], close: number): Code {
return {
open: `\x1b[${open.join(";")}m`,
open: `\x1b[${open.join(';')}m`,
close: `\x1b[${close}m`,
regexp: new RegExp(`\\x1b\\[${close}m`, "g"),
};
regexp: new RegExp(`\\x1b\\[${close}m`, 'g'),
}
}
/**
@@ -58,9 +58,7 @@ function code(open: number[], close: number): Code {
* @param code color code to apply
*/
function run(str: string, code: Code): string {
return enabled
? `${code.open}${str.replace(code.regexp, code.open)}${code.close}`
: str;
return enabled ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` : str
}
/**
@@ -68,7 +66,7 @@ function run(str: string, code: Code): string {
* @param str text to reset
*/
export function reset(str: string): string {
return run(str, code([0], 0));
return run(str, code([0], 0))
}
/**
@@ -76,7 +74,7 @@ export function reset(str: string): string {
* @param str text to make bold
*/
export function bold(str: string): string {
return run(str, code([1], 22));
return run(str, code([1], 22))
}
/**
@@ -84,7 +82,7 @@ export function bold(str: string): string {
* @param str text to dim
*/
export function dim(str: string): string {
return run(str, code([2], 22));
return run(str, code([2], 22))
}
/**
@@ -92,7 +90,7 @@ export function dim(str: string): string {
* @param str text to make italic
*/
export function italic(str: string): string {
return run(str, code([3], 23));
return run(str, code([3], 23))
}
/**
@@ -100,7 +98,7 @@ export function italic(str: string): string {
* @param str text to underline
*/
export function underline(str: string): string {
return run(str, code([4], 24));
return run(str, code([4], 24))
}
/**
@@ -108,7 +106,7 @@ export function underline(str: string): string {
* @param str text to invert its color
*/
export function inverse(str: string): string {
return run(str, code([7], 27));
return run(str, code([7], 27))
}
/**
@@ -116,7 +114,7 @@ export function inverse(str: string): string {
* @param str text to hide
*/
export function hidden(str: string): string {
return run(str, code([8], 28));
return run(str, code([8], 28))
}
/**
@@ -124,7 +122,7 @@ export function hidden(str: string): string {
* @param str text to strike through
*/
export function strikethrough(str: string): string {
return run(str, code([9], 29));
return run(str, code([9], 29))
}
/**
@@ -132,7 +130,7 @@ export function strikethrough(str: string): string {
* @param str text to make black
*/
export function black(str: string): string {
return run(str, code([30], 39));
return run(str, code([30], 39))
}
/**
@@ -140,7 +138,7 @@ export function black(str: string): string {
* @param str text to make red
*/
export function red(str: string): string {
return run(str, code([31], 39));
return run(str, code([31], 39))
}
/**
@@ -148,7 +146,7 @@ export function red(str: string): string {
* @param str text to make green
*/
export function green(str: string): string {
return run(str, code([32], 39));
return run(str, code([32], 39))
}
/**
@@ -156,7 +154,7 @@ export function green(str: string): string {
* @param str text to make yellow
*/
export function yellow(str: string): string {
return run(str, code([33], 39));
return run(str, code([33], 39))
}
/**
@@ -164,7 +162,7 @@ export function yellow(str: string): string {
* @param str text to make blue
*/
export function blue(str: string): string {
return run(str, code([34], 39));
return run(str, code([34], 39))
}
/**
@@ -172,7 +170,7 @@ export function blue(str: string): string {
* @param str text to make magenta
*/
export function magenta(str: string): string {
return run(str, code([35], 39));
return run(str, code([35], 39))
}
/**
@@ -180,7 +178,7 @@ export function magenta(str: string): string {
* @param str text to make cyan
*/
export function cyan(str: string): string {
return run(str, code([36], 39));
return run(str, code([36], 39))
}
/**
@@ -188,7 +186,7 @@ export function cyan(str: string): string {
* @param str text to make white
*/
export function white(str: string): string {
return run(str, code([37], 39));
return run(str, code([37], 39))
}
/**
@@ -196,7 +194,7 @@ export function white(str: string): string {
* @param str text to make gray
*/
export function gray(str: string): string {
return brightBlack(str);
return brightBlack(str)
}
/**
@@ -204,7 +202,7 @@ export function gray(str: string): string {
* @param str text to make bright-black
*/
export function brightBlack(str: string): string {
return run(str, code([90], 39));
return run(str, code([90], 39))
}
/**
@@ -212,7 +210,7 @@ export function brightBlack(str: string): string {
* @param str text to make bright-red
*/
export function brightRed(str: string): string {
return run(str, code([91], 39));
return run(str, code([91], 39))
}
/**
@@ -220,7 +218,7 @@ export function brightRed(str: string): string {
* @param str text to make bright-green
*/
export function brightGreen(str: string): string {
return run(str, code([92], 39));
return run(str, code([92], 39))
}
/**
@@ -228,7 +226,7 @@ export function brightGreen(str: string): string {
* @param str text to make bright-yellow
*/
export function brightYellow(str: string): string {
return run(str, code([93], 39));
return run(str, code([93], 39))
}
/**
@@ -236,7 +234,7 @@ export function brightYellow(str: string): string {
* @param str text to make bright-blue
*/
export function brightBlue(str: string): string {
return run(str, code([94], 39));
return run(str, code([94], 39))
}
/**
@@ -244,7 +242,7 @@ export function brightBlue(str: string): string {
* @param str text to make bright-magenta
*/
export function brightMagenta(str: string): string {
return run(str, code([95], 39));
return run(str, code([95], 39))
}
/**
@@ -252,7 +250,7 @@ export function brightMagenta(str: string): string {
* @param str text to make bright-cyan
*/
export function brightCyan(str: string): string {
return run(str, code([96], 39));
return run(str, code([96], 39))
}
/**
@@ -260,7 +258,7 @@ export function brightCyan(str: string): string {
* @param str text to make bright-white
*/
export function brightWhite(str: string): string {
return run(str, code([97], 39));
return run(str, code([97], 39))
}
/**
@@ -268,7 +266,7 @@ export function brightWhite(str: string): string {
* @param str text to make its background black
*/
export function bgBlack(str: string): string {
return run(str, code([40], 49));
return run(str, code([40], 49))
}
/**
@@ -276,7 +274,7 @@ export function bgBlack(str: string): string {
* @param str text to make its background red
*/
export function bgRed(str: string): string {
return run(str, code([41], 49));
return run(str, code([41], 49))
}
/**
@@ -284,7 +282,7 @@ export function bgRed(str: string): string {
* @param str text to make its background green
*/
export function bgGreen(str: string): string {
return run(str, code([42], 49));
return run(str, code([42], 49))
}
/**
@@ -292,7 +290,7 @@ export function bgGreen(str: string): string {
* @param str text to make its background yellow
*/
export function bgYellow(str: string): string {
return run(str, code([43], 49));
return run(str, code([43], 49))
}
/**
@@ -300,7 +298,7 @@ export function bgYellow(str: string): string {
* @param str text to make its background blue
*/
export function bgBlue(str: string): string {
return run(str, code([44], 49));
return run(str, code([44], 49))
}
/**
@@ -308,7 +306,7 @@ export function bgBlue(str: string): string {
* @param str text to make its background magenta
*/
export function bgMagenta(str: string): string {
return run(str, code([45], 49));
return run(str, code([45], 49))
}
/**
@@ -316,7 +314,7 @@ export function bgMagenta(str: string): string {
* @param str text to make its background cyan
*/
export function bgCyan(str: string): string {
return run(str, code([46], 49));
return run(str, code([46], 49))
}
/**
@@ -324,7 +322,7 @@ export function bgCyan(str: string): string {
* @param str text to make its background white
*/
export function bgWhite(str: string): string {
return run(str, code([47], 49));
return run(str, code([47], 49))
}
/**
@@ -332,7 +330,7 @@ export function bgWhite(str: string): string {
* @param str text to make its background bright-black
*/
export function bgBrightBlack(str: string): string {
return run(str, code([100], 49));
return run(str, code([100], 49))
}
/**
@@ -340,7 +338,7 @@ export function bgBrightBlack(str: string): string {
* @param str text to make its background bright-red
*/
export function bgBrightRed(str: string): string {
return run(str, code([101], 49));
return run(str, code([101], 49))
}
/**
@@ -348,7 +346,7 @@ export function bgBrightRed(str: string): string {
* @param str text to make its background bright-green
*/
export function bgBrightGreen(str: string): string {
return run(str, code([102], 49));
return run(str, code([102], 49))
}
/**
@@ -356,7 +354,7 @@ export function bgBrightGreen(str: string): string {
* @param str text to make its background bright-yellow
*/
export function bgBrightYellow(str: string): string {
return run(str, code([103], 49));
return run(str, code([103], 49))
}
/**
@@ -364,7 +362,7 @@ export function bgBrightYellow(str: string): string {
* @param str text to make its background bright-blue
*/
export function bgBrightBlue(str: string): string {
return run(str, code([104], 49));
return run(str, code([104], 49))
}
/**
@@ -372,7 +370,7 @@ export function bgBrightBlue(str: string): string {
* @param str text to make its background bright-magenta
*/
export function bgBrightMagenta(str: string): string {
return run(str, code([105], 49));
return run(str, code([105], 49))
}
/**
@@ -380,7 +378,7 @@ export function bgBrightMagenta(str: string): string {
* @param str text to make its background bright-cyan
*/
export function bgBrightCyan(str: string): string {
return run(str, code([106], 49));
return run(str, code([106], 49))
}
/**
@@ -388,7 +386,7 @@ export function bgBrightCyan(str: string): string {
* @param str text to make its background bright-white
*/
export function bgBrightWhite(str: string): string {
return run(str, code([107], 49));
return run(str, code([107], 49))
}
/* Special Color Sequences */
@@ -400,7 +398,7 @@ export function bgBrightWhite(str: string): string {
* @param min number to truncate from
*/
function clampAndTruncate(n: number, max = 255, min = 0): number {
return Math.trunc(Math.max(Math.min(n, max), min));
return Math.trunc(Math.max(Math.min(n, max), min))
}
/**
@@ -410,7 +408,7 @@ function clampAndTruncate(n: number, max = 255, min = 0): number {
* @param color code
*/
export function rgb8(str: string, color: number): string {
return run(str, code([38, 5, clampAndTruncate(color)], 39));
return run(str, code([38, 5, clampAndTruncate(color)], 39))
}
/**
@@ -420,7 +418,7 @@ export function rgb8(str: string, color: number): string {
* @param color code
*/
export function bgRgb8(str: string, color: number): string {
return run(str, code([48, 5, clampAndTruncate(color)], 49));
return run(str, code([48, 5, clampAndTruncate(color)], 49))
}
/**
@@ -439,28 +437,10 @@ export function bgRgb8(str: string, color: number): string {
* @param color code
*/
export function rgb24(str: string, color: number | Rgb): string {
if (typeof color === "number") {
return run(
str,
code(
[38, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff],
39,
),
);
if (typeof color === 'number') {
return run(str, code([38, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], 39))
}
return run(
str,
code(
[
38,
2,
clampAndTruncate(color.r),
clampAndTruncate(color.g),
clampAndTruncate(color.b),
],
39,
),
);
return run(str, code([38, 2, clampAndTruncate(color.r), clampAndTruncate(color.g), clampAndTruncate(color.b)], 39))
}
/**
@@ -479,43 +459,25 @@ export function rgb24(str: string, color: number | Rgb): string {
* @param color code
*/
export function bgRgb24(str: string, color: number | Rgb): string {
if (typeof color === "number") {
return run(
str,
code(
[48, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff],
49,
),
);
if (typeof color === 'number') {
return run(str, code([48, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], 49))
}
return run(
str,
code(
[
48,
2,
clampAndTruncate(color.r),
clampAndTruncate(color.g),
clampAndTruncate(color.b),
],
49,
),
);
return run(str, code([48, 2, clampAndTruncate(color.r), clampAndTruncate(color.g), clampAndTruncate(color.b)], 49))
}
// https://github.com/chalk/ansi-regex/blob/02fa893d619d3da85411acc8fd4e2eea0e95a9d9/index.js
const ANSI_PATTERN = new RegExp(
[
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))",
].join("|"),
"g",
);
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))',
].join('|'),
'g',
)
/**
* Remove ANSI escape codes from the string.
* @param string to remove ANSI escape codes from
*/
export function stripColor(string: string): string {
return string.replace(ANSI_PATTERN, "");
}
return string.replace(ANSI_PATTERN, '')
}
+2 -2
View File
@@ -1,5 +1,5 @@
import type { FileContent } from "@discordeno/types"
import { decode } from "./base64.js"
import type { FileContent } from '@discordeno/types'
import { decode } from './base64.js'
export function findFiles(file: unknown): FileContent[] {
if (!file) {
+2 -2
View File
@@ -1,4 +1,4 @@
export function iconHashToBigInt (hash: string): bigint {
export function iconHashToBigInt(hash: string): bigint {
// The icon is animated so it needs special handling
if (hash.startsWith('a_')) {
// Change the `a_` to just be `a`
@@ -11,7 +11,7 @@ export function iconHashToBigInt (hash: string): bigint {
return BigInt(`0x${hash}`)
}
export function iconBigintToHash (icon: bigint): string {
export function iconBigintToHash(icon: bigint): string {
// Convert the bigint back to a hash
const hash = icon.toString(16)
// Hashes starting with a are animated and with b are not so need to handle that
+11 -18
View File
@@ -81,16 +81,14 @@ export function guildIconUrl(
options?: {
size?: ImageSize
format?: ImageFormat
}
},
): string | undefined {
return imageHash
? formatImageUrl(
`https://cdn.discordapp.com/icons/${guildId}/${typeof imageHash === 'string'
? imageHash
: iconBigintToHash(imageHash)}`,
options?.size ?? 128,
options?.format
)
`https://cdn.discordapp.com/icons/${guildId}/${typeof imageHash === 'string' ? imageHash : iconBigintToHash(imageHash)}`,
options?.size ?? 128,
options?.format,
)
: undefined
}
@@ -108,16 +106,14 @@ export function guildSplashUrl(
options?: {
size?: ImageSize
format?: ImageFormat
}
},
): string | undefined {
return imageHash
? formatImageUrl(
`https://cdn.discordapp.com/splashes/${guildId}/${typeof imageHash === 'string'
? imageHash
: iconBigintToHash(imageHash)}`,
options?.size ?? 128,
options?.format
)
`https://cdn.discordapp.com/splashes/${guildId}/${typeof imageHash === 'string' ? imageHash : iconBigintToHash(imageHash)}`,
options?.size ?? 128,
options?.format,
)
: undefined
}
@@ -128,10 +124,7 @@ export function guildSplashUrl(
* @param options - The parameters for the building of the URL.
* @returns The link to the resource.
*/
export function getWidgetImageUrl (
guildId: BigString,
options?: GetGuildWidgetImageQuery
): string {
export function getWidgetImageUrl(guildId: BigString, options?: GetGuildWidgetImageQuery): string {
let url = `https://cdn.discordapp.com/guilds/${guildId}/widget.png`
if (options?.style) {
+3 -8
View File
@@ -1,15 +1,10 @@
import { Buffer } from 'node:buffer'
/** Removes the Bot before the token. */
export function removeTokenPrefix (
token?: string,
type: 'GATEWAY' | 'REST' = 'REST'
): string {
export function removeTokenPrefix(token?: string, type: 'GATEWAY' | 'REST' = 'REST'): string {
// If no token is provided, throw an error
if (token === undefined) {
throw new Error(
`The ${type} was not given a token. Please provide a token and try again.`
)
throw new Error(`The ${type} was not given a token. Please provide a token and try again.`)
}
// If the token does not have a prefix just return token
if (!token.startsWith('Bot ')) return token
@@ -18,6 +13,6 @@ export function removeTokenPrefix (
}
/** Get the bot id from the bot token. WARNING: Discord staff has mentioned this may not be stable forever. Use at your own risk. However, note for over 5 years this has never broken. */
export function getBotIdFromToken (token: string): bigint {
export function getBotIdFromToken(token: string): bigint {
return BigInt(Buffer.from(token.split('.')[0], 'base64').toString())
}
+1 -4
View File
@@ -12,10 +12,7 @@ export async function delay(ms: number): Promise<void> {
// Typescript is not so good as we developers so we need this little utility function to help it out
// Taken from https://fettblog.eu/typescript-hasownproperty/
/** TS save way to check if a property exists in an object */
export function hasProperty<T extends {}, Y extends PropertyKey = string> (
obj: T,
prop: Y
): obj is T & Record<Y, unknown> {
export function hasProperty<T extends {}, Y extends PropertyKey = string>(obj: T, prop: Y): obj is T & Record<Y, unknown> {
// eslint-disable-next-line no-prototype-builtins
return obj.hasOwnProperty(prop)
}