prettier on everything

This commit is contained in:
Skillz
2020-02-10 16:30:58 -05:00
parent 2d9a194848
commit d366582873
13 changed files with 223 additions and 229 deletions
+11 -12
View File
@@ -1,12 +1,12 @@
import Client from "../module/Client.ts"; import Client from '../module/Client.ts'
class RequestManager { class RequestManager {
client: Client; client: Client
token: string; token: string
constructor(client: Client, token: string) { constructor(client: Client, token: string) {
this.client = client; this.client = client
this.token = token; this.token = token
} }
async get(url: string, payload?: unknown) { async get(url: string, payload?: unknown) {
@@ -18,15 +18,14 @@ class RequestManager {
// let attempts = 0 // let attempts = 0
const headers = { const headers = {
Authorization: this.token, Authorization: this.token,
"User-Agent": 'User-Agent': `DiscordBot (https://github.com/skillz4killz/discordeno, 0.0.1)`
`DiscordBot (https://github.com/skillz4killz/discordeno, 0.0.1)` }
};
console.log("payload", payload); console.log('payload', payload)
const data = await fetch(url, { headers }).then(res => res.json()); const data = await fetch(url, { headers }).then(res => res.json())
return data; return data
} }
} }
export default RequestManager; export default RequestManager
+2 -3
View File
@@ -1,4 +1,3 @@
class ShardingManager extends Map { class ShardingManager extends Map {}
}
export default ShardingManager; export default ShardingManager
+3 -3
View File
@@ -1,7 +1,7 @@
import Client from "./module/Client.ts" import Client from './module/Client.ts'
import { configs } from "./configs.ts" import { configs } from './configs.ts'
const Discordeno = new Client(configs.token) const Discordeno = new Client(configs.token)
Discordeno.connect() Discordeno.connect()
export default Discordeno export default Discordeno
+32 -40
View File
@@ -1,87 +1,79 @@
import { endpoints } from "../constants/discord.ts"; import { endpoints } from '../constants/discord.ts'
import RequestManager from "../managers/RequestManager.ts"; import RequestManager from '../managers/RequestManager.ts'
import { DiscordBotGateway, DiscordPayload, import { DiscordBotGateway, DiscordPayload, DiscordHeartbeatPayload } from '../types/discord.ts'
DiscordHeartbeatPayload } from "../types/discord.ts"; import ShardingManager from '../managers/ShardingManager.ts'
import ShardingManager from "../managers/ShardingManager.ts";
import { import {
connectWebSocket, connectWebSocket,
isWebSocketCloseEvent, isWebSocketCloseEvent,
isWebSocketPingEvent, isWebSocketPingEvent,
isWebSocketPongEvent, isWebSocketPongEvent,
WebSocket WebSocket
} from "https://deno.land/std/ws/mod.ts"; } from 'https://deno.land/std/ws/mod.ts'
// import { encode } from "https://deno.land/std/strings/mod.ts" // import { encode } from "https://deno.land/std/strings/mod.ts"
// import { BufReader } from "https://deno.land/std/io/bufio.ts" // import { BufReader } from "https://deno.land/std/io/bufio.ts"
// import { TextProtoReader } from "https://deno.land/std/textproto/mod.ts" // import { TextProtoReader } from "https://deno.land/std/textproto/mod.ts"
import { keepDiscordWebsocketAlive, import { keepDiscordWebsocketAlive, updatePreviousSequenceNumber } from './websocket.ts'
updatePreviousSequenceNumber } from "./websocket.ts"; import { logGreen, logRed, logYellow, logBlue } from '../utils/logger.ts'
import { logGreen, logRed, logYellow, logBlue } from "../utils/logger.ts";
class Client { class Client {
/** The bot's token. This should never be used by end users. It is meant to be used internally to make requests to the Discord API. */ /** The bot's token. This should never be used by end users. It is meant to be used internally to make requests to the Discord API. */
token: string; token: string
/** The Rate limit manager to handle all outgoing requests to discord. Not meant to be used by users. */ /** The Rate limit manager to handle all outgoing requests to discord. Not meant to be used by users. */
RequestManager: RequestManager; RequestManager: RequestManager
/** Creates and handles all the shards necessary for the bot. */ /** Creates and handles all the shards necessary for the bot. */
ShardingManager: ShardingManager; ShardingManager: ShardingManager
constructor(token: string) { constructor(token: string) {
this.token = `Bot ${token}`; this.token = `Bot ${token}`
this.RequestManager = new RequestManager(this, this.token); this.RequestManager = new RequestManager(this, this.token)
this.ShardingManager = new ShardingManager(); this.ShardingManager = new ShardingManager()
} }
/** Begins initial handshake, creates the websocket with Discord and spawns all necessary shards. */ /** Begins initial handshake, creates the websocket with Discord and spawns all necessary shards. */
async connect() { async connect() {
const data = (await this.RequestManager.get( const data = (await this.RequestManager.get(endpoints.GATEWAY_BOT)) as DiscordBotGateway
endpoints.GATEWAY_BOT
)) as DiscordBotGateway;
// Open a WS with the url from discord. // Open a WS with the url from discord.
const sock = await connectWebSocket(data.url); const sock = await connectWebSocket(data.url)
console.log(sock); console.log(sock)
logGreen("ws connected! (type 'close' to quit)"); logGreen("ws connected! (type 'close' to quit)")
for await (const msg of sock.receive()) { for await (const msg of sock.receive()) {
if (typeof msg === "string") { if (typeof msg === 'string') {
try { try {
const json = JSON.parse(msg); const json = JSON.parse(msg)
this.handleDiscordPayload(json, sock); this.handleDiscordPayload(json, sock)
} catch { } catch {
logRed(`Invalid JSON String send by discord: ${msg}`); logRed(`Invalid JSON String send by discord: ${msg}`)
} }
logYellow("< " + msg); logYellow('< ' + msg)
} else if (isWebSocketPingEvent(msg)) { } else if (isWebSocketPingEvent(msg)) {
logBlue("< ping"); logBlue('< ping')
} else if (isWebSocketPongEvent(msg)) { } else if (isWebSocketPongEvent(msg)) {
logBlue("< pong"); logBlue('< pong')
} else if (isWebSocketCloseEvent(msg)) { } else if (isWebSocketCloseEvent(msg)) {
logRed(`closed: code=${msg.code}, reason=${msg.reason}`); logRed(`closed: code=${msg.code}, reason=${msg.reason}`)
} }
} }
// Begin spawning all necessary shards // Begin spawning all necessary shards
this.spawnShards(data.shards); this.spawnShards(data.shards)
} }
handleDiscordPayload(data: DiscordPayload, socket: WebSocket) { handleDiscordPayload(data: DiscordPayload, socket: WebSocket) {
switch (data.op) { switch (data.op) {
case 10: // Initial Heartbeat case 10: // Initial Heartbeat
keepDiscordWebsocketAlive( keepDiscordWebsocketAlive(socket, (data.d as DiscordHeartbeatPayload).heartbeat_interval, data.s)
socket, break
(data.d as DiscordHeartbeatPayload).heartbeat_interval,
data.s
);
break;
case 11: case 11:
updatePreviousSequenceNumber(data.s); updatePreviousSequenceNumber(data.s)
break; break
} }
} }
spawnShards(total: number, id = 1) { spawnShards(total: number, id = 1) {
// this.ShardingManager.spawnShard(id); // this.ShardingManager.spawnShard(id);
if (id < total) this.spawnShards(total, id + 1); if (id < total) this.spawnShards(total, id + 1)
} }
} }
export default Client; export default Client
+15 -9
View File
@@ -1,16 +1,22 @@
import { WebSocket } from "https://deno.land/std/ws/mod.ts"; import { WebSocket } from 'https://deno.land/std/ws/mod.ts'
let previousSequenceNumber: number | null = null let previousSequenceNumber: number | null = null
export const keepDiscordWebsocketAlive = (socket: WebSocket, millesecondsInterval: number, payload: number | null = null) => { export const keepDiscordWebsocketAlive = (
previousSequenceNumber = payload socket: WebSocket,
millesecondsInterval: number,
payload: number | null = null
) => {
previousSequenceNumber = payload
setInterval(() => { setInterval(() => {
socket.send(JSON.stringify({ socket.send(
op: 1, JSON.stringify({
d: previousSequenceNumber op: 1,
})) d: previousSequenceNumber
}, millesecondsInterval) })
)
}, millesecondsInterval)
} }
export const updatePreviousSequenceNumber = (sequence: number | null = null) => { export const updatePreviousSequenceNumber = (sequence: number | null = null) => {
+2 -2
View File
@@ -1,3 +1,3 @@
export const createChannel = (data: unknown) => { export const createChannel = (data: unknown) => {
console.log(data); console.log(data)
}; }
+2 -2
View File
@@ -1,3 +1,3 @@
export const createEmoji = (data: unknown) => { export const createEmoji = (data: unknown) => {
console.log(data); console.log(data)
}; }
+2 -2
View File
@@ -1,3 +1,3 @@
export const createMember = (data: unknown) => { export const createMember = (data: unknown) => {
console.log(data); console.log(data)
}; }
+2 -2
View File
@@ -1,3 +1,3 @@
export const createPresence = (data: unknown) => { export const createPresence = (data: unknown) => {
console.log(data); console.log(data)
}; }
+2 -2
View File
@@ -1,3 +1,3 @@
export const createRole = (data: unknown) => { export const createRole = (data: unknown) => {
console.log(data); console.log(data)
}; }
+2 -2
View File
@@ -1,3 +1,3 @@
export const createVoiceState = (data: unknown) => { export const createVoiceState = (data: unknown) => {
console.log(data); console.log(data)
}; }
+130 -130
View File
@@ -1,156 +1,156 @@
export interface DiscordPayload { export interface DiscordPayload {
/** OP code for the payload */ /** OP code for the payload */
op: number op: number
/** The real event data. Any JSON value basically. */ /** The real event data. Any JSON value basically. */
d: unknown d: unknown
/** The sequence number, used for resuming sessions and heartbeats. ONLY for OPCode 0 */ /** The sequence number, used for resuming sessions and heartbeats. ONLY for OPCode 0 */
s?: number s?: number
/** The event name for this payload. ONLY for OPCode 0 */ /** The event name for this payload. ONLY for OPCode 0 */
t?: string t?: string
} }
export interface DiscordBotGateway { export interface DiscordBotGateway {
/** The WSS URL that can be used for connecting to the gateway. */ /** The WSS URL that can be used for connecting to the gateway. */
url: string url: string
/** The recommended number of shards to use when connecting. */ /** The recommended number of shards to use when connecting. */
shards: number shards: number
/** Info on the current start limit. */ /** Info on the current start limit. */
session_start_limit: { session_start_limit: {
/** The total number of session starts the current user is allowed. */ /** The total number of session starts the current user is allowed. */
total: number total: number
/** The remaining number of session starts the current user is allowed. */ /** The remaining number of session starts the current user is allowed. */
remaining: number remaining: number
/** Milliseconds left until limit is reset. */ /** Milliseconds left until limit is reset. */
reset_after: number reset_after: number
} }
} }
export interface DiscordHeartbeatPayload { export interface DiscordHeartbeatPayload {
heartbeat_interval: number heartbeat_interval: number
} }
export enum GatewayOpcode { export enum GatewayOpcode {
Dispatch = 0, Dispatch = 0,
Heartbeat, Heartbeat,
Identify, Identify,
StatusUpdate, StatusUpdate,
VoiceStateUpdate, VoiceStateUpdate,
Resume, Resume,
Reconnect, Reconnect,
RequestGuildMembers, RequestGuildMembers,
InvalidSession, InvalidSession,
Hello, Hello,
HeartbeatACK HeartbeatACK
} }
export enum GatewayCloseEventCode { export enum GatewayCloseEventCode {
UnknownError = 4000, UnknownError = 4000,
UnknownOpcode, UnknownOpcode,
DecodeError, DecodeError,
NotAuthenticated, NotAuthenticated,
AuthenticationFailed, AuthenticationFailed,
AlreadyAuthenticated, AlreadyAuthenticated,
InvalidSeq = 4007, InvalidSeq = 4007,
RateLimited, RateLimited,
SessionTimeout, SessionTimeout,
InvalidShard, InvalidShard,
ShardingRequired ShardingRequired
} }
export enum VoiceOpcode { export enum VoiceOpcode {
Identify, Identify,
SelectProtocol, SelectProtocol,
Ready, Ready,
Heartbeat, Heartbeat,
SessionDescription, SessionDescription,
Speaking, Speaking,
HeartbeatACK, HeartbeatACK,
Resume, Resume,
Hello, Hello,
Resumed, Resumed,
ClientDisconnect = 13 ClientDisconnect = 13
} }
export enum VoiceCloseEventCode { export enum VoiceCloseEventCode {
UnknownOpcode = 4001, UnknownOpcode = 4001,
NotAuthenticated = 4003, NotAuthenticated = 4003,
AuthenticationFailed, AuthenticationFailed,
AlreadyAuthenticated, AlreadyAuthenticated,
SessionNoLongerValid, SessionNoLongerValid,
SessionTimeout = 4009, SessionTimeout = 4009,
ServerNotFound = 4011, ServerNotFound = 4011,
UnknownProtocol, UnknownProtocol,
Disconnected = 4014, Disconnected = 4014,
VoiceServerCrashed, VoiceServerCrashed,
UnknownEncryptionMode UnknownEncryptionMode
} }
export enum HttpResponseCode { export enum HttpResponseCode {
Ok = 200, Ok = 200,
Created, Created,
NoContent = 204, NoContent = 204,
NotModified = 304, NotModified = 304,
BadRequest = 400, BadRequest = 400,
Unauthorized = 401, Unauthorized = 401,
Forbidden = 403, Forbidden = 403,
NotFound, NotFound,
MethodNotAllowed, MethodNotAllowed,
TooManyRequests = 429, TooManyRequests = 429,
GatewayUnavailable = 502, GatewayUnavailable = 502
// ServerError left untyped because it's 5xx. // ServerError left untyped because it's 5xx.
} }
export enum JSONErrorCode { export enum JSONErrorCode {
UnknownAccount = 10001, UnknownAccount = 10001,
UnknownApplication, UnknownApplication,
UnknownChannel, UnknownChannel,
UnknownGuild, UnknownGuild,
UnknownIntegration, UnknownIntegration,
UnknownInvite, UnknownInvite,
UnknownMember, UnknownMember,
UnknownMessge, UnknownMessge,
UnknownOverwrite, UnknownOverwrite,
UnknownProvider, UnknownProvider,
UnknownRole, UnknownRole,
UnknownToken = 10012, UnknownToken = 10012,
UnknownUser, UnknownUser,
UnknownEmoji, UnknownEmoji,
UnknownWebhook, UnknownWebhook,
BotsCannotUse = 20001, BotsCannotUse = 20001,
OnlyBotsCanUse, OnlyBotsCanUse,
MaxGuildsReached = 30001, MaxGuildsReached = 30001,
MaxFriendsReached, MaxFriendsReached,
MaxPinsReached, MaxPinsReached,
MaxGuildRolesReached = 30005, MaxGuildRolesReached = 30005,
MaxReactionsReached = 30010, MaxReactionsReached = 30010,
MaxGuildChannelsReached = 30013, MaxGuildChannelsReached = 30013,
MaxInvitesReached = 30016, MaxInvitesReached = 30016,
Unathorized = 40001, Unathorized = 40001,
UserIsBannedFromGuild = 40007, UserIsBannedFromGuild = 40007,
MissingAccess = 50001, MissingAccess = 50001,
InvalidAccountType = 50002, InvalidAccountType = 50002,
CannotExecuteOnDMChannel, CannotExecuteOnDMChannel,
WidgetDisabled, WidgetDisabled,
CannotEditMessageByAnotherUser, CannotEditMessageByAnotherUser,
CannotSendEmptyMessage, CannotSendEmptyMessage,
CannotSendMessageToUser, CannotSendMessageToUser,
CannotSendMessageInVoiceChannel, CannotSendMessageInVoiceChannel,
ChannelVerificationTooHigh, ChannelVerificationTooHigh,
OAuth2ApplicationNoBot, OAuth2ApplicationNoBot,
OAuth2ApplicationLimitReached, OAuth2ApplicationLimitReached,
InvalidOAuthState, InvalidOAuthState,
MissingPermissions, MissingPermissions,
InvalidAuthenticationToken, InvalidAuthenticationToken,
NoteIsTooLong, NoteIsTooLong,
TooFewOrTooManyMessagesToDelete, TooFewOrTooManyMessagesToDelete,
MessageCanOnlyBePinnedInParentChannel = 50019, MessageCanOnlyBePinnedInParentChannel = 50019,
InviteCodeTakenOrInvalid, InviteCodeTakenOrInvalid,
CannotExecuteOnSystemMessage, CannotExecuteOnSystemMessage,
InvalidOAuth2AccessToken, InvalidOAuth2AccessToken,
MessageProvidedTooOldToBulkDelet = 50034, MessageProvidedTooOldToBulkDelet = 50034,
InvalidFormBody, InvalidFormBody,
InviteAcceptedToGuildApplicationBotNotIn, InviteAcceptedToGuildApplicationBotNotIn,
InvalidAPIVersion = 50041, InvalidAPIVersion = 50041,
ReactionBlocked = 90001, ReactionBlocked = 90001,
ResourceOverloaded = 130000 ResourceOverloaded = 130000
} }
+18 -20
View File
@@ -1,34 +1,32 @@
import { blue, green, red, yellow } from "https://deno.land/std/fmt/colors.ts"; import { blue, green, red, yellow } from 'https://deno.land/std/fmt/colors.ts'
export const getTime = () => { export const getTime = () => {
const now = new Date(); const now = new Date()
const hours = now.getHours(); const hours = now.getHours()
const minute = now.getMinutes(); const minute = now.getMinutes()
let hour = hours; let hour = hours
let amOrPm = `AM`; let amOrPm = `AM`
if (hour > 12) { if (hour > 12) {
amOrPm = `PM`; amOrPm = `PM`
hour = hour - 12; hour = hour - 12
} }
return `${hour >= 10 ? hour : `0${hour}`}:${minute >= 10 return `${hour >= 10 ? hour : `0${hour}`}:${minute >= 10 ? minute : `0${minute}`} ${amOrPm}`
? minute }
: `0${minute}`} ${amOrPm}`;
};
export const logGreen = (text: string) => { export const logGreen = (text: string) => {
console.log(green(`[${getTime()}] => ${text}`)); console.log(green(`[${getTime()}] => ${text}`))
}; }
export const logBlue = (text: string) => { export const logBlue = (text: string) => {
console.log(blue(`[${getTime()}] => ${text}`)); console.log(blue(`[${getTime()}] => ${text}`))
}; }
export const logRed = (text: string) => { export const logRed = (text: string) => {
console.log(red(`[${getTime()}] => ${text}`)); console.log(red(`[${getTime()}] => ${text}`))
}; }
export const logYellow = (text: string) => { export const logYellow = (text: string) => {
console.log(yellow(`[${getTime()}] => ${text}`)); console.log(yellow(`[${getTime()}] => ${text}`))
}; }