This commit is contained in:
DjDeveloperr 2021-04-04 11:12:15 +05:30
parent 7dc316c76f
commit 22e041f440
111 changed files with 1753 additions and 1713 deletions

View File

@ -2,7 +2,7 @@ import {
SlashCommandsManager,
SlashClient,
SlashCommandHandlerCallback
} from './src/models/slashClient.ts'
} from './src/interactions/mod.ts'
import { InteractionResponseType, InteractionType } from './src/types/slash.ts'
export interface DeploySlashInitOptions {
@ -41,7 +41,7 @@ export function init(options: DeploySlashInitOptions): void {
try {
const d = await client.verifyFetchEvent({
respondWith: (...args: any[]) => evt.respondWith(...args),
request: evt.request,
request: evt.request
})
if (d === false) {
await evt.respondWith(
@ -72,11 +72,11 @@ export function handle(
cmd:
| string
| {
name: string
parent?: string
group?: string
guild?: string
},
name: string
parent?: string
group?: string
guild?: string
},
handler: SlashCommandHandlerCallback
): void {
const handle = {
@ -85,9 +85,15 @@ export function handle(
...(typeof cmd === 'string' ? {} : cmd)
}
if (typeof handle.name === 'string' && handle.name.includes(' ') && handle.parent === undefined && handle.group === undefined) {
const parts = handle.name.split(/ +/).filter(e => e !== '')
if (parts.length > 3 || parts.length < 1) throw new Error('Invalid command name')
if (
typeof handle.name === 'string' &&
handle.name.includes(' ') &&
handle.parent === undefined &&
handle.group === undefined
) {
const parts = handle.name.split(/ +/).filter((e) => e !== '')
if (parts.length > 3 || parts.length < 1)
throw new Error('Invalid command name')
const root = parts.shift() as string
const group = parts.length === 2 ? parts.shift() : undefined
const sub = parts.shift()
@ -103,4 +109,4 @@ export function handle(
export { commands, client }
export * from './src/types/slash.ts'
export * from './src/structures/slash.ts'
export * from './src/models/slashClient.ts'
export * from './src/interactions/mod.ts'

34
mod.ts
View File

@ -1,20 +1,18 @@
export { GatewayIntents } from './src/types/gateway.ts'
export { Base } from './src/structures/base.ts'
export { Gateway } from './src/gateway/index.ts'
export type { GatewayTypedEvents } from './src/gateway/index.ts'
export type { ClientEvents } from './src/gateway/handlers/index.ts'
export * from './src/models/client.ts'
export * from './src/models/slashClient.ts'
export { Gateway } from './src/gateway/mod.ts'
export type { GatewayTypedEvents } from './src/gateway/mod.ts'
export type { ClientEvents } from './src/gateway/handlers/mod.ts'
export * from './src/client/mod.ts'
export * from './src/interactions/mod.ts'
export {
RESTManager,
TokenType,
HttpResponseCode,
DiscordAPIError
} from './src/models/rest.ts'
export type { APIMap, DiscordAPIErrorPayload } from './src/models/rest.ts'
export type { RequestHeaders } from './src/models/rest.ts'
export type { RESTOptions } from './src/models/rest.ts'
export * from './src/models/cacheAdapter.ts'
} from './src/rest/mod.ts'
export * from './src/rest/mod.ts'
export * from './src/cache/adapter.ts'
export {
Command,
CommandBuilder,
@ -22,16 +20,16 @@ export {
CommandsManager,
CategoriesManager,
CommandsLoader
} from './src/models/command.ts'
export type { CommandContext, CommandOptions } from './src/models/command.ts'
} from './src/commands/command.ts'
export type { CommandContext, CommandOptions } from './src/commands/command.ts'
export {
Extension,
ExtensionCommands,
ExtensionsManager
} from './src/models/extensions.ts'
export { SlashModule } from './src/models/slashModule.ts'
export { CommandClient, command } from './src/models/commandClient.ts'
export type { CommandClientOptions } from './src/models/commandClient.ts'
} from './src/commands/extension.ts'
export { SlashModule } from './src/interactions/slashModule.ts'
export { CommandClient, command } from './src/commands/client.ts'
export type { CommandClientOptions } from './src/commands/client.ts'
export { BaseManager } from './src/managers/base.ts'
export { BaseChildManager } from './src/managers/baseChild.ts'
export { ChannelsManager } from './src/managers/channels.ts'
@ -165,8 +163,8 @@ export type { UserPayload } from './src/types/user.ts'
export { UserFlags } from './src/types/userFlags.ts'
export type { VoiceStatePayload } from './src/types/voice.ts'
export type { WebhookPayload } from './src/types/webhook.ts'
export * from './src/models/collectors.ts'
export * from './src/client/collectors.ts'
export type { Dict } from './src/utils/dict.ts'
export * from './src/models/redisCache.ts'
export * from './src/cache/redis.ts'
export { ColorUtil } from './src/utils/colorutil.ts'
export type { Colors } from './src/utils/colorutil.ts'

View File

@ -1,5 +1,9 @@
import { ICacheAdapter } from './cacheAdapter.ts'
import { connect, Redis, RedisConnectOptions } from 'https://deno.land/x/redis@v0.14.1/mod.ts'
import { ICacheAdapter } from './adapter.ts'
import {
connect,
Redis,
RedisConnectOptions
} from 'https://deno.land/x/redis@v0.14.1/mod.ts'
/** Redis Cache Adapter for using Redis as a cache-provider. */
export class RedisCacheAdapter implements ICacheAdapter {
@ -102,4 +106,4 @@ export class RedisCacheAdapter implements ICacheAdapter {
await this._checkReady()
return (await this.redis?.del(cacheName)) !== 0
}
}
}

View File

@ -1,437 +1,437 @@
/* eslint-disable @typescript-eslint/method-signature-style */
import { User } from '../structures/user.ts'
import { GatewayIntents } from '../types/gateway.ts'
import { Gateway } from '../gateway/index.ts'
import { RESTManager, RESTOptions, TokenType } from './rest.ts'
import { DefaultCacheAdapter, ICacheAdapter } from './cacheAdapter.ts'
import { UsersManager } from '../managers/users.ts'
import { GuildManager } from '../managers/guilds.ts'
import { ChannelsManager } from '../managers/channels.ts'
import { ClientPresence } from '../structures/presence.ts'
import { EmojisManager } from '../managers/emojis.ts'
import { ActivityGame, ClientActivity } from '../types/presence.ts'
import { Extension } from './extensions.ts'
import { SlashClient } from './slashClient.ts'
import { Interaction } from '../structures/slash.ts'
import { ShardManager } from './shard.ts'
import { Application } from '../structures/application.ts'
import { Invite } from '../structures/invite.ts'
import { INVITE } from '../types/endpoint.ts'
import { ClientEvents } from '../gateway/handlers/index.ts'
import type { Collector } from './collectors.ts'
import { HarmonyEventEmitter } from '../utils/events.ts'
import { VoiceRegion } from '../types/voice.ts'
import { fetchAuto } from '../../deps.ts'
import { DMChannel } from '../structures/dmChannel.ts'
import { Template } from '../structures/template.ts'
/** OS related properties sent with Gateway Identify */
export interface ClientProperties {
os?: 'darwin' | 'windows' | 'linux' | 'custom_os' | string
browser?: 'harmony' | string
device?: 'harmony' | string
}
/** Some Client Options to modify behaviour */
export interface ClientOptions {
/** ID of the Client/Application to initialize Slash Client REST */
id?: string
/** Token of the Bot/User */
token?: string
/** Gateway Intents */
intents?: GatewayIntents[]
/** Cache Adapter to use, defaults to Collections one */
cache?: ICacheAdapter
/** Force New Session and don't use cached Session (by persistent caching) */
forceNewSession?: boolean
/** Startup presence of client */
presence?: ClientPresence | ClientActivity | ActivityGame
/** Force all requests to Canary API */
canary?: boolean
/** Time till which Messages are to be cached, in MS. Default is 3600000 */
messageCacheLifetime?: number
/** Time till which Message Reactions are to be cached, in MS. Default is 3600000 */
reactionCacheLifetime?: number
/** Whether to fetch Uncached Message of Reaction or not? */
fetchUncachedReactions?: boolean
/** Client Properties */
clientProperties?: ClientProperties
/** Enable/Disable Slash Commands Integration (enabled by default) */
enableSlash?: boolean
/** Disable taking token from env if not provided (token is taken from env if present by default) */
disableEnvToken?: boolean
/** Override REST Options */
restOptions?: RESTOptions
/** Whether to fetch Gateway info or not */
fetchGatewayInfo?: boolean
/** ADVANCED: Shard ID to launch on */
shard?: number
/** ADVACNED: Shard count. */
shardCount?: number | 'auto'
}
/**
* Discord Client.
*/
export class Client extends HarmonyEventEmitter<ClientEvents> {
/** REST Manager - used to make all requests */
rest: RESTManager
/** User which Client logs in to, undefined until logs in */
user?: User
/** WebSocket ping of Client */
ping = 0
/** Token of the Bot/User */
token?: string
/** Cache Adapter */
cache: ICacheAdapter = new DefaultCacheAdapter()
/** Gateway Intents */
intents?: GatewayIntents[]
/** Whether to force new session or not */
forceNewSession?: boolean
/** Time till messages to stay cached, in MS. */
messageCacheLifetime: number = 3600000
/** Time till messages to stay cached, in MS. */
reactionCacheLifetime: number = 3600000
/** Whether to fetch Uncached Message of Reaction or not? */
fetchUncachedReactions: boolean = false
/** Client Properties */
clientProperties: ClientProperties
/** Slash-Commands Management client */
slash: SlashClient
/** Whether to fetch Gateway info or not */
fetchGatewayInfo: boolean = true
/** Users Manager, containing all Users cached */
users: UsersManager = new UsersManager(this)
/** Guilds Manager, providing cache & API interface to Guilds */
guilds: GuildManager = new GuildManager(this)
/** Channels Manager, providing cache interface to Channels */
channels: ChannelsManager = new ChannelsManager(this)
/** Channels Manager, providing cache interface to Channels */
emojis: EmojisManager = new EmojisManager(this)
/** Last READY timestamp */
upSince?: Date
/** Client's presence. Startup one if set before connecting */
presence: ClientPresence = new ClientPresence()
_decoratedEvents?: {
[name: string]: (...args: any[]) => void
}
_decoratedSlash?: Array<{
name: string
guild?: string
parent?: string
group?: string
handler: (interaction: Interaction) => any
}>
_id?: string
/** Shard on which this Client is */
shard?: number
/** Shard Count */
shardCount: number | 'auto' = 'auto'
/** Shard Manager of this Client if Sharded */
shards: ShardManager
/** Collectors set */
collectors: Set<Collector> = new Set()
/** Since when is Client online (ready). */
get uptime(): number {
if (this.upSince === undefined) return 0
else {
const dif = Date.now() - this.upSince.getTime()
if (dif < 0) return 0
else return dif
}
}
get gateway(): Gateway {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
return this.shards.list.get('0') as Gateway
}
applicationID?: string
applicationFlags?: number
constructor(options: ClientOptions = {}) {
super()
this._id = options.id
this.token = options.token
this.intents = options.intents
this.shards = new ShardManager(this)
this.forceNewSession = options.forceNewSession
if (options.cache !== undefined) this.cache = options.cache
if (options.presence !== undefined)
this.presence =
options.presence instanceof ClientPresence
? options.presence
: new ClientPresence(options.presence)
if (options.messageCacheLifetime !== undefined)
this.messageCacheLifetime = options.messageCacheLifetime
if (options.reactionCacheLifetime !== undefined)
this.reactionCacheLifetime = options.reactionCacheLifetime
if (options.fetchUncachedReactions === true)
this.fetchUncachedReactions = true
if (
this._decoratedEvents !== undefined &&
Object.keys(this._decoratedEvents).length !== 0
) {
Object.entries(this._decoratedEvents).forEach((entry) => {
this.on(entry[0] as keyof ClientEvents, entry[1].bind(this))
})
this._decoratedEvents = undefined
}
this.clientProperties =
options.clientProperties === undefined
? {
os: Deno.build.os,
browser: 'harmony',
device: 'harmony'
}
: options.clientProperties
if (options.shard !== undefined) this.shard = options.shard
if (options.shardCount !== undefined) this.shardCount = options.shardCount
this.fetchGatewayInfo = options.fetchGatewayInfo ?? true
if (this.token === undefined) {
try {
const token = Deno.env.get('DISCORD_TOKEN')
if (token !== undefined) {
this.token = token
this.debug('Info', 'Found token in ENV')
}
} catch (e) { }
}
const restOptions: RESTOptions = {
token: () => this.token,
tokenType: TokenType.Bot,
canary: options.canary,
client: this
}
if (options.restOptions !== undefined)
Object.assign(restOptions, options.restOptions)
this.rest = new RESTManager(restOptions)
this.slash = new SlashClient({
id: () => this.getEstimatedID(),
client: this,
enabled: options.enableSlash
})
}
/**
* Sets Cache Adapter
*
* Should NOT be set after bot is already logged in or using current cache.
* Please look into using `cache` option.
*/
setAdapter(adapter: ICacheAdapter): Client {
this.cache = adapter
return this
}
/** Changes Presence of Client */
setPresence(presence: ClientPresence | ClientActivity | ActivityGame): void {
if (presence instanceof ClientPresence) {
this.presence = presence
} else this.presence = new ClientPresence(presence)
this.gateway?.sendPresence(this.presence.create())
}
/** Emits debug event */
debug(tag: string, msg: string): void {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.emit('debug', `[${tag}] ${msg}`)
}
getEstimatedID(): string {
if (this.user !== undefined) return this.user.id
else if (this.token !== undefined) {
try {
return atob(this.token.split('.')[0])
} catch (e) {
return this._id ?? 'unknown'
}
} else {
return this._id ?? 'unknown'
}
}
/** Fetch Application of the Client */
async fetchApplication(): Promise<Application> {
const app = await this.rest.api.oauth2.applications['@me'].get()
return new Application(this, app)
}
/** Fetch an Invite */
async fetchInvite(id: string): Promise<Invite> {
return await new Promise((resolve, reject) => {
this.rest
.get(INVITE(id))
.then((data) => {
resolve(new Invite(this, data))
})
.catch((e) => reject(e))
})
}
/**
* This function is used for connecting to discord.
* @param token Your token. This is required if not given in ClientOptions.
* @param intents Gateway intents in array. This is required if not given in ClientOptions.
*/
async connect(token?: string, intents?: GatewayIntents[]): Promise<Client> {
token ??= this.token
if (token === undefined) throw new Error('No Token Provided')
this.token = token
if (intents !== undefined && this.intents !== undefined) {
this.debug(
'client',
'Intents were set in both client and connect function. Using the one in the connect function...'
)
} else if (intents === undefined && this.intents !== undefined) {
intents = this.intents
} else if (intents !== undefined && this.intents === undefined) {
this.intents = intents
} else throw new Error('No Gateway Intents were provided')
this.rest.token = token
if (this.shard !== undefined) {
if (typeof this.shardCount === 'number')
this.shards.cachedShardCount = this.shardCount
await this.shards.launch(this.shard)
} else await this.shards.connect()
return this.waitFor('ready', () => true).then(() => this)
}
/** Destroy the Gateway connection */
async destroy(): Promise<Client> {
this.gateway.initialized = false
this.gateway.sequenceID = undefined
this.gateway.sessionID = undefined
await this.gateway.cache.delete('seq')
await this.gateway.cache.delete('session_id')
this.gateway.close()
this.user = undefined
this.upSince = undefined
return this
}
/** Attempt to Close current Gateway connection and Resume */
async reconnect(): Promise<Client> {
this.gateway.close()
this.gateway.initWebsocket()
return this.waitFor('ready', () => true).then(() => this)
}
/** Add a new Collector */
addCollector(collector: Collector): boolean {
if (this.collectors.has(collector)) return false
else {
this.collectors.add(collector)
return true
}
}
/** Remove a Collector */
removeCollector(collector: Collector): boolean {
if (!this.collectors.has(collector)) return false
else {
this.collectors.delete(collector)
return true
}
}
async emit(event: keyof ClientEvents, ...args: any[]): Promise<void> {
const collectors: Collector[] = []
for (const collector of this.collectors.values()) {
if (collector.event === event) collectors.push(collector)
}
if (collectors.length !== 0) {
this.collectors.forEach((collector) => collector._fire(...args))
}
// TODO(DjDeveloperr): Fix this ts-ignore
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
// @ts-ignore
return super.emit(event, ...args)
}
/** Returns an array of voice region objects that can be used when creating servers. */
async fetchVoiceRegions(): Promise<VoiceRegion[]> {
return this.rest.api.voice.regions.get()
}
/** Modify current (Client) User. */
async editUser(data: {
username?: string
avatar?: string
}): Promise<Client> {
if (data.username === undefined && data.avatar === undefined)
throw new Error(
'Either username or avatar or both must be specified to edit'
)
if (data.avatar?.startsWith('http') === true) {
data.avatar = await fetchAuto(data.avatar)
}
await this.rest.api.users['@me'].patch({
username: data.username,
avatar: data.avatar
})
return this
}
/** Change Username of the Client User */
async setUsername(username: string): Promise<Client> {
return await this.editUser({ username })
}
/** Change Avatar of the Client User */
async setAvatar(avatar: string): Promise<Client> {
return await this.editUser({ avatar })
}
/** Create a DM Channel with a User */
async createDM(user: User | string): Promise<DMChannel> {
const id = typeof user === 'object' ? user.id : user
const dmPayload = await this.rest.api.users['@me'].channels.post({
recipient_id: id
})
await this.channels.set(dmPayload.id, dmPayload)
return (this.channels.get<DMChannel>(dmPayload.id) as unknown) as DMChannel
}
/** Returns a template object for the given code. */
async fetchTemplate(code: string): Promise<Template> {
const payload = await this.rest.api.guilds.templates[code].get()
return new Template(this, payload)
}
}
/** Event decorator to create an Event handler from function */
export function event(name?: keyof ClientEvents) {
return function (
client: Client | Extension,
prop: keyof ClientEvents | string
) {
const listener = ((client as unknown) as {
[name in keyof ClientEvents]: (...args: ClientEvents[name]) => any
})[(prop as unknown) as keyof ClientEvents]
if (typeof listener !== 'function')
throw new Error('@event decorator requires a function')
if (client._decoratedEvents === undefined) client._decoratedEvents = {}
const key = name === undefined ? prop : name
client._decoratedEvents[key] = listener
}
}
/* eslint-disable @typescript-eslint/method-signature-style */
import { User } from '../structures/user.ts'
import { GatewayIntents } from '../types/gateway.ts'
import { Gateway } from '../gateway/mod.ts'
import { RESTManager, RESTOptions, TokenType } from '../rest/mod.ts'
import { DefaultCacheAdapter, ICacheAdapter } from '../cache/adapter.ts'
import { UsersManager } from '../managers/users.ts'
import { GuildManager } from '../managers/guilds.ts'
import { ChannelsManager } from '../managers/channels.ts'
import { ClientPresence } from '../structures/presence.ts'
import { EmojisManager } from '../managers/emojis.ts'
import { ActivityGame, ClientActivity } from '../types/presence.ts'
import type { Extension } from '../commands/extension.ts'
import { SlashClient } from '../interactions/slashClient.ts'
import { Interaction } from '../structures/slash.ts'
import { ShardManager } from './shard.ts'
import { Application } from '../structures/application.ts'
import { Invite } from '../structures/invite.ts'
import { INVITE } from '../types/endpoint.ts'
import { ClientEvents } from '../gateway/handlers/mod.ts'
import type { Collector } from './collectors.ts'
import { HarmonyEventEmitter } from '../utils/events.ts'
import { VoiceRegion } from '../types/voice.ts'
import { fetchAuto } from '../../deps.ts'
import { DMChannel } from '../structures/dmChannel.ts'
import { Template } from '../structures/template.ts'
/** OS related properties sent with Gateway Identify */
export interface ClientProperties {
os?: 'darwin' | 'windows' | 'linux' | 'custom_os' | string
browser?: 'harmony' | string
device?: 'harmony' | string
}
/** Some Client Options to modify behaviour */
export interface ClientOptions {
/** ID of the Client/Application to initialize Slash Client REST */
id?: string
/** Token of the Bot/User */
token?: string
/** Gateway Intents */
intents?: GatewayIntents[]
/** Cache Adapter to use, defaults to Collections one */
cache?: ICacheAdapter
/** Force New Session and don't use cached Session (by persistent caching) */
forceNewSession?: boolean
/** Startup presence of client */
presence?: ClientPresence | ClientActivity | ActivityGame
/** Force all requests to Canary API */
canary?: boolean
/** Time till which Messages are to be cached, in MS. Default is 3600000 */
messageCacheLifetime?: number
/** Time till which Message Reactions are to be cached, in MS. Default is 3600000 */
reactionCacheLifetime?: number
/** Whether to fetch Uncached Message of Reaction or not? */
fetchUncachedReactions?: boolean
/** Client Properties */
clientProperties?: ClientProperties
/** Enable/Disable Slash Commands Integration (enabled by default) */
enableSlash?: boolean
/** Disable taking token from env if not provided (token is taken from env if present by default) */
disableEnvToken?: boolean
/** Override REST Options */
restOptions?: RESTOptions
/** Whether to fetch Gateway info or not */
fetchGatewayInfo?: boolean
/** ADVANCED: Shard ID to launch on */
shard?: number
/** ADVACNED: Shard count. */
shardCount?: number | 'auto'
}
/**
* Discord Client.
*/
export class Client extends HarmonyEventEmitter<ClientEvents> {
/** REST Manager - used to make all requests */
rest: RESTManager
/** User which Client logs in to, undefined until logs in */
user?: User
/** WebSocket ping of Client */
ping = 0
/** Token of the Bot/User */
token?: string
/** Cache Adapter */
cache: ICacheAdapter = new DefaultCacheAdapter()
/** Gateway Intents */
intents?: GatewayIntents[]
/** Whether to force new session or not */
forceNewSession?: boolean
/** Time till messages to stay cached, in MS. */
messageCacheLifetime: number = 3600000
/** Time till messages to stay cached, in MS. */
reactionCacheLifetime: number = 3600000
/** Whether to fetch Uncached Message of Reaction or not? */
fetchUncachedReactions: boolean = false
/** Client Properties */
clientProperties: ClientProperties
/** Slash-Commands Management client */
slash: SlashClient
/** Whether to fetch Gateway info or not */
fetchGatewayInfo: boolean = true
/** Users Manager, containing all Users cached */
users: UsersManager = new UsersManager(this)
/** Guilds Manager, providing cache & API interface to Guilds */
guilds: GuildManager = new GuildManager(this)
/** Channels Manager, providing cache interface to Channels */
channels: ChannelsManager = new ChannelsManager(this)
/** Channels Manager, providing cache interface to Channels */
emojis: EmojisManager = new EmojisManager(this)
/** Last READY timestamp */
upSince?: Date
/** Client's presence. Startup one if set before connecting */
presence: ClientPresence = new ClientPresence()
_decoratedEvents?: {
[name: string]: (...args: any[]) => void
}
_decoratedSlash?: Array<{
name: string
guild?: string
parent?: string
group?: string
handler: (interaction: Interaction) => any
}>
_id?: string
/** Shard on which this Client is */
shard?: number
/** Shard Count */
shardCount: number | 'auto' = 'auto'
/** Shard Manager of this Client if Sharded */
shards: ShardManager
/** Collectors set */
collectors: Set<Collector> = new Set()
/** Since when is Client online (ready). */
get uptime(): number {
if (this.upSince === undefined) return 0
else {
const dif = Date.now() - this.upSince.getTime()
if (dif < 0) return 0
else return dif
}
}
get gateway(): Gateway {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
return this.shards.list.get('0') as Gateway
}
applicationID?: string
applicationFlags?: number
constructor(options: ClientOptions = {}) {
super()
this._id = options.id
this.token = options.token
this.intents = options.intents
this.shards = new ShardManager(this)
this.forceNewSession = options.forceNewSession
if (options.cache !== undefined) this.cache = options.cache
if (options.presence !== undefined)
this.presence =
options.presence instanceof ClientPresence
? options.presence
: new ClientPresence(options.presence)
if (options.messageCacheLifetime !== undefined)
this.messageCacheLifetime = options.messageCacheLifetime
if (options.reactionCacheLifetime !== undefined)
this.reactionCacheLifetime = options.reactionCacheLifetime
if (options.fetchUncachedReactions === true)
this.fetchUncachedReactions = true
if (
this._decoratedEvents !== undefined &&
Object.keys(this._decoratedEvents).length !== 0
) {
Object.entries(this._decoratedEvents).forEach((entry) => {
this.on(entry[0] as keyof ClientEvents, entry[1].bind(this))
})
this._decoratedEvents = undefined
}
this.clientProperties =
options.clientProperties === undefined
? {
os: Deno.build.os,
browser: 'harmony',
device: 'harmony'
}
: options.clientProperties
if (options.shard !== undefined) this.shard = options.shard
if (options.shardCount !== undefined) this.shardCount = options.shardCount
this.fetchGatewayInfo = options.fetchGatewayInfo ?? true
if (this.token === undefined) {
try {
const token = Deno.env.get('DISCORD_TOKEN')
if (token !== undefined) {
this.token = token
this.debug('Info', 'Found token in ENV')
}
} catch (e) {}
}
const restOptions: RESTOptions = {
token: () => this.token,
tokenType: TokenType.Bot,
canary: options.canary,
client: this
}
if (options.restOptions !== undefined)
Object.assign(restOptions, options.restOptions)
this.rest = new RESTManager(restOptions)
this.slash = new SlashClient({
id: () => this.getEstimatedID(),
client: this,
enabled: options.enableSlash
})
}
/**
* Sets Cache Adapter
*
* Should NOT be set after bot is already logged in or using current cache.
* Please look into using `cache` option.
*/
setAdapter(adapter: ICacheAdapter): Client {
this.cache = adapter
return this
}
/** Changes Presence of Client */
setPresence(presence: ClientPresence | ClientActivity | ActivityGame): void {
if (presence instanceof ClientPresence) {
this.presence = presence
} else this.presence = new ClientPresence(presence)
this.gateway?.sendPresence(this.presence.create())
}
/** Emits debug event */
debug(tag: string, msg: string): void {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.emit('debug', `[${tag}] ${msg}`)
}
getEstimatedID(): string {
if (this.user !== undefined) return this.user.id
else if (this.token !== undefined) {
try {
return atob(this.token.split('.')[0])
} catch (e) {
return this._id ?? 'unknown'
}
} else {
return this._id ?? 'unknown'
}
}
/** Fetch Application of the Client */
async fetchApplication(): Promise<Application> {
const app = await this.rest.api.oauth2.applications['@me'].get()
return new Application(this, app)
}
/** Fetch an Invite */
async fetchInvite(id: string): Promise<Invite> {
return await new Promise((resolve, reject) => {
this.rest
.get(INVITE(id))
.then((data) => {
resolve(new Invite(this, data))
})
.catch((e) => reject(e))
})
}
/**
* This function is used for connecting to discord.
* @param token Your token. This is required if not given in ClientOptions.
* @param intents Gateway intents in array. This is required if not given in ClientOptions.
*/
async connect(token?: string, intents?: GatewayIntents[]): Promise<Client> {
token ??= this.token
if (token === undefined) throw new Error('No Token Provided')
this.token = token
if (intents !== undefined && this.intents !== undefined) {
this.debug(
'client',
'Intents were set in both client and connect function. Using the one in the connect function...'
)
} else if (intents === undefined && this.intents !== undefined) {
intents = this.intents
} else if (intents !== undefined && this.intents === undefined) {
this.intents = intents
} else throw new Error('No Gateway Intents were provided')
this.rest.token = token
if (this.shard !== undefined) {
if (typeof this.shardCount === 'number')
this.shards.cachedShardCount = this.shardCount
await this.shards.launch(this.shard)
} else await this.shards.connect()
return this.waitFor('ready', () => true).then(() => this)
}
/** Destroy the Gateway connection */
async destroy(): Promise<Client> {
this.gateway.initialized = false
this.gateway.sequenceID = undefined
this.gateway.sessionID = undefined
await this.gateway.cache.delete('seq')
await this.gateway.cache.delete('session_id')
this.gateway.close()
this.user = undefined
this.upSince = undefined
return this
}
/** Attempt to Close current Gateway connection and Resume */
async reconnect(): Promise<Client> {
this.gateway.close()
this.gateway.initWebsocket()
return this.waitFor('ready', () => true).then(() => this)
}
/** Add a new Collector */
addCollector(collector: Collector): boolean {
if (this.collectors.has(collector)) return false
else {
this.collectors.add(collector)
return true
}
}
/** Remove a Collector */
removeCollector(collector: Collector): boolean {
if (!this.collectors.has(collector)) return false
else {
this.collectors.delete(collector)
return true
}
}
async emit(event: keyof ClientEvents, ...args: any[]): Promise<void> {
const collectors: Collector[] = []
for (const collector of this.collectors.values()) {
if (collector.event === event) collectors.push(collector)
}
if (collectors.length !== 0) {
this.collectors.forEach((collector) => collector._fire(...args))
}
// TODO(DjDeveloperr): Fix this ts-ignore
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
// @ts-ignore
return super.emit(event, ...args)
}
/** Returns an array of voice region objects that can be used when creating servers. */
async fetchVoiceRegions(): Promise<VoiceRegion[]> {
return this.rest.api.voice.regions.get()
}
/** Modify current (Client) User. */
async editUser(data: {
username?: string
avatar?: string
}): Promise<Client> {
if (data.username === undefined && data.avatar === undefined)
throw new Error(
'Either username or avatar or both must be specified to edit'
)
if (data.avatar?.startsWith('http') === true) {
data.avatar = await fetchAuto(data.avatar)
}
await this.rest.api.users['@me'].patch({
username: data.username,
avatar: data.avatar
})
return this
}
/** Change Username of the Client User */
async setUsername(username: string): Promise<Client> {
return await this.editUser({ username })
}
/** Change Avatar of the Client User */
async setAvatar(avatar: string): Promise<Client> {
return await this.editUser({ avatar })
}
/** Create a DM Channel with a User */
async createDM(user: User | string): Promise<DMChannel> {
const id = typeof user === 'object' ? user.id : user
const dmPayload = await this.rest.api.users['@me'].channels.post({
recipient_id: id
})
await this.channels.set(dmPayload.id, dmPayload)
return (this.channels.get<DMChannel>(dmPayload.id) as unknown) as DMChannel
}
/** Returns a template object for the given code. */
async fetchTemplate(code: string): Promise<Template> {
const payload = await this.rest.api.guilds.templates[code].get()
return new Template(this, payload)
}
}
/** Event decorator to create an Event handler from function */
export function event(name?: keyof ClientEvents) {
return function (
client: Client | Extension,
prop: keyof ClientEvents | string
) {
const listener = ((client as unknown) as {
[name in keyof ClientEvents]: (...args: ClientEvents[name]) => any
})[(prop as unknown) as keyof ClientEvents]
if (typeof listener !== 'function')
throw new Error('@event decorator requires a function')
if (client._decoratedEvents === undefined) client._decoratedEvents = {}
const key = name === undefined ? prop : name
client._decoratedEvents[key] = listener
}
}

View File

@ -1,5 +1,5 @@
import { Collection } from '../utils/collection.ts'
import type { Client } from './client.ts'
import type { Client } from '../client/mod.ts'
import { HarmonyEventEmitter } from '../utils/events.ts'
export type CollectorFilter = (...args: any[]) => boolean | Promise<boolean>

3
src/client/mod.ts Normal file
View File

@ -0,0 +1,3 @@
export * from './client.ts'
export * from './collectors.ts'
export * from './shard.ts'

View File

@ -1,7 +1,7 @@
import { Collection } from '../utils/collection.ts'
import type { Client } from './client.ts'
import { RESTManager } from './rest.ts'
import { Gateway } from '../gateway/index.ts'
import { RESTManager } from '../rest/mod.ts'
import { Gateway } from '../gateway/mod.ts'
import { HarmonyEventEmitter } from '../utils/events.ts'
import { GatewayEvents } from '../types/gateway.ts'
import { delay } from '../utils/delay.ts'

View File

@ -1,6 +1,6 @@
import { Message } from '../structures/message.ts'
import { GuildTextBasedChannel } from '../structures/guildTextChannel.ts'
import { Client, ClientOptions } from './client.ts'
import { Client, ClientOptions } from '../client/mod.ts'
import {
CategoriesManager,
Command,
@ -9,7 +9,7 @@ import {
CommandsManager,
parseCommand
} from './command.ts'
import { Extension, ExtensionsManager } from './extensions.ts'
import { Extension, ExtensionsManager } from './extension.ts'
type PrefixReturnType = string | string[] | Promise<string | string[]>

View File

@ -3,8 +3,8 @@ import { Message } from '../structures/message.ts'
import { TextChannel } from '../structures/textChannel.ts'
import { User } from '../structures/user.ts'
import { Collection } from '../utils/collection.ts'
import { CommandClient } from './commandClient.ts'
import { Extension } from './extensions.ts'
import type { CommandClient } from './client.ts'
import type { Extension } from './extension.ts'
import { join, walk } from '../../deps.ts'
export interface CommandContext {

View File

@ -1,7 +1,7 @@
import { ClientEvents } from '../../mod.ts'
import { Collection } from '../utils/collection.ts'
import { Command } from './command.ts'
import { CommandClient } from './commandClient.ts'
import { CommandClient } from './client.ts'
export type ExtensionEventCallback = (ext: Extension, ...args: any[]) => any

3
src/commands/mod.ts Normal file
View File

@ -0,0 +1,3 @@
export * from './client.ts'
export * from './command.ts'
export * from './extension.ts'

View File

@ -1,9 +0,0 @@
export const DISCORD_API_URL: string = 'https://discord.com/api'
export const DISCORD_GATEWAY_URL: string = 'wss://gateway.discord.gg'
export const DISCORD_CDN_URL: string = 'https://cdn.discordapp.com'
export const DISCORD_API_VERSION: number = 8
export const DISCORD_VOICE_VERSION: number = 4

View File

@ -1,6 +1,6 @@
import { SlashCommand } from '../../models/slashClient.ts'
import { SlashCommand } from '../../interactions/slashCommand.ts'
import { ApplicationCommandPayload } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const applicationCommandCreate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,6 +1,6 @@
import { SlashCommand } from '../../models/slashClient.ts'
import { SlashCommand } from '../../interactions/slashCommand.ts'
import { ApplicationCommandPayload } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const applicationCommandDelete: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,6 +1,6 @@
import { SlashCommand } from '../../models/slashClient.ts'
import { SlashCommand } from '../../interactions/slashCommand.ts'
import { ApplicationCommandPayload } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const applicationCommandUpdate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import getChannelByType from '../../utils/getChannelByType.ts'
import { ChannelPayload, GuildChannelPayload } from '../../types/channel.ts'
import { Guild } from '../../structures/guild.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { ChannelPayload } from '../../types/channel.ts'
export const channelDelete: GatewayEventHandler = async (

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { TextChannel } from '../../structures/textChannel.ts'
import { ChannelPinsUpdatePayload } from '../../types/gateway.ts'

View File

@ -1,6 +1,6 @@
import { Channel } from '../../structures/channel.ts'
import { ChannelPayload } from '../../types/channel.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const channelUpdate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { User } from '../../structures/user.ts'
import { GuildBanAddPayload } from '../../types/gateway.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { User } from '../../structures/user.ts'
import { GuildBanRemovePayload } from '../../types/gateway.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildPayload } from '../../types/guild.ts'
import { GuildChannelPayload } from '../../types/channel.ts'

View File

@ -1,6 +1,6 @@
import { Guild } from '../../structures/guild.ts'
import { GuildPayload } from '../../types/guild.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const guildDelete: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -2,7 +2,7 @@ import { Emoji } from '../../structures/emoji.ts'
import { Guild } from '../../structures/guild.ts'
import { EmojiPayload } from '../../types/emoji.ts'
import { GuildEmojiUpdatePayload } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const guildEmojiUpdate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildIntegrationsUpdatePayload } from '../../types/gateway.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildMemberAddPayload } from '../../types/gateway.ts'
import { Member } from '../../structures/member.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { User } from '../../structures/user.ts'
import { GuildMemberRemovePayload } from '../../types/gateway.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildMemberUpdatePayload } from '../../types/gateway.ts'
import { MemberPayload } from '../../types/guild.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildMemberChunkPayload } from '../../types/gateway.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildRoleCreatePayload } from '../../types/gateway.ts'
import { Role } from '../../structures/role.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildRoleDeletePayload } from '../../types/gateway.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildRoleUpdatePayload } from '../../types/gateway.ts'
import { Role } from '../../structures/role.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { GuildPayload } from '../../types/guild.ts'

View File

@ -9,7 +9,7 @@ import { GuildTextBasedChannel } from '../../structures/guildTextChannel.ts'
import { InteractionPayload } from '../../types/slash.ts'
import { UserPayload } from '../../types/user.ts'
import { Permissions } from '../../utils/permissions.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { User } from '../../structures/user.ts'
import { Role } from '../../structures/role.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { InviteCreatePayload } from '../../types/gateway.ts'
import { ChannelPayload } from '../../types/channel.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { InviteDeletePayload } from '../../types/gateway.ts'
import { PartialInvitePayload } from '../../types/invite.ts'

View File

@ -2,7 +2,7 @@ import { Message } from '../../structures/message.ts'
import { TextChannel } from '../../structures/textChannel.ts'
import { User } from '../../structures/user.ts'
import { MessagePayload } from '../../types/channel.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const messageCreate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,6 +1,6 @@
import { TextChannel } from '../../structures/textChannel.ts'
import { MessageDeletePayload } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const messageDelete: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -2,7 +2,7 @@ import { Message } from '../../structures/message.ts'
import { GuildTextBasedChannel } from '../../structures/guildTextChannel.ts'
import { MessageDeleteBulkPayload } from '../../types/gateway.ts'
import { Collection } from '../../utils/collection.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const messageDeleteBulk: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { MessageReactionAddPayload } from '../../types/gateway.ts'
import { TextChannel } from '../../structures/textChannel.ts'
import { MessageReaction } from '../../structures/messageReaction.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { MessageReactionRemovePayload } from '../../types/gateway.ts'
import { TextChannel } from '../../structures/textChannel.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { MessageReactionRemoveAllPayload } from '../../types/gateway.ts'
import { TextChannel } from '../../structures/textChannel.ts'

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { MessageReactionRemoveEmojiPayload } from '../../types/gateway.ts'
import { TextChannel } from '../../structures/textChannel.ts'

View File

@ -1,7 +1,7 @@
import { Message } from '../../structures/message.ts'
import { TextChannel } from '../../structures/textChannel.ts'
import { MessagePayload } from '../../types/channel.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const messageUpdate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,4 +1,4 @@
import { GatewayEventHandler } from '../index.ts'
import type { GatewayEventHandler } from '../mod.ts'
import {
GatewayEvents,
MessageDeletePayload,
@ -60,14 +60,14 @@ import {
} from '../../utils/getChannelByType.ts'
import { interactionCreate } from './interactionCreate.ts'
import { Interaction } from '../../structures/slash.ts'
import { CommandContext } from '../../models/command.ts'
import { RequestMethods } from '../../models/rest.ts'
import { CommandContext } from '../../commands/command.ts'
import { RequestMethods } from '../../rest/types.ts'
import { PartialInvitePayload } from '../../types/invite.ts'
import { GuildChannels } from '../../types/guild.ts'
import { applicationCommandCreate } from './applicationCommandCreate.ts'
import { applicationCommandDelete } from './applicationCommandDelete.ts'
import { applicationCommandUpdate } from './applicationCommandUpdate.ts'
import { SlashCommand } from '../../models/slashClient.ts'
import { SlashCommand } from '../../interactions/slashCommand.ts'
export const gatewayHandlers: {
[eventCode in GatewayEvents]: GatewayEventHandler | undefined

View File

@ -1,5 +1,5 @@
import { PresenceUpdatePayload } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const presenceUpdate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,7 +1,7 @@
import { User } from '../../structures/user.ts'
import { Ready } from '../../types/gateway.ts'
import { GuildPayload } from '../../types/guild.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const ready: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const reconnect: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,7 +1,7 @@
import { User } from '../../structures/user.ts'
import { CLIENT_USER } from '../../types/endpoint.ts'
import { Resume } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const resume: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,7 +1,7 @@
import { Member } from '../../structures/member.ts'
import { TextChannel } from '../../structures/textChannel.ts'
import { TypingStartPayload } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
// TODO: Do we need to add uncached events here?
export const typingStart: GatewayEventHandler = async (

View File

@ -1,6 +1,6 @@
import { User } from '../../structures/user.ts'
import { UserPayload } from '../../types/user.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const userUpdate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,6 +1,6 @@
import { Guild } from '../../structures/guild.ts'
import { VoiceServerUpdatePayload } from '../../types/gateway.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const voiceServerUpdate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -2,7 +2,7 @@ import { Guild } from '../../structures/guild.ts'
import { VoiceState } from '../../structures/voiceState.ts'
import { MemberPayload } from '../../types/guild.ts'
import { VoiceStatePayload } from '../../types/voice.ts'
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
export const voiceStateUpdate: GatewayEventHandler = async (
gateway: Gateway,

View File

@ -1,4 +1,4 @@
import { Gateway, GatewayEventHandler } from '../index.ts'
import type { Gateway, GatewayEventHandler } from '../mod.ts'
import { Guild } from '../../structures/guild.ts'
import { WebhooksUpdatePayload } from '../../types/gateway.ts'
import { GuildTextBasedChannel } from '../../structures/guildTextChannel.ts'

View File

@ -1,9 +1,5 @@
import { unzlib } from '../../deps.ts'
import { Client } from '../models/client.ts'
import {
DISCORD_GATEWAY_URL,
DISCORD_API_VERSION
} from '../consts/urlsAndVersions.ts'
import { Client } from '../client/mod.ts'
import { GatewayResponse } from '../types/gatewayResponse.ts'
import {
GatewayOpcodes,
@ -12,13 +8,14 @@ import {
StatusUpdatePayload,
GatewayEvents
} from '../types/gateway.ts'
import { gatewayHandlers } from './handlers/index.ts'
import { gatewayHandlers } from './handlers/mod.ts'
import { GatewayCache } from '../managers/gatewayCache.ts'
import { delay } from '../utils/delay.ts'
import { VoiceChannel } from '../structures/guildVoiceChannel.ts'
import { Guild } from '../structures/guild.ts'
import { HarmonyEventEmitter } from '../utils/events.ts'
import { decodeText } from '../utils/encoding.ts'
import { Constants } from '../types/constants.ts'
export interface RequestMembersOptions {
limit?: number
@ -417,7 +414,7 @@ export class Gateway extends HarmonyEventEmitter<GatewayTypedEvents> {
this.debug('Initializing WebSocket...')
this.websocket = new WebSocket(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`${DISCORD_GATEWAY_URL}/?v=${DISCORD_API_VERSION}&encoding=json`,
`${Constants.DISCORD_GATEWAY_URL}/?v=${Constants.DISCORD_API_VERSION}&encoding=json`,
[]
)
this.websocket.binaryType = 'arraybuffer'

3
src/interactions/mod.ts Normal file
View File

@ -0,0 +1,3 @@
export * from './slashClient.ts'
export * from './slashModule.ts'
export * from './slashCommand.ts'

View File

@ -1,4 +1,3 @@
import type { Guild } from '../structures/guild.ts'
import {
Interaction,
InteractionApplicationCommandResolved
@ -7,358 +6,16 @@ import {
InteractionPayload,
InteractionResponsePayload,
InteractionType,
SlashCommandChoice,
SlashCommandOption,
SlashCommandOptionType,
SlashCommandPartial,
SlashCommandPayload
SlashCommandOptionType
} from '../types/slash.ts'
import { Collection } from '../utils/collection.ts'
import type { Client } from './client.ts'
import { RESTManager } from './rest.ts'
import type { Client } from '../client/mod.ts'
import { RESTManager } from '../rest/mod.ts'
import { SlashModule } from './slashModule.ts'
import { verify as edverify } from 'https://deno.land/x/ed25519@1.0.1/mod.ts'
import { User } from '../structures/user.ts'
import { HarmonyEventEmitter } from '../utils/events.ts'
import { encodeText, decodeText } from '../utils/encoding.ts'
export class SlashCommand {
slash: SlashCommandsManager
id: string
applicationID: string
name: string
description: string
options: SlashCommandOption[]
guild?: Guild
_guild?: string
constructor(
manager: SlashCommandsManager,
data: SlashCommandPayload,
guild?: Guild
) {
this.slash = manager
this.id = data.id
this.applicationID = data.application_id
this.name = data.name
this.description = data.description
this.options = data.options ?? []
this.guild = guild
}
async delete(): Promise<void> {
await this.slash.delete(this.id, this._guild)
}
async edit(data: SlashCommandPartial): Promise<void> {
await this.slash.edit(this.id, data, this._guild)
}
/** Create a handler for this Slash Command */
handle(
func: SlashCommandHandlerCallback,
options?: { parent?: string; group?: string }
): SlashCommand {
this.slash.slash.handle({
name: this.name,
parent: options?.parent,
group: options?.group,
guild: this._guild,
handler: func
})
return this
}
}
export interface CreateOptions {
name: string
description?: string
options?: Array<SlashCommandOption | SlashOptionCallable>
choices?: Array<SlashCommandChoice | string>
}
function createSlashOption(
type: SlashCommandOptionType,
data: CreateOptions
): SlashCommandOption {
return {
name: data.name,
type,
description:
type === 0 || type === 1
? undefined
: data.description ?? 'No description.',
options: data.options?.map((e) =>
typeof e === 'function' ? e(SlashOption) : e
),
choices:
data.choices === undefined
? undefined
: data.choices.map((e) =>
typeof e === 'string' ? { name: e, value: e } : e
)
}
}
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class SlashOption {
static string(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.STRING, data)
}
static bool(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.BOOLEAN, data)
}
static subCommand(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.SUB_COMMAND, data)
}
static subCommandGroup(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.SUB_COMMAND_GROUP, data)
}
static role(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.ROLE, data)
}
static channel(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.CHANNEL, data)
}
static user(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.USER, data)
}
static number(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.INTEGER, data)
}
}
export type SlashOptionCallable = (o: typeof SlashOption) => SlashCommandOption
export type SlashBuilderOptionsData =
| Array<SlashCommandOption | SlashOptionCallable>
| {
[name: string]:
| {
description: string
type: SlashCommandOptionType
options?: SlashCommandOption[]
choices?: SlashCommandChoice[]
}
| SlashOptionCallable
}
function buildOptionsArray(
options: SlashBuilderOptionsData
): SlashCommandOption[] {
return Array.isArray(options)
? options.map((op) => (typeof op === 'function' ? op(SlashOption) : op))
: Object.entries(options).map((entry) =>
typeof entry[1] === 'function'
? entry[1](SlashOption)
: Object.assign(entry[1], { name: entry[0] })
)
}
/** Slash Command Builder */
export class SlashBuilder {
data: SlashCommandPartial
constructor(
name?: string,
description?: string,
options?: SlashBuilderOptionsData
) {
this.data = {
name: name ?? '',
description: description ?? 'No description.',
options: options === undefined ? [] : buildOptionsArray(options)
}
}
name(name: string): SlashBuilder {
this.data.name = name
return this
}
description(desc: string): SlashBuilder {
this.data.description = desc
return this
}
option(option: SlashOptionCallable | SlashCommandOption): SlashBuilder {
if (this.data.options === undefined) this.data.options = []
this.data.options.push(
typeof option === 'function' ? option(SlashOption) : option
)
return this
}
options(options: SlashBuilderOptionsData): SlashBuilder {
this.data.options = buildOptionsArray(options)
return this
}
export(): SlashCommandPartial {
if (this.data.name === '')
throw new Error('Name was not provided in Slash Builder')
return this.data
}
}
/** Manages Slash Commands, allows fetching/modifying/deleting/creating Slash Commands. */
export class SlashCommandsManager {
slash: SlashClient
rest: RESTManager
constructor(client: SlashClient) {
this.slash = client
this.rest = client.rest
}
/** Get all Global Slash Commands */
async all(): Promise<Collection<string, SlashCommand>> {
const col = new Collection<string, SlashCommand>()
const res = (await this.rest.api.applications[
this.slash.getID()
].commands.get()) as SlashCommandPayload[]
if (!Array.isArray(res)) return col
for (const raw of res) {
const cmd = new SlashCommand(this, raw)
col.set(raw.id, cmd)
}
return col
}
/** Get a Guild's Slash Commands */
async guild(
guild: Guild | string
): Promise<Collection<string, SlashCommand>> {
const col = new Collection<string, SlashCommand>()
const res = (await this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands.get()) as SlashCommandPayload[]
if (!Array.isArray(res)) return col
const _guild =
typeof guild === 'object'
? guild
: await this.slash.client?.guilds.get(guild)
for (const raw of res) {
const cmd = new SlashCommand(this, raw, _guild)
cmd._guild = typeof guild === 'string' ? guild : guild.id
col.set(raw.id, cmd)
}
return col
}
/** Create a Slash Command (global or Guild) */
async create(
data: SlashCommandPartial,
guild?: Guild | string
): Promise<SlashCommand> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands
const payload = await route.post(data)
const _guild =
typeof guild === 'object'
? guild
: guild === undefined
? undefined
: await this.slash.client?.guilds.get(guild)
const cmd = new SlashCommand(this, payload, _guild)
cmd._guild =
typeof guild === 'string' || guild === undefined ? guild : guild.id
return cmd
}
/** Edit a Slash Command (global or Guild) */
async edit(
id: string,
data: SlashCommandPartial,
guild?: Guild | string
): Promise<SlashCommandsManager> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands[id]
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands[id]
await route.patch(data)
return this
}
/** Delete a Slash Command (global or Guild) */
async delete(
id: string,
guild?: Guild | string
): Promise<SlashCommandsManager> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands[id]
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands[id]
await route.delete()
return this
}
/** Get a Slash Command (global or Guild) */
async get(id: string, guild?: Guild | string): Promise<SlashCommand> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands[id]
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands[id]
const data = await route.get()
const _guild =
typeof guild === 'object'
? guild
: guild === undefined
? undefined
: await this.slash.client?.guilds.get(guild)
return new SlashCommand(this, data, _guild)
}
/** Bulk Edit Global or Guild Slash Commands */
async bulkEdit(
cmds: Array<SlashCommandPartial | SlashCommandPayload>,
guild?: Guild | string
): Promise<SlashCommandsManager> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands
await route.put(cmds)
return this
}
}
import { SlashCommandsManager } from './slashCommand.ts'
export type SlashCommandHandlerCallback = (interaction: Interaction) => unknown
export interface SlashCommandHandler {

View File

@ -0,0 +1,349 @@
import { RESTManager } from '../rest/manager.ts'
import { Guild } from '../structures/guild.ts'
import {
SlashCommandChoice,
SlashCommandOption,
SlashCommandOptionType,
SlashCommandPartial,
SlashCommandPayload
} from '../types/slash.ts'
import { Collection } from '../utils/collection.ts'
import type { SlashClient, SlashCommandHandlerCallback } from './slashClient.ts'
export class SlashCommand {
slash: SlashCommandsManager
id: string
applicationID: string
name: string
description: string
options: SlashCommandOption[]
guild?: Guild
_guild?: string
constructor(
manager: SlashCommandsManager,
data: SlashCommandPayload,
guild?: Guild
) {
this.slash = manager
this.id = data.id
this.applicationID = data.application_id
this.name = data.name
this.description = data.description
this.options = data.options ?? []
this.guild = guild
}
async delete(): Promise<void> {
await this.slash.delete(this.id, this._guild)
}
async edit(data: SlashCommandPartial): Promise<void> {
await this.slash.edit(this.id, data, this._guild)
}
/** Create a handler for this Slash Command */
handle(
func: SlashCommandHandlerCallback,
options?: { parent?: string; group?: string }
): SlashCommand {
this.slash.slash.handle({
name: this.name,
parent: options?.parent,
group: options?.group,
guild: this._guild,
handler: func
})
return this
}
}
export interface CreateOptions {
name: string
description?: string
options?: Array<SlashCommandOption | SlashOptionCallable>
choices?: Array<SlashCommandChoice | string>
}
function createSlashOption(
type: SlashCommandOptionType,
data: CreateOptions
): SlashCommandOption {
return {
name: data.name,
type,
description:
type === 0 || type === 1
? undefined
: data.description ?? 'No description.',
options: data.options?.map((e) =>
typeof e === 'function' ? e(SlashOption) : e
),
choices:
data.choices === undefined
? undefined
: data.choices.map((e) =>
typeof e === 'string' ? { name: e, value: e } : e
)
}
}
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class SlashOption {
static string(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.STRING, data)
}
static bool(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.BOOLEAN, data)
}
static subCommand(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.SUB_COMMAND, data)
}
static subCommandGroup(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.SUB_COMMAND_GROUP, data)
}
static role(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.ROLE, data)
}
static channel(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.CHANNEL, data)
}
static user(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.USER, data)
}
static number(data: CreateOptions): SlashCommandOption {
return createSlashOption(SlashCommandOptionType.INTEGER, data)
}
}
export type SlashOptionCallable = (o: typeof SlashOption) => SlashCommandOption
export type SlashBuilderOptionsData =
| Array<SlashCommandOption | SlashOptionCallable>
| {
[name: string]:
| {
description: string
type: SlashCommandOptionType
options?: SlashCommandOption[]
choices?: SlashCommandChoice[]
}
| SlashOptionCallable
}
function buildOptionsArray(
options: SlashBuilderOptionsData
): SlashCommandOption[] {
return Array.isArray(options)
? options.map((op) => (typeof op === 'function' ? op(SlashOption) : op))
: Object.entries(options).map((entry) =>
typeof entry[1] === 'function'
? entry[1](SlashOption)
: Object.assign(entry[1], { name: entry[0] })
)
}
/** Slash Command Builder */
export class SlashBuilder {
data: SlashCommandPartial
constructor(
name?: string,
description?: string,
options?: SlashBuilderOptionsData
) {
this.data = {
name: name ?? '',
description: description ?? 'No description.',
options: options === undefined ? [] : buildOptionsArray(options)
}
}
name(name: string): SlashBuilder {
this.data.name = name
return this
}
description(desc: string): SlashBuilder {
this.data.description = desc
return this
}
option(option: SlashOptionCallable | SlashCommandOption): SlashBuilder {
if (this.data.options === undefined) this.data.options = []
this.data.options.push(
typeof option === 'function' ? option(SlashOption) : option
)
return this
}
options(options: SlashBuilderOptionsData): SlashBuilder {
this.data.options = buildOptionsArray(options)
return this
}
export(): SlashCommandPartial {
if (this.data.name === '')
throw new Error('Name was not provided in Slash Builder')
return this.data
}
}
/** Manages Slash Commands, allows fetching/modifying/deleting/creating Slash Commands. */
export class SlashCommandsManager {
slash: SlashClient
rest: RESTManager
constructor(client: SlashClient) {
this.slash = client
this.rest = client.rest
}
/** Get all Global Slash Commands */
async all(): Promise<Collection<string, SlashCommand>> {
const col = new Collection<string, SlashCommand>()
const res = (await this.rest.api.applications[
this.slash.getID()
].commands.get()) as SlashCommandPayload[]
if (!Array.isArray(res)) return col
for (const raw of res) {
const cmd = new SlashCommand(this, raw)
col.set(raw.id, cmd)
}
return col
}
/** Get a Guild's Slash Commands */
async guild(
guild: Guild | string
): Promise<Collection<string, SlashCommand>> {
const col = new Collection<string, SlashCommand>()
const res = (await this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands.get()) as SlashCommandPayload[]
if (!Array.isArray(res)) return col
const _guild =
typeof guild === 'object'
? guild
: await this.slash.client?.guilds.get(guild)
for (const raw of res) {
const cmd = new SlashCommand(this, raw, _guild)
cmd._guild = typeof guild === 'string' ? guild : guild.id
col.set(raw.id, cmd)
}
return col
}
/** Create a Slash Command (global or Guild) */
async create(
data: SlashCommandPartial,
guild?: Guild | string
): Promise<SlashCommand> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands
const payload = await route.post(data)
const _guild =
typeof guild === 'object'
? guild
: guild === undefined
? undefined
: await this.slash.client?.guilds.get(guild)
const cmd = new SlashCommand(this, payload, _guild)
cmd._guild =
typeof guild === 'string' || guild === undefined ? guild : guild.id
return cmd
}
/** Edit a Slash Command (global or Guild) */
async edit(
id: string,
data: SlashCommandPartial,
guild?: Guild | string
): Promise<SlashCommandsManager> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands[id]
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands[id]
await route.patch(data)
return this
}
/** Delete a Slash Command (global or Guild) */
async delete(
id: string,
guild?: Guild | string
): Promise<SlashCommandsManager> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands[id]
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands[id]
await route.delete()
return this
}
/** Get a Slash Command (global or Guild) */
async get(id: string, guild?: Guild | string): Promise<SlashCommand> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands[id]
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands[id]
const data = await route.get()
const _guild =
typeof guild === 'object'
? guild
: guild === undefined
? undefined
: await this.slash.client?.guilds.get(guild)
return new SlashCommand(this, data, _guild)
}
/** Bulk Edit Global or Guild Slash Commands */
async bulkEdit(
cmds: Array<SlashCommandPartial | SlashCommandPayload>,
guild?: Guild | string
): Promise<SlashCommandsManager> {
const route =
guild === undefined
? this.rest.api.applications[this.slash.getID()].commands
: this.rest.api.applications[this.slash.getID()].guilds[
typeof guild === 'string' ? guild : guild.id
].commands
await route.put(cmds)
return this
}
}

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Collection } from '../utils/collection.ts'
/**

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Collection } from '../utils/collection.ts'
import { BaseManager } from './base.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Channel } from '../structures/channel.ts'
import { Embed } from '../structures/embed.ts'
import { Message } from '../structures/message.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Emoji } from '../structures/emoji.ts'
import { EmojiPayload } from '../types/emoji.ts'
import { GUILD_EMOJI } from '../types/endpoint.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
/**
* Cache Manager used for Caching values related to Gateway connection

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { BaseChildManager } from './baseChild.ts'
import { VoiceStatePayload } from '../types/voice.ts'
import { VoiceState } from '../structures/voiceState.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Channel } from '../structures/channel.ts'
import { Guild } from '../structures/guild.ts'
import { CategoryChannel } from '../structures/guildCategoryChannel.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Emoji } from '../structures/emoji.ts'
import { Guild } from '../structures/guild.ts'
import { Role } from '../structures/role.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Guild } from '../structures/guild.ts'
import { VoiceChannel } from '../structures/guildVoiceChannel.ts'
import { User } from '../structures/user.ts'

View File

@ -1,5 +1,5 @@
import { fetchAuto } from '../../deps.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Guild } from '../structures/guild.ts'
import { Template } from '../structures/template.ts'
import { Role } from '../structures/role.ts'

View File

@ -1,5 +1,5 @@
import { GuildTextChannel, User } from '../../mod.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Guild } from '../structures/guild.ts'
import { Invite } from '../structures/invite.ts'
import { CHANNEL_INVITES, GUILD_INVITES, INVITE } from '../types/endpoint.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { BaseChildManager } from './baseChild.ts'
import { RolePayload } from '../types/role.ts'
import { Role } from '../structures/role.ts'

View File

@ -1,5 +1,5 @@
import { User } from '../structures/user.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Guild } from '../structures/guild.ts'
import { Member } from '../structures/member.ts'
import { GUILD_MEMBER } from '../types/endpoint.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Emoji } from '../structures/emoji.ts'
import { Guild } from '../structures/guild.ts'
import { Message } from '../structures/message.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Message } from '../structures/message.ts'
import { TextChannel } from '../structures/textChannel.ts'
import { User } from '../structures/user.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Guild } from '../structures/guild.ts'
import { Presence } from '../structures/presence.ts'
import { User } from '../structures/user.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { MessageReaction } from '../structures/messageReaction.ts'
import { User } from '../structures/user.ts'
import { UsersManager } from './users.ts'

View File

@ -1,5 +1,5 @@
import { Permissions } from '../../mod.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Guild } from '../structures/guild.ts'
import { Role } from '../structures/role.ts'
import { GUILD_ROLE, GUILD_ROLES } from '../types/endpoint.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { User } from '../structures/user.ts'
import { USER } from '../types/endpoint.ts'
import { UserPayload } from '../types/user.ts'

File diff suppressed because it is too large Load Diff

2
src/rest/mod.ts Normal file
View File

@ -0,0 +1,2 @@
export * from './manager.ts'
export * from './types.ts'

37
src/rest/types.ts Normal file
View File

@ -0,0 +1,37 @@
export type RequestMethods =
| 'get'
| 'post'
| 'put'
| 'patch'
| 'head'
| 'delete'
export enum HttpResponseCode {
Ok = 200,
Created = 201,
NoContent = 204,
NotModified = 304,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
TooManyRequests = 429,
GatewayUnavailable = 502
}
export interface RequestHeaders {
[name: string]: string
}
export interface DiscordAPIErrorPayload {
url: string
status: number
method: string
code?: number
message?: string
errors: object
requestData: { [key: string]: any }
}
export const METHODS = ['get', 'post', 'patch', 'put', 'delete', 'head']

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { ApplicationPayload } from '../types/application.ts'
import { SnowflakeBase } from './base.ts'
import { User } from './user.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Snowflake } from '../utils/snowflake.ts'
export class Base {

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import {
ChannelPayload,
ChannelTypes,
@ -81,7 +81,7 @@ export class GuildChannel extends Channel {
const stringToObject =
typeof target === 'string'
? (await this.guild.members.get(target)) ??
(await this.guild.roles.get(target))
(await this.guild.roles.get(target))
: target
if (stringToObject === undefined) {
@ -128,7 +128,7 @@ export class GuildChannel extends Channel {
const stringToObject =
typeof target === 'string'
? (await this.guild.members.get(target)) ??
(await this.guild.roles.get(target))
(await this.guild.roles.get(target))
: target
if (stringToObject === undefined) {
@ -200,8 +200,8 @@ export class GuildChannel extends Channel {
overwrite.id instanceof Role
? 0
: overwrite.id instanceof Member
? 1
: overwrite.type
? 1
: overwrite.type
if (type === undefined) {
throw new Error('Overwrite type is undefined.')
}
@ -233,8 +233,8 @@ export class GuildChannel extends Channel {
overwrite.id instanceof Role
? 0
: overwrite.id instanceof Member
? 1
: overwrite.type
? 1
: overwrite.type
if (type === undefined) {
throw new Error('Overwrite type is undefined.')
}
@ -303,7 +303,10 @@ export class GuildChannel extends Channel {
: overwrite.allow?.toJSON() ?? overwrites[index].allow
}
if (overwrite.deny !== undefined && overwriteDeny !== OverrideType.REPLACE) {
if (
overwrite.deny !== undefined &&
overwriteDeny !== OverrideType.REPLACE
) {
switch (overwriteDeny) {
case OverrideType.ADD: {
const originalDeny = new Permissions(overwrites[index].deny)
@ -331,8 +334,8 @@ export class GuildChannel extends Channel {
overwrite.id instanceof Role
? 0
: overwrite.id instanceof Member
? 1
: overwrite.type
? 1
: overwrite.type
if (type === undefined) {
throw new Error('Overwrite type is undefined.')
}

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { DMChannelPayload } from '../types/channel.ts'
import { UserPayload } from '../types/user.ts'
import { TextChannel } from './textChannel.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { ImageSize } from '../types/cdn.ts'
import { EmojiPayload } from '../types/emoji.ts'
import { CUSTOM_EMOJI, EMOJI } from '../types/endpoint.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { GroupDMChannelPayload } from '../types/channel.ts'
import { Channel } from './channel.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import {
GuildBanPayload,
GuildFeatures,
@ -41,11 +41,11 @@ import {
GUILD_SPLASH
} from '../types/endpoint.ts'
import { GuildVoiceStatesManager } from '../managers/guildVoiceStates.ts'
import { RequestMembersOptions } from '../gateway/index.ts'
import { RequestMembersOptions } from '../gateway/mod.ts'
import { GuildPresencesManager } from '../managers/presences.ts'
import { TemplatePayload } from '../types/template.ts'
import { Template } from './template.ts'
import { DiscordAPIError } from '../models/rest.ts'
import { DiscordAPIError } from '../rest/mod.ts'
import { ImageFormats, ImageSize } from '../types/cdn.ts'
import { ImageURL } from './cdn.ts'

View File

@ -1,7 +1,7 @@
import { Mixin } from '../../deps.ts'
import { TextChannel } from './textChannel.ts'
import { GuildChannel } from './channel.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import {
ChannelTypes,
GuildTextBasedChannelPayload,

View File

@ -1,6 +1,6 @@
import { VoiceServerUpdateData } from '../gateway/handlers/index.ts'
import { VoiceStateOptions } from '../gateway/index.ts'
import { Client } from '../models/client.ts'
import { VoiceServerUpdateData } from '../gateway/handlers/mod.ts'
import { VoiceStateOptions } from '../gateway/mod.ts'
import { Client } from '../client/mod.ts'
import {
GuildVoiceChannelPayload,
ModifyVoiceChannelOption,

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { ChannelPayload } from '../types/channel.ts'
import { INVITE } from '../types/endpoint.ts'
import { GuildPayload } from '../types/guild.ts'

View File

@ -1,5 +1,5 @@
import { MemberRolesManager } from '../managers/memberRoles.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { GUILD_MEMBER } from '../types/endpoint.ts'
import { MemberPayload } from '../types/guild.ts'
import { Permissions } from '../utils/permissions.ts'

View File

@ -8,7 +8,7 @@ import {
MessagePayload,
MessageReference
} from '../types/channel.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { User } from './user.ts'
import { Member } from './member.ts'
import { Embed } from './embed.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { MessagePayload } from '../types/channel.ts'
import { Collection } from '../utils/collection.ts'
import { GuildTextBasedChannel } from './guildTextChannel.ts'

View File

@ -1,5 +1,5 @@
import { ReactionUsersManager } from '../managers/reactionUsers.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { Reaction } from '../types/channel.ts'
import { Base } from './base.ts'
import { Emoji } from './emoji.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import {
MessageStickerFormatTypes,
MessageStickerPayload

View File

@ -9,7 +9,7 @@ import { PresenceUpdatePayload, StatusUpdatePayload } from '../types/gateway.ts'
import { Base } from './base.ts'
import { Guild } from './guild.ts'
import { User } from './user.ts'
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
export enum ActivityTypes {
PLAYING = 0,

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import { SnowflakeBase } from './base.ts'
import { RoleModifyPayload, RolePayload } from '../types/role.ts'
import { Permissions } from '../utils/permissions.ts'

View File

@ -1,4 +1,4 @@
import { Client } from '../models/client.ts'
import { Client } from '../client/mod.ts'
import {
AllowedMentionsPayload,
ChannelTypes,

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