Merge branch 'main' into slash

This commit is contained in:
Helloyunho 2021-03-05 19:47:30 +09:00 committed by GitHub
commit 3e81002c33
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 169 additions and 19 deletions

3
.eggignore Normal file
View file

@ -0,0 +1,3 @@
extends .gitignore
./src/test/**/*

View file

@ -30,13 +30,15 @@
You can import the package from https://deno.land/x/harmony/mod.ts (with latest version) or can add a version too, and raw GitHub URL (latest unpublished version) https://raw.githubusercontent.com/harmonyland/harmony/main/mod.ts too. You can import the package from https://deno.land/x/harmony/mod.ts (with latest version) or can add a version too, and raw GitHub URL (latest unpublished version) https://raw.githubusercontent.com/harmonyland/harmony/main/mod.ts too.
You can also check(not import) the module in https://nest.land/package/harmony (link for importing is in the site).
For a quick example, run this: For a quick example, run this:
```bash ```bash
deno run --allow-net https://deno.land/x/harmony/examples/ping.ts deno run --allow-net https://deno.land/x/harmony/examples/ping.ts
``` ```
And input your bot's token and Intents. And input your bot's token.
Here is a small example of how to use harmony, Here is a small example of how to use harmony,

24
egg.json Normal file
View file

@ -0,0 +1,24 @@
{
"$schema": "https://x.nest.land/eggs@0.3.4/src/schema.json",
"name": "harmony",
"entry": "./mod.ts",
"description": "An easy to use Discord API Library for Deno.",
"homepage": "https://github.com/harmonyland/harmony",
"version": "v1.1.3",
"files": [
"./src/**/*",
"./deps.ts",
"./README.md",
"./LICENSE",
"./banner.png",
"./CONTRIBUTING.md",
"./CODE_OF_CONDUCT.md",
"./examples/*"
],
"checkFormat": "npx eslint src",
"checkTests": false,
"checkInstallation": false,
"check": true,
"unlisted": false,
"ignore": []
}

4
mod.ts
View file

@ -14,7 +14,8 @@ export {
CommandBuilder, CommandBuilder,
CommandCategory, CommandCategory,
CommandsManager, CommandsManager,
CategoriesManager CategoriesManager,
CommandsLoader
} from './src/models/command.ts' } from './src/models/command.ts'
export type { CommandContext, CommandOptions } from './src/models/command.ts' export type { CommandContext, CommandOptions } from './src/models/command.ts'
export { export {
@ -42,6 +43,7 @@ export { ReactionUsersManager } from './src/managers/reactionUsers.ts'
export { MessagesManager } from './src/managers/messages.ts' export { MessagesManager } from './src/managers/messages.ts'
export { RolesManager } from './src/managers/roles.ts' export { RolesManager } from './src/managers/roles.ts'
export { UsersManager } from './src/managers/users.ts' export { UsersManager } from './src/managers/users.ts'
export { InviteManager } from './src/managers/invites.ts'
export { Application } from './src/structures/application.ts' export { Application } from './src/structures/application.ts'
// export { ImageURL } from './src/structures/cdn.ts' // export { ImageURL } from './src/structures/cdn.ts'
export { Channel } from './src/structures/channel.ts' export { Channel } from './src/structures/channel.ts'

View file

@ -60,6 +60,13 @@ export class BaseManager<T, T2> {
return collection return collection
} }
async *[Symbol.asyncIterator](): AsyncIterableIterator<T2> {
const arr = (await this.array()) ?? []
const { readable, writable } = new TransformStream()
arr.forEach((el) => writable.getWriter().write(el))
yield* readable.getIterator()
}
/** Deletes everything from Cache */ /** Deletes everything from Cache */
flush(): any { flush(): any {
return this.client.cache.deleteCache(this.cacheName) return this.client.cache.deleteCache(this.cacheName)

View file

@ -39,4 +39,11 @@ export class BaseChildManager<T, T2> {
} }
return collection return collection
} }
async *[Symbol.asyncIterator](): AsyncIterableIterator<T2> {
const arr = (await this.array()) ?? []
const { readable, writable } = new TransformStream()
arr.forEach((el: unknown) => writable.getWriter().write(el))
yield* readable.getIterator()
}
} }

View file

@ -66,8 +66,7 @@ export class GuildChannelsManager extends BaseChildManager<
async create(options: CreateChannelOptions): Promise<GuildChannels> { async create(options: CreateChannelOptions): Promise<GuildChannels> {
if (options.name === undefined) if (options.name === undefined)
throw new Error('name is required for GuildChannelsManager#create') throw new Error('name is required for GuildChannelsManager#create')
const res = ((await this.client.rest.post(GUILD_CHANNELS(this.guild.id)), const res = ((await this.client.rest.post(GUILD_CHANNELS(this.guild.id), {
{
name: options.name, name: options.name,
type: options.type, type: options.type,
topic: options.topic, topic: options.topic,
@ -83,7 +82,7 @@ export class GuildChannelsManager extends BaseChildManager<
? options.parent.id ? options.parent.id
: options.parent, : options.parent,
nsfw: options.nsfw nsfw: options.nsfw
}) as unknown) as GuildChannelPayload })) as unknown) as GuildChannelPayload
await this.set(res.id, res) await this.set(res.id, res)
const channel = await this.get(res.id) const channel = await this.get(res.id)

View file

@ -147,6 +147,7 @@ export class GuildManager extends BaseManager<GuildPayload, Guild> {
/** Sets a value to Cache */ /** Sets a value to Cache */
async set(key: string, value: GuildPayload): Promise<any> { async set(key: string, value: GuildPayload): Promise<any> {
value = { ...value }
if ('roles' in value) value.roles = [] if ('roles' in value) value.roles = []
if ('emojis' in value) value.emojis = [] if ('emojis' in value) value.emojis = []
if ('members' in value) value.members = [] if ('members' in value) value.members = []

View file

@ -37,6 +37,7 @@ export interface DiscordAPIErrorPayload {
code?: number code?: number
message?: string message?: string
errors: object errors: object
requestData: { [key: string]: any }
} }
export class DiscordAPIError extends Error { export class DiscordAPIError extends Error {
@ -319,7 +320,9 @@ export class RESTManager {
} }
} }
const form = new FormData() const form = new FormData()
files.forEach((file, index) => form.append(`file${index + 1}`, file.blob, file.name)) files.forEach((file, index) =>
form.append(`file${index + 1}`, file.blob, file.name)
)
const json = JSON.stringify(body) const json = JSON.stringify(body)
form.append('payload_json', json) form.append('payload_json', json)
if (body === undefined) body = {} if (body === undefined) body = {}
@ -465,7 +468,8 @@ export class RESTManager {
).map((entry) => { ).map((entry) => {
return [entry[0], entry[1]._errors ?? []] return [entry[0], entry[1]._errors ?? []]
}) })
) ),
requestData: data
} }
// if (typeof error.errors === 'object') { // if (typeof error.errors === 'object') {

View file

@ -3,11 +3,13 @@ import { ImageFormats, ImageSize } from '../types/cdn.ts'
/** Function to get Image URL from a resource on Discord CDN */ /** Function to get Image URL from a resource on Discord CDN */
export const ImageURL = ( export const ImageURL = (
url: string, url: string,
format: ImageFormats | undefined = 'png', format: ImageFormats = 'png',
size: ImageSize | undefined = 128 size: ImageSize = 128
): string => { ): string => {
size = size === undefined ? 128 : size
if (url.includes('a_')) { if (url.includes('a_')) {
return `${url}.${format === undefined ? 'gif' : format}?size=${size}` return `${url}.${format === 'dynamic' ? 'gif' : format}?size=${size}`
} else return `${url}.${format === 'gif' ? 'png' : format}?size=${size}` } else
return `${url}.${
format === 'gif' || format === 'dynamic' ? 'png' : format
}?size=${size}`
} }

View file

@ -1,8 +1,10 @@
import { Client } from '../models/client.ts' import { Client } from '../models/client.ts'
import { ImageSize } from '../types/cdn.ts'
import { EmojiPayload } from '../types/emoji.ts' import { EmojiPayload } from '../types/emoji.ts'
import { EMOJI } from '../types/endpoint.ts' import { CUSTOM_EMOJI, EMOJI } from '../types/endpoint.ts'
import { Snowflake } from '../utils/snowflake.ts' import { Snowflake } from '../utils/snowflake.ts'
import { Base } from './base.ts' import { Base } from './base.ts'
import { ImageURL } from './cdn.ts'
import { Guild } from './guild.ts' import { Guild } from './guild.ts'
import { Role } from './role.ts' import { Role } from './role.ts'
import { User } from './user.ts' import { User } from './user.ts'
@ -54,6 +56,18 @@ export class Emoji extends Base {
this.available = data.available this.available = data.available
} }
/**
* Gets emoji image URL
*/
emojiImageURL(
format: 'png' | 'gif' | 'dynamic' = 'png',
size: ImageSize = 512
): string | undefined {
return this.id != null
? `${ImageURL(CUSTOM_EMOJI(this.id), format, size)}`
: undefined
}
/** Modify the given emoji. Requires the MANAGE_EMOJIS permission. Returns the updated emoji object on success. Fires a Guild Emojis Update Gateway event. */ /** Modify the given emoji. Requires the MANAGE_EMOJIS permission. Returns the updated emoji object on success. Fires a Guild Emojis Update Gateway event. */
async edit(data: ModifyGuildEmojiParams): Promise<Emoji> { async edit(data: ModifyGuildEmojiParams): Promise<Emoji> {
if (this.id === null) throw new Error('Emoji ID is not valid.') if (this.id === null) throw new Error('Emoji ID is not valid.')

View file

@ -32,9 +32,13 @@ import { User } from './user.ts'
import { Application } from './application.ts' import { Application } from './application.ts'
import { import {
GUILD_BAN, GUILD_BAN,
GUILD_BANNER,
GUILD_BANS, GUILD_BANS,
GUILD_DISCOVERY_SPLASH,
GUILD_ICON,
GUILD_INTEGRATIONS, GUILD_INTEGRATIONS,
GUILD_PRUNE GUILD_PRUNE,
GUILD_SPLASH
} from '../types/endpoint.ts' } from '../types/endpoint.ts'
import { GuildVoiceStatesManager } from '../managers/guildVoiceStates.ts' import { GuildVoiceStatesManager } from '../managers/guildVoiceStates.ts'
import { RequestMembersOptions } from '../gateway/index.ts' import { RequestMembersOptions } from '../gateway/index.ts'
@ -42,6 +46,8 @@ import { GuildPresencesManager } from '../managers/presences.ts'
import { TemplatePayload } from '../types/template.ts' import { TemplatePayload } from '../types/template.ts'
import { Template } from './template.ts' import { Template } from './template.ts'
import { DiscordAPIError } from '../models/rest.ts' import { DiscordAPIError } from '../models/rest.ts'
import { ImageFormats, ImageSize } from '../types/cdn.ts'
import { ImageURL } from './cdn.ts'
export class GuildBan extends Base { export class GuildBan extends Base {
guild: Guild guild: Guild
@ -258,6 +264,58 @@ export class Guild extends SnowflakeBase {
} }
} }
/**
* Gets guild icon URL
*/
iconURL(
format: ImageFormats = 'png',
size: ImageSize = 512
): string | undefined {
return this.icon != null
? `${ImageURL(GUILD_ICON(this.id, this.icon), format, size)}`
: undefined
}
/**
* Gets guild splash URL
*/
splashURL(
format: ImageFormats = 'png',
size: ImageSize = 512
): string | undefined {
return this.splash != null
? `${ImageURL(GUILD_SPLASH(this.id, this.splash), format, size)}`
: undefined
}
/**
* Gets guild discover splash URL
*/
discoverSplashURL(
format: ImageFormats = 'png',
size: ImageSize = 512
): string | undefined {
return this.discoverySplash != null
? `${ImageURL(
GUILD_DISCOVERY_SPLASH(this.id, this.discoverySplash),
format,
size
)}`
: undefined
}
/**
* Gets guild banner URL
*/
bannerURL(
format: ImageFormats = 'png',
size: ImageSize = 512
): string | undefined {
return this.banner != null
? `${ImageURL(GUILD_BANNER(this.id, this.banner), format, size)}`
: undefined
}
/** /**
* Gets Everyone role of the Guild * Gets Everyone role of the Guild
*/ */

View file

@ -215,6 +215,30 @@ client.on('messageCreate', async (msg: Message) => {
.map((e) => `${e[0]}: ${e[1] === true ? '`✅`' : '`❌`'}`) .map((e) => `${e[0]}: ${e[1] === true ? '`✅`' : '`❌`'}`)
.join('\n') .join('\n')
) )
msg.channel.send(`Your permissions:\n${permissions.toArray().join('\n')}`)
} else if (msg.content === '!addAllRoles') {
const roles = await msg.guild?.roles.array()
if (roles !== undefined) {
roles.forEach(async (role) => {
await msg.member?.roles.add(role)
console.log(role)
})
}
} else if (msg.content === '!createAndAddRole') {
if (msg.guild !== undefined) {
const role = await msg.guild.roles.create({
name: 'asdf',
permissions: 0
})
await msg.member?.roles.add(role)
}
} else if (msg.content === '!roles') {
let buf = 'Roles:'
if (msg.member === undefined) return
for await (const role of msg.member.roles) {
buf += `\n${role.name}`
}
msg.reply(buf)
} }
}) })

View file

@ -1,2 +1,2 @@
export type ImageSize = 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 export type ImageSize = 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048
export type ImageFormats = 'jpg' | 'jpeg' | 'png' | 'webp' | 'gif' export type ImageFormats = 'jpg' | 'jpeg' | 'png' | 'webp' | 'gif' | 'dynamic'

View file

@ -14,7 +14,10 @@ export class BitField {
#flags: { [name: string]: number | bigint } = {} #flags: { [name: string]: number | bigint } = {}
bitfield: bigint bitfield: bigint
constructor(flags: { [name: string]: number | bigint }, bits: any) { constructor(
flags: { [name: string]: number | bigint },
bits: BitFieldResolvable
) {
this.#flags = flags this.#flags = flags
this.bitfield = BitField.resolve(this.#flags, bits) this.bitfield = BitField.resolve(this.#flags, bits)
} }
@ -104,11 +107,11 @@ export class BitField {
if (bit instanceof BitField) return this.resolve(flags, bit.bitfield) if (bit instanceof BitField) return this.resolve(flags, bit.bitfield)
if (Array.isArray(bit)) if (Array.isArray(bit))
return (bit.map as any)((p: any) => this.resolve(flags, p)).reduce( return (bit.map as any)((p: any) => this.resolve(flags, p)).reduce(
(prev: any, p: any) => prev | p, (prev: bigint, p: bigint) => prev | p,
0 0n
) )
if (typeof bit === 'string' && typeof flags[bit] !== 'undefined') if (typeof bit === 'string' && typeof flags[bit] !== 'undefined')
return flags[bit] return BigInt(flags[bit])
const error = new RangeError('BITFIELD_INVALID') const error = new RangeError('BITFIELD_INVALID')
throw error throw error
} }