Has some errors but since we didn't committed so long

Co-Authored-By: Aki <71239005+AkiaCode@users.noreply.github.com>
Co-Authored-By: Lee Hyun <ink0416@naver.com>
Co-Authored-By: khk4912 <30457148+khk4912@users.noreply.github.com>
Co-Authored-By: Choi Minseo <minseo0388@outlook.com>
Co-Authored-By: Y <8479056+yky4589@users.noreply.github.com>
This commit is contained in:
Helloyunho 2020-10-29 23:43:27 +09:00
parent 1d067a957c
commit e899738b55
27 changed files with 602 additions and 206 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

BIN
src/.DS_Store vendored Normal file

Binary file not shown.

View file

@ -44,4 +44,5 @@ const resetCaches = (): void => {
caches = {}
}
export default { get, set, del, deleteCache, resetCaches }
export { get, set, del, deleteCache, resetCaches }

View file

@ -130,10 +130,7 @@ class Gateway {
this.client.user = new User(this.client, d.user)
this.sessionID = d.session_id
d.guilds.forEach((guild: GuildPayload) => {
Guild.autoInit(this.client, {
endpoint: 'guild',
restURLfuncArgs: [guild.id]
})
cache.set('guild', guild.id, new Guild(this.client, guild))
})
this.client.emit('ready')
break
@ -171,43 +168,63 @@ class Gateway {
case GatewayEvents.Channel_Update: {
const oldChannel: Channel = cache.get('channel', d.id)
if (oldChannel.type !== d.type) {
let channel: Channel = oldChannel
switch (d.type) {
case ChannelTypes.DM:
channel = new DMChannel(this.client, d)
break
case ChannelTypes.GROUP_DM:
channel = new GroupDMChannel(this.client, d)
break
case ChannelTypes.GUILD_TEXT:
channel = new GuildTextChannel(this.client, d)
break
case ChannelTypes.GUILD_VOICE:
channel = new VoiceChannel(this.client, d)
break
case ChannelTypes.GUILD_CATEGORY:
channel = new CategoryChannel(this.client, d)
break
case ChannelTypes.GUILD_NEWS:
channel = new NewsChannel(this.client, d)
break
default:
break
if (oldChannel !== undefined) {
if (oldChannel.type !== d.type) {
let channel: Channel = oldChannel
switch (d.type) {
case ChannelTypes.DM:
channel = new DMChannel(this.client, d)
break
case ChannelTypes.GROUP_DM:
channel = new GroupDMChannel(this.client, d)
break
case ChannelTypes.GUILD_TEXT:
channel = new GuildTextChannel(this.client, d)
break
case ChannelTypes.GUILD_VOICE:
channel = new VoiceChannel(this.client, d)
break
case ChannelTypes.GUILD_CATEGORY:
channel = new CategoryChannel(this.client, d)
break
case ChannelTypes.GUILD_NEWS:
channel = new NewsChannel(this.client, d)
break
default:
break
}
cache.set('channel', channel.id, channel)
this.client.emit('channelUpdate', oldChannel, channel)
} else {
const before = oldChannel.refreshFromData(d)
this.client.emit('channelUpdate', before, oldChannel)
}
cache.set('channel', channel.id, channel)
this.client.emit('channelUpdate', oldChannel, channel)
} else {
const before = oldChannel.refreshFromData(d)
this.client.emit('channelUpdate', before, oldChannel)
}
break
}
case GatewayEvents.Channel_Delete: {
const channel: Channel = cache.get('channel', d.id)
cache.del('channel', d.id)
this.client.emit('channelDelete', channel)
if (channel !== undefined) {
cache.del('channel', d.id)
this.client.emit('channelDelete', channel)
}
break
}
case GatewayEvents.Channel_Pins_Update: {
const channel: Channel = cache.get('channel', d.channel_id)
if (channel !== undefined && d.last_pin_timestamp !== null) {
channel.refreshFromData({
last_pin_timestamp: d.last_pin_timestamp
})
this.client.emit('channelPinsUpdate', channel)
}
break
}
case GatewayEvents.Guild_Create: {
const guild: Guild = cache.get('guild', d.id)
if (guild !== undefined) {
guild.refreshFromData(guild)
}
break
}
default:

View file

@ -1,10 +1,9 @@
import { Client } from '../models/client.ts'
import * as cache from '../models/cache.ts'
import endpoints from '../types/endpoint.ts'
interface IInit {
useCache?: boolean
endpoint: string
endpoint: (...restURLfuncArgs: string[]) => string
restURLfuncArgs: string[]
}
@ -31,24 +30,15 @@ export class Base {
return cached
}
}
this.restFunc = endpoints.find(v => v.name === endpoint)
// TODO: Make error for this
if (this.restFunc !== undefined) {
const resp = await fetch(this.restFunc(...restURLfuncArgs), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const jsonParsed = await resp.json()
cache.set(
this.cacheName ?? this.name,
cacheID,
new this(client, jsonParsed)
)
const resp = await fetch(endpoint(...restURLfuncArgs), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const jsonParsed = await resp.json()
return new this(client, jsonParsed)
}
return new this(client, jsonParsed)
}
async refreshFromAPI (
@ -56,58 +46,26 @@ export class Base {
{ endpoint, restURLfuncArgs }: IInit
): Promise<this> {
const oldOne = Object.assign(Object.create(this), this)
const restFunc:
| ((...restURLfuncArgs: string[]) => string)
| undefined = endpoints.find(v => v.name === endpoint)
// TODO: Make error for this
if (restFunc !== undefined) {
const resp = await fetch(restFunc(...restURLfuncArgs), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const jsonParsed = await resp.json()
const result: { [k: string]: any } = {}
Object.keys(jsonParsed).forEach(key => {
result[this.convertPropertyNameToStandard(key)] = jsonParsed[key]
})
Object.assign(this, result)
}
const resp = await fetch(endpoint(...restURLfuncArgs), {
headers: {
Authorization: `Bot ${client.token}`
}
})
const jsonParsed = await resp.json()
this.readFromData(jsonParsed)
return oldOne
}
refreshFromData (data: { [k: string]: any }): this {
const oldOne = Object.assign(Object.create(this), this)
const result: { [k: string]: any } = {}
Object.keys(data).forEach(key => {
result[this.convertPropertyNameToStandard(key)] = data[key]
})
Object.assign(this, result)
this.readFromData(data)
return oldOne
}
convertPropertyNameToStandard (name: string): string {
if (name in this.propertyConverterOverride) {
return this.propertyConverterOverride[name]
}
name = name.replaceAll('_id', 'ID')
name = name
.split('_')
.map((value, index) => {
if (index !== 0) {
value = value[0].toUpperCase() + value.slice(1)
}
return value
})
.join('')
return name
}
readFromData (data: { [k: string]: any }): void {}
// toJSON() {}
}
// 오류를 해결하기 위해 저는 2개로 접속하겠습니다. VS2019

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { ChannelPayload, ChannelTypes } from '../types/channelTypes.ts'
import { Base } from './base.ts'
@ -14,5 +15,12 @@ export class Channel extends Base {
super(client, data)
this.type = data.type
this.id = data.id
cache.set('channel', this.id, this)
}
readFromData (data: ChannelPayload): void {
super.readFromData(data)
this.type = data.type ?? this.type
this.id = data.id ?? this.id
}
}

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { DMChannelPayload } from '../types/channelTypes.ts'
import { UserPayload } from '../types/userTypes.ts'
@ -9,5 +10,11 @@ export class DMChannel extends TextChannel {
constructor (client: Client, data: DMChannelPayload) {
super(client, data)
this.recipients = data.recipients
cache.set('dmchannel', this.id, this)
}
readFromData (data: DMChannelPayload): void {
super.readFromData(data)
this.recipients = data.recipients ?? this.recipients
}
}

View file

@ -1,4 +1,3 @@
import { Client } from '../models/client.ts'
import {
EmbedAuthor,
EmbedField,
@ -25,21 +24,124 @@ export class Embed {
provider?: EmbedProvider
author?: EmbedAuthor
fields?: EmbedField[]
constructor (client: Client, data?: EmbedPayload) {
if (data !== undefined) {
this.title = data.title
this.type = data.type
this.description = data.description
this.url = data.url
this.timestamp = data.timestamp
this.color = data.color
this.footer = data.footer
this.image = data.image
this.thumbnail = data.thumbnail
this.video = data.video
this.provider = data.provider
this.author = data.author
this.fields = data.fields
constructor (data?: EmbedPayload) {
this.title = data?.title
this.type = data?.type
this.description = data?.description
this.url = data?.url
this.timestamp = data?.timestamp
this.color = data?.color
this.footer = data?.footer
this.image = data?.image
this.thumbnail = data?.thumbnail
this.video = data?.video
this.provider = data?.provider
this.author = data?.author
this.fields = data?.fields
}
// khk4912
toJSON (): EmbedPayload {
return {
title: this.title,
type: this.type,
description: this.description,
url: this.url,
timestamp: this.timestamp,
color: this.color,
footer: this.footer,
image: this.image,
thumbnail: this.thumbnail,
video: this.video,
provider: this.provider,
author: this.author,
fields: this.fields
}
}
setTitle (title: string): Embed {
this.title = title
return this
}
setDescription (description: string): Embed {
this.description = description
return this
}
setType (type: EmbedTypes): Embed {
this.type = type
return this
}
setURL (url: string): Embed {
this.url = url
return this
}
setTimestamp (timestamp: string): Embed {
this.timestamp = timestamp
return this
}
setColor (hex: number): Embed {
this.color = hex
return this
}
setFooter (footer: EmbedFooter): Embed {
this.footer = footer
return this
}
setImage (image: EmbedImage): Embed {
this.image = image
return this
}
setThumbnail (thumbnail: EmbedThumbnail): Embed {
this.thumbnail = thumbnail
return this
}
setVideo (video: EmbedVideo): Embed {
this.video = video
return this
}
setProvider (provider: EmbedProvider): Embed {
this.provider = provider
return this
}
setAuthor (author: EmbedAuthor): Embed {
this.author = author
return this
}
setFields (fields: EmbedField[]): Embed {
this.fields = fields
return this
}
addField (name: string, value: string, inline?: boolean): Embed {
if (this.fields === undefined) {
this.fields = [
{
name: name,
value: value,
inline: inline
}
]
} else {
this.fields.push({
name: name,
value: value,
inline: inline
})
}
return this
}
}

View file

@ -1,22 +1,14 @@
import { Client } from '../models/client.ts'
import { EmojiPayload } from '../types/emojiTypes.ts'
import { USER } from '../types/endpoint.ts'
import { Base } from './base.ts'
import { User } from './user.ts'
export class Emoji extends Base {
// eslint-disable-next-line @typescript-eslint/prefer-readonly
private data: EmojiPayload
client: Client
id: string
name: string
roles?: []
get user (): User | undefined {
if (this.data.user !== undefined) {
return new User(this.client, this.data.user)
}
}
roles?: string[]
user?: User
requireColons?: boolean
managed?: boolean
animated?: boolean
@ -30,14 +22,35 @@ export class Emoji extends Base {
constructor (client: Client, data: EmojiPayload) {
super(client, data)
this.data = data
this.client = client
this.id = data.id
this.name = data.name
this.roles = data.roles
if (data.user !== undefined) {
User.autoInit(this.client, {
endpoint: USER,
restURLfuncArgs: [data.user.id]
}).then(user => (this.user = user))
}
this.requireColons = data.require_colons
this.managed = data.managed
this.animated = data.animated
this.available = data.available
}
readFromData (data: EmojiPayload): void {
super.readFromData(data)
this.id = data.id ?? this.id
this.name = data.name ?? this.name
this.roles = data.roles ?? this.roles
this.requireColons = data.require_colons ?? this.requireColons
this.managed = data.managed ?? this.managed
this.animated = data.animated ?? this.animated
this.available = data.available ?? this.available
if (data.user !== undefined && data.user.id !== this.user?.id) {
User.autoInit(this.client, {
endpoint: USER,
restURLfuncArgs: [data.user.id]
}).then(user => (this.user = user))
}
}
}

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { GroupDMChannelPayload } from '../types/channelTypes.ts'
import { Channel } from './channel.ts'
@ -13,5 +14,13 @@ export class GroupDMChannel extends Channel {
this.name = data.name
this.icon = data.icon
this.ownerID = data.owner_id
cache.set('groupchannel', this.id, this)
}
readFromData (data: GroupDMChannelPayload): void {
super.readFromData(data)
this.name = data.name ?? this.name
this.icon = data.icon ?? this.icon
this.ownerID = data.owner_id ?? this.ownerID
}
}

View file

@ -7,32 +7,33 @@ import { Emoji } from './emoji.ts'
import { Member } from './member.ts'
import { Role } from './role.ts'
import { VoiceState } from './voiceState.ts'
import cache from '../models/cache.ts'
export class Guild extends Base {
id: string
name: string
name?: string
icon?: string
iconHash?: string
splash?: string
discoverySplash?: string
owner?: boolean
ownerID: string
ownerID?: string
permissions?: string
region: string
region?: string
afkChannelID?: string
afkTimeout: number
afkTimeout?: number
widgetEnabled?: boolean
widgetChannelID?: string
verificationLevel: string
defaultMessageNotifications: string
explicitContentFilter: string
roles: Role[]
emojis: Emoji[]
features: GuildFeatures[]
mfaLevel: string
verificationLevel?: string
defaultMessageNotifications?: string
explicitContentFilter?: string
roles?: Role[]
emojis?: Emoji[]
features?: GuildFeatures[]
mfaLevel?: string
applicationID?: string
systemChannelID?: string
systemChannelFlags: string
systemChannelFlags?: string
rulesChannelID?: string
joinedAt?: string
large?: boolean
@ -47,9 +48,9 @@ export class Guild extends Base {
vanityURLCode?: string
description?: string
banner?: string
premiumTier: number
premiumTier?: number
premiumSubscriptionCount?: number
preferredLocale: string
preferredLocale?: string
publicUpdatesChannelID?: string
maxVideoChannelUsers?: number
approximateNumberCount?: number
@ -58,48 +59,144 @@ export class Guild extends Base {
constructor (client: Client, data: GuildPayload) {
super(client, data)
this.id = data.id
this.name = data.name
this.icon = data.icon
this.iconHash = data.icon_hash
this.splash = data.splash
this.discoverySplash = data.discovery_splash
this.owner = data.owner
this.ownerID = data.owner_id
this.permissions = data.permissions
this.region = data.region
this.afkTimeout = data.afk_timeout
this.afkChannelID = data.afk_channel_id
this.widgetEnabled = data.widget_enabled
this.widgetChannelID = data.widget_channel_id
this.verificationLevel = data.verification_level
this.defaultMessageNotifications = data.default_message_notifications
this.explicitContentFilter = data.explicit_content_filter
this.roles = data.roles.map(v => new Role(client, v))
this.emojis = data.emojis.map(v => new Emoji(client, v))
this.features = data.features
this.mfaLevel = data.mfa_level
this.systemChannelID = data.system_channel_id
this.systemChannelFlags = data.system_channel_flags
this.rulesChannelID = data.rules_channel_id
this.joinedAt = data.joined_at
this.large = data.large
this.unavailable = data.unavailable
this.memberCount = data.member_count
this.voiceStates = data.voice_states?.map(v => new VoiceState(client, v))
this.members = data.members?.map(v => new Member(client, v))
this.channels = data.channels?.map(v => new Channel(client, v))
this.presences = data.presences
this.maxPresences = data.max_presences
this.maxMembers = data.max_members
this.vanityURLCode = data.vanity_url_code
this.description = data.description
this.banner = data.banner
this.premiumTier = data.premium_tier
this.premiumSubscriptionCount = data.premium_subscription_count
this.preferredLocale = data.preferred_locale
this.publicUpdatesChannelID = data.public_updates_channel_id
this.maxVideoChannelUsers = data.max_video_channel_users
this.approximateNumberCount = data.approximate_number_count
this.approximatePresenceCount = data.approximate_presence_count
if (!this.unavailable) {
this.name = data.name
this.icon = data.icon
this.iconHash = data.icon_hash
this.splash = data.splash
this.discoverySplash = data.discovery_splash
this.owner = data.owner
this.ownerID = data.owner_id
this.permissions = data.permissions
this.region = data.region
this.afkTimeout = data.afk_timeout
this.afkChannelID = data.afk_channel_id
this.widgetEnabled = data.widget_enabled
this.widgetChannelID = data.widget_channel_id
this.verificationLevel = data.verification_level
this.defaultMessageNotifications = data.default_message_notifications
this.explicitContentFilter = data.explicit_content_filter
this.roles = data.roles.map(
v => cache.get('role', v.id) ?? new Role(client, v)
)
this.emojis = data.emojis.map(
v => cache.get('emoji', v.id) ?? new Emoji(client, v)
)
this.features = data.features
this.mfaLevel = data.mfa_level
this.systemChannelID = data.system_channel_id
this.systemChannelFlags = data.system_channel_flags
this.rulesChannelID = data.rules_channel_id
this.joinedAt = data.joined_at
this.large = data.large
this.memberCount = data.member_count
this.voiceStates = data.voice_states?.map(
v =>
cache.get('voiceState', `${v.guild_id}:${v.user_id}`) ??
new VoiceState(client, v)
)
this.members = data.members?.map(
v =>
cache.get('member', `${this.id}:${v.user.id}`) ??
new Member(client, v)
)
this.channels = data.channels?.map(
v => cache.get('channel', v.id) ?? new Channel(client, v)
)
this.presences = data.presences
this.maxPresences = data.max_presences
this.maxMembers = data.max_members
this.vanityURLCode = data.vanity_url_code
this.description = data.description
this.banner = data.banner
this.premiumTier = data.premium_tier
this.premiumSubscriptionCount = data.premium_subscription_count
this.preferredLocale = data.preferred_locale
this.publicUpdatesChannelID = data.public_updates_channel_id
this.maxVideoChannelUsers = data.max_video_channel_users
this.approximateNumberCount = data.approximate_number_count
this.approximatePresenceCount = data.approximate_presence_count
}
cache.set('guild', this.id, this)
}
readFromData (data: GuildPayload): void {
super.readFromData(data)
this.id = data.id ?? this.id
this.unavailable = data.unavailable ?? this.unavailable
if (!this.unavailable) {
this.name = data.name ?? this.name
this.icon = data.icon ?? this.icon
this.iconHash = data.icon_hash ?? this.iconHash
this.splash = data.splash ?? this.splash
this.discoverySplash = data.discovery_splash ?? this.discoverySplash
this.owner = data.owner ?? this.owner
this.ownerID = data.owner_id ?? this.ownerID
this.permissions = data.permissions ?? this.permissions
this.region = data.region ?? this.region
this.afkTimeout = data.afk_timeout ?? this.afkTimeout
this.afkChannelID = data.afk_channel_id ?? this.afkChannelID
this.widgetEnabled = data.widget_enabled ?? this.widgetEnabled
this.widgetChannelID = data.widget_channel_id ?? this.widgetChannelID
this.verificationLevel = data.verification_level ?? this.verificationLevel
this.defaultMessageNotifications =
data.default_message_notifications ?? this.defaultMessageNotifications
this.explicitContentFilter =
data.explicit_content_filter ?? this.explicitContentFilter
this.roles =
data.roles.map(
v => cache.get('role', v.id) ?? new Role(this.client, v)
) ?? this.roles
this.emojis =
data.emojis.map(
v => cache.get('emoji', v.id) ?? new Emoji(this.client, v)
) ?? this.emojis
this.features = data.features ?? this.features
this.mfaLevel = data.mfa_level ?? this.mfaLevel
this.systemChannelID = data.system_channel_id ?? this.systemChannelID
this.systemChannelFlags =
data.system_channel_flags ?? this.systemChannelFlags
this.rulesChannelID = data.rules_channel_id ?? this.rulesChannelID
this.joinedAt = data.joined_at ?? this.joinedAt
this.large = data.large ?? this.large
this.memberCount = data.member_count ?? this.memberCount
this.voiceStates =
data.voice_states?.map(
v =>
cache.get('voiceState', `${v.guild_id}:${v.user_id}`) ??
new VoiceState(this.client, v)
) ?? this.voiceStates
this.members =
data.members?.map(
v =>
cache.get('member', `${this.id}:${v.user.id}`) ??
new Member(this.client, v)
) ?? this.members
this.channels =
data.channels?.map(
v => cache.get('channel', v.id) ?? new Channel(this.client, v)
) ?? this.members
this.presences = data.presences ?? this.presences
this.maxPresences = data.max_presences ?? this.maxPresences
this.maxMembers = data.max_members ?? this.maxMembers
this.vanityURLCode = data.vanity_url_code ?? this.vanityURLCode
this.description = data.description ?? this.description
this.banner = data.banner ?? this.banner
this.premiumTier = data.premium_tier ?? this.premiumTier
this.premiumSubscriptionCount =
data.premium_subscription_count ?? this.premiumSubscriptionCount
this.preferredLocale = data.preferred_locale ?? this.preferredLocale
this.publicUpdatesChannelID =
data.public_updates_channel_id ?? this.publicUpdatesChannelID
this.maxVideoChannelUsers =
data.max_video_channel_users ?? this.maxVideoChannelUsers
this.approximateNumberCount =
data.approximate_number_count ?? this.approximateNumberCount
this.approximatePresenceCount =
data.approximate_presence_count ?? this.approximatePresenceCount
}
}
}

View file

@ -4,6 +4,7 @@ import {
GuildChannelCategoryPayload,
Overwrite
} from '../types/channelTypes.ts'
import cache from '../models/cache.ts'
export class CategoryChannel extends Channel {
guildID: string
@ -21,5 +22,17 @@ export class CategoryChannel extends Channel {
this.permissionOverwrites = data.permission_overwrites
this.nsfw = data.nsfw
this.parentID = data.parent_id
cache.set('guildcategorychannel', this.id, this)
}
readFromData (data: GuildChannelCategoryPayload): void {
super.readFromData(data)
this.guildID = data.guild_id ?? this.guildID
this.name = data.name ?? this.name
this.position = data.position ?? this.position
this.permissionOverwrites =
data.permission_overwrites ?? this.permissionOverwrites
this.nsfw = data.nsfw ?? this.nsfw
this.parentID = data.parent_id ?? this.parentID
}
}

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { GuildChannelPayload, Overwrite } from '../types/channelTypes.ts'
import { Channel } from './channel.ts'
@ -18,5 +19,17 @@ export class GuildChannel extends Channel {
this.permissionOverwrites = data.permission_overwrites
this.nsfw = data.nsfw
this.parentID = data.parent_id
cache.set('guildchannel', this.id, this)
}
readFromData (data: GuildChannelPayload): void {
super.readFromData(data)
this.guildID = data.guild_id ?? this.guildID
this.name = data.name ?? this.name
this.position = data.position ?? this.position
this.permissionOverwrites =
data.permission_overwrites ?? this.permissionOverwrites
this.nsfw = data.nsfw ?? this.nsfw
this.parentID = data.parent_id ?? this.parentID
}
}

View file

@ -1,6 +1,7 @@
import { Client } from '../models/client.ts'
import { GuildChannel } from './guildChannel.ts'
import { GuildTextChannelPayload } from '../types/channelTypes.ts'
import cache from '../models/cache.ts'
export class GuildTextChannel extends GuildChannel {
rateLimit: number
@ -14,5 +15,12 @@ export class GuildTextChannel extends GuildChannel {
super(client, data)
this.topic = data.topic
this.rateLimit = data.rate_limit_per_user
cache.set('guildtextchannel', this.id, this)
}
readFromData (data: GuildTextChannelPayload): void {
super.readFromData(data)
this.topic = data.topic ?? this.topic
this.rateLimit = data.rate_limit_per_user ?? this.rateLimit
}
}

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { GuildVoiceChannelPayload, Overwrite } from '../types/channelTypes.ts'
import { Channel } from './channel.ts'
@ -22,5 +23,19 @@ export class VoiceChannel extends Channel {
this.permissionOverwrites = data.permission_overwrites
this.nsfw = data.nsfw
this.parentID = data.parent_id
cache.set('guildvoicechannel', this.id, this)
}
readFromData (data: GuildVoiceChannelPayload): void {
super.readFromData(data)
this.bitrate = data.bitrate ?? this.bitrate
this.userLimit = data.user_limit ?? this.userLimit
this.guildID = data.guild_id ?? this.guildID
this.name = data.name ?? this.name
this.position = data.position ?? this.position
this.permissionOverwrites =
data.permission_overwrites ?? this.permissionOverwrites
this.nsfw = data.nsfw ?? this.nsfw
this.parentID = data.parent_id ?? this.parentID
}
}

View file

@ -30,4 +30,18 @@ export class Invite extends Base {
this.approximateMemberCount = data.approximate_member_count
this.approximatePresenceCount = data.approximate_presence_count
}
readFromData (data: InvitePayload): void {
super.readFromData(data)
this.code = data.code ?? this.code
this.guild = data.guild ?? this.guild
this.channel = data.channel ?? this.channel
this.inviter = data.inviter ?? this.inviter
this.targetUser = data.target_user ?? this.targetUser
this.targetUserType = data.target_user_type ?? this.targetUserType
this.approximateMemberCount =
data.approximate_member_count ?? this.approximateMemberCount
this.approximatePresenceCount =
data.approximate_presence_count ?? this.approximatePresenceCount
}
}

View file

@ -1,11 +1,11 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { MemberPayload } from '../types/guildTypes.ts'
import { Role } from './role.ts'
import { User } from './user.ts'
export class Member extends User {
nick?: string
roles: Role[]
roles: string[]
joinedAt: string
premiumSince?: string
deaf: boolean
@ -14,10 +14,21 @@ export class Member extends User {
constructor (client: Client, data: MemberPayload) {
super(client, data.user)
this.nick = data.nick
this.roles = data.roles.map(v => new Role(client, v))
this.roles = data.roles
this.joinedAt = data.joined_at
this.premiumSince = data.premium_since
this.deaf = data.deaf
this.mute = data.mute
cache.set('member', this.id, this)
}
readFromData (data: MemberPayload): void {
super.readFromData(data)
this.nick = data.nick ?? this.nick
this.roles = data.roles ?? this.roles
this.joinedAt = data.joined_at ?? this.joinedAt
this.premiumSince = data.premium_since ?? this.premiumSince
this.deaf = data.deaf ?? this.deaf
this.mute = data.mute ?? this.mute
}
}

View file

@ -13,8 +13,8 @@ import { Client } from '../models/client.ts'
import { User } from './user.ts'
import { Member } from './member.ts'
import { Embed } from './embed.ts'
import { Role } from './role.ts'
import { CHANNEL_MESSAGE } from '../types/endpoint.ts'
import cache from '../models/cache.ts'
export class Message extends Base {
// eslint-disable-next-line @typescript-eslint/prefer-readonly
@ -23,27 +23,21 @@ export class Message extends Base {
channelID: string
guildID?: string
author: User
member?: Member
content: string
timestamp: string
editedTimestamp?: string
tts: boolean
get member (): Member | undefined {
if (this.data.member !== undefined) {
return new Member(this.client, this.data.member)
}
}
mentionEveryone: boolean
mentions: Member[]
mentionRoles: Role[]
mentions: User[]
mentionRoles: string[]
mentionChannels?: ChannelMention[]
attachments: Attachment[]
embeds: Embed[]
reactions?: Reaction[]
nonce?: string | number
pinned: boolean
webhookId?: string
webhookID?: string
type: number
activity?: MessageActivity
application?: MessageApplication
@ -56,27 +50,65 @@ export class Message extends Base {
this.id = data.id
this.channelID = data.channel_id
this.guildID = data.guild_id
this.author = new User(client, data.author)
this.author =
cache.get('user', data.author.id) ?? new User(this.client, data.author)
this.content = data.content
this.timestamp = data.timestamp
this.editedTimestamp = data.edited_timestamp
this.tts = data.tts
this.mentionEveryone = data.mention_everyone
this.mentions = data.mentions.map(v => new Member(client, v))
this.mentionRoles = data.mention_roles.map(v => new Role(client, v))
this.mentions = data.mentions.map(
v => cache.get('user', v.id) ?? new User(client, v)
)
this.mentionRoles = data.mention_roles
this.mentionChannels = data.mention_channels
this.attachments = data.attachments
this.embeds = data.embeds.map(v => new Embed(client, v))
this.embeds = data.embeds.map(v => new Embed(v))
this.reactions = data.reactions
this.nonce = data.nonce
this.pinned = data.pinned
this.webhookId = data.webhook_id
this.webhookID = data.webhook_id
this.type = data.type
this.activity = data.activity
this.application = data.application
this.messageReference = data.message_reference
this.flags = data.flags
cache.set('message', this.id, this)
}
readFromData (data: MessagePayload): void {
super.readFromData(data)
this.channelID = data.channel_id ?? this.channelID
this.guildID = data.guild_id ?? this.guildID
this.author =
cache.get('user', data.author.id) ??
new User(this.client, data.author) ??
this.author
this.content = data.content ?? this.content
this.timestamp = data.timestamp ?? this.timestamp
this.editedTimestamp = data.edited_timestamp ?? this.editedTimestamp
this.tts = data.tts ?? this.tts
this.mentionEveryone = data.mention_everyone ?? this.mentionEveryone
this.mentions =
data.mentions.map(
v => cache.get('user', v.id) ?? new User(this.client, v)
) ?? this.mentions
this.mentionRoles = data.mention_roles ?? this.mentionRoles
this.mentionChannels = data.mention_channels ?? this.mentionChannels
this.attachments = data.attachments ?? this.attachments
this.embeds = data.embeds.map(v => new Embed(v)) ?? this.embeds
this.reactions = data.reactions ?? this.reactions
this.nonce = data.nonce ?? this.nonce
this.pinned = data.pinned ?? this.pinned
this.webhookID = data.webhook_id ?? this.webhookID
this.type = data.type ?? this.type
this.activity = data.activity ?? this.activity
this.application = data.application ?? this.application
this.messageReference = data.message_reference ?? this.messageReference
this.flags = data.flags ?? this.flags
}
// TODO: We have to seperate fetch()
async editMessage (text?: string, option?: MessageOption): Promise<Message> {
if (text !== undefined && option !== undefined) {
throw new Error('Either text or option is necessary.')
@ -89,7 +121,7 @@ export class Message extends Base {
method: 'PATCH',
body: JSON.stringify({
content: text,
embed: option?.embed,
embed: option?.embed.toJSON(),
file: option?.file,
tts: option?.tts,
allowed_mentions: option?.allowedMention
@ -98,4 +130,22 @@ export class Message extends Base {
return new Message(this.client, await resp.json())
}
// TODO: We have to seperate fetch()
async delete (): Promise<void> {
const resp = await fetch(CHANNEL_MESSAGE(this.channelID, this.id), {
headers: {
Authorization: `Bot ${this.client.token}`
},
method: 'DELETE'
})
// TODO: improve Error and Promise
return await new Promise((resolve, reject) => {
if (resp.status !== 204) {
reject(new Error())
}
resolve()
})
}
}

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { Base } from './base.ts'
import { RolePayload } from '../types/roleTypes.ts'
@ -26,5 +27,17 @@ export class Role extends Base {
this.permissions = data.permissions
this.managed = data.managed
this.mentionable = data.mentionable
cache.set('role', this.id, this)
}
readFromData (data: RolePayload): void {
super.readFromData(data)
this.name = data.name ?? this.name
this.color = data.color ?? this.color
this.hoist = data.hoist ?? this.hoist
this.position = data.position ?? this.position
this.permissions = data.permissions ?? this.permissions
this.managed = data.managed ?? this.managed
this.mentionable = data.mentionable ?? this.mentionable
}
}

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { MessageOption, TextChannelPayload } from '../types/channelTypes.ts'
import { CHANNEL_MESSAGE, CHANNEL_MESSAGES } from '../types/endpoint.ts'
@ -12,6 +13,13 @@ export class TextChannel extends Channel {
super(client, data)
this.lastMessageID = data.last_message_id
this.lastPinTimestamp = data.last_pin_timestamp
cache.set('textchannel', this.id, this)
}
readFromData (data: TextChannelPayload): void {
super.readFromData(data)
this.lastMessageID = data.last_message_id ?? this.lastMessageID
this.lastPinTimestamp = data.last_pin_timestamp ?? this.lastPinTimestamp
}
async send (text?: string, option?: MessageOption): Promise<Message> {

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { UserPayload } from '../types/userTypes.ts'
import { Base } from './base.ts'
@ -40,5 +41,22 @@ export class User extends Base {
this.flags = data.flags
this.premiumType = data.premium_type
this.publicFlags = data.public_flags
cache.set('user', this.id, this)
}
readFromData (data: UserPayload): void {
super.readFromData(data)
this.username = data.username ?? this.username
this.discriminator = data.discriminator ?? this.discriminator
this.avatar = data.avatar ?? this.avatar
this.bot = data.bot ?? this.bot
this.system = data.system ?? this.system
this.mfaEnabled = data.mfa_enabled ?? this.mfaEnabled
this.locale = data.locale ?? this.locale
this.verified = data.verified ?? this.verified
this.email = data.email ?? this.email
this.flags = data.flags ?? this.flags
this.premiumType = data.premium_type ?? this.premiumType
this.publicFlags = data.public_flags ?? this.publicFlags
}
}

View file

@ -1,3 +1,4 @@
import cache from '../models/cache.ts'
import { Client } from '../models/client.ts'
import { MemberPayload } from '../types/guildTypes.ts'
import { VoiceStatePayload } from '../types/voiceTypes.ts'
@ -29,5 +30,20 @@ export class VoiceState extends Base {
this.selfStream = data.self_stream
this.selfVideo = data.self_video
this.suppress = data.suppress
cache.set('voiceState', `${this.guildID}:${this.userID}`, this)
}
readFromData (data: VoiceStatePayload): void {
super.readFromData(data)
this.channelID = data.channel_id ?? this.channelID
this.sessionID = data.session_id ?? this.sessionID
this.userID = data.user_id ?? this.userID
this.deaf = data.deaf ?? this.deaf
this.mute = data.mute ?? this.mute
this.selfDeaf = data.self_deaf ?? this.selfDeaf
this.selfMute = data.self_mute ?? this.selfMute
this.selfStream = data.self_stream ?? this.selfStream
this.selfVideo = data.self_video ?? this.selfVideo
this.suppress = data.suppress ?? this.suppress
}
}

View file

@ -16,6 +16,9 @@ bot.on('channelUpdate', (before: Channel, after: Channel) => {
if (before instanceof GuildTextChannel && after instanceof GuildTextChannel) {
console.log(before.name)
console.log(after.name)
} else {
console.log(before)
console.log(after)
}
})

View file

@ -1,7 +1,6 @@
import { Embed } from '../structures/embed.ts'
import { EmojiPayload } from './emojiTypes.ts'
import { MemberPayload } from './guildTypes.ts'
import { RolePayload } from './roleTypes.ts'
import { UserPayload } from './userTypes.ts'
interface ChannelPayload {
@ -83,8 +82,8 @@ interface MessagePayload {
edited_timestamp?: string
tts: boolean
mention_everyone: boolean
mentions: MemberPayload[]
mention_roles: RolePayload[]
mentions: UserPayload[]
mention_roles: string[]
mention_channels?: ChannelMention[]
attachments: Attachment[]
embeds: EmbedPayload[]
@ -281,6 +280,9 @@ export {
Attachment,
Reaction,
MessageActivity,
MessageActivityTypes,
MessageFlags,
FollowedChannel,
MessageApplication,
MessageReference,
MessagePayload,

View file

@ -3,7 +3,7 @@ import { UserPayload } from './userTypes.ts'
export interface EmojiPayload {
id: string
name: string
roles?: []
roles?: string[]
user?: UserPayload
require_colons?: boolean
managed?: boolean

View file

@ -70,7 +70,7 @@ enum GatewayEvents {
Channel_Create = 'CHANNEL_CREATE',
Channel_Update = 'CHANNEL_UPDATE',
Channel_Delete = 'CHANNEL_DELETE',
Channel_Pins_Update = 'CHANNEL_PIN_UPDATE',
Channel_Pins_Update = 'CHANNEL_PINS_UPDATE',
Guild_Create = 'GUILD_CREATE',
Guild_Update = 'GUILD_UPDATE',
Guild_Delete = 'GUILD_DELETE',

View file

@ -56,7 +56,7 @@ interface GuildPayload {
interface MemberPayload {
user: UserPayload
nick?: string
roles: RolePayload[]
roles: string[]
joined_at: string
premium_since?: string
deaf: boolean