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

View File

@@ -1,12 +1,12 @@
import Client from "../module/Client.ts";
import Client from '../module/Client.ts'
class RequestManager {
client: Client;
token: string;
client: Client
token: string
constructor(client: Client, token: string) {
this.client = client;
this.token = token;
this.client = client
this.token = token
}
async get(url: string, payload?: unknown) {
@@ -18,15 +18,14 @@ class RequestManager {
// let attempts = 0
const headers = {
Authorization: this.token,
"User-Agent":
`DiscordBot (https://github.com/skillz4killz/discordeno, 0.0.1)`
};
'User-Agent': `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());
return data;
const data = await fetch(url, { headers }).then(res => res.json())
return data
}
}
export default RequestManager;
export default RequestManager

View File

@@ -1,4 +1,3 @@
class ShardingManager extends Map {
}
class ShardingManager extends Map {}
export default ShardingManager;
export default ShardingManager

6
mod.ts
View File

@@ -1,7 +1,7 @@
import Client from "./module/Client.ts"
import { configs } from "./configs.ts"
import Client from './module/Client.ts'
import { configs } from './configs.ts'
const Discordeno = new Client(configs.token)
Discordeno.connect()
export default Discordeno
export default Discordeno

View File

@@ -1,87 +1,79 @@
import { endpoints } from "../constants/discord.ts";
import RequestManager from "../managers/RequestManager.ts";
import { DiscordBotGateway, DiscordPayload,
DiscordHeartbeatPayload } from "../types/discord.ts";
import ShardingManager from "../managers/ShardingManager.ts";
import { endpoints } from '../constants/discord.ts'
import RequestManager from '../managers/RequestManager.ts'
import { DiscordBotGateway, DiscordPayload, DiscordHeartbeatPayload } from '../types/discord.ts'
import ShardingManager from '../managers/ShardingManager.ts'
import {
connectWebSocket,
isWebSocketCloseEvent,
isWebSocketPingEvent,
isWebSocketPongEvent,
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 { BufReader } from "https://deno.land/std/io/bufio.ts"
// import { TextProtoReader } from "https://deno.land/std/textproto/mod.ts"
import { keepDiscordWebsocketAlive,
updatePreviousSequenceNumber } from "./websocket.ts";
import { logGreen, logRed, logYellow, logBlue } from "../utils/logger.ts";
import { keepDiscordWebsocketAlive, updatePreviousSequenceNumber } from './websocket.ts'
import { logGreen, logRed, logYellow, logBlue } from '../utils/logger.ts'
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. */
token: string;
token: string
/** 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. */
ShardingManager: ShardingManager;
ShardingManager: ShardingManager
constructor(token: string) {
this.token = `Bot ${token}`;
this.RequestManager = new RequestManager(this, this.token);
this.ShardingManager = new ShardingManager();
this.token = `Bot ${token}`
this.RequestManager = new RequestManager(this, this.token)
this.ShardingManager = new ShardingManager()
}
/** Begins initial handshake, creates the websocket with Discord and spawns all necessary shards. */
async connect() {
const data = (await this.RequestManager.get(
endpoints.GATEWAY_BOT
)) as DiscordBotGateway;
const data = (await this.RequestManager.get(endpoints.GATEWAY_BOT)) as DiscordBotGateway
// Open a WS with the url from discord.
const sock = await connectWebSocket(data.url);
console.log(sock);
logGreen("ws connected! (type 'close' to quit)");
const sock = await connectWebSocket(data.url)
console.log(sock)
logGreen("ws connected! (type 'close' to quit)")
for await (const msg of sock.receive()) {
if (typeof msg === "string") {
if (typeof msg === 'string') {
try {
const json = JSON.parse(msg);
this.handleDiscordPayload(json, sock);
const json = JSON.parse(msg)
this.handleDiscordPayload(json, sock)
} 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)) {
logBlue("< ping");
logBlue('< ping')
} else if (isWebSocketPongEvent(msg)) {
logBlue("< pong");
logBlue('< pong')
} 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
this.spawnShards(data.shards);
this.spawnShards(data.shards)
}
handleDiscordPayload(data: DiscordPayload, socket: WebSocket) {
switch (data.op) {
case 10: // Initial Heartbeat
keepDiscordWebsocketAlive(
socket,
(data.d as DiscordHeartbeatPayload).heartbeat_interval,
data.s
);
break;
keepDiscordWebsocketAlive(socket, (data.d as DiscordHeartbeatPayload).heartbeat_interval, data.s)
break
case 11:
updatePreviousSequenceNumber(data.s);
break;
updatePreviousSequenceNumber(data.s)
break
}
}
spawnShards(total: number, id = 1) {
// 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

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
export const keepDiscordWebsocketAlive = (socket: WebSocket, millesecondsInterval: number, payload: number | null = null) => {
previousSequenceNumber = payload
export const keepDiscordWebsocketAlive = (
socket: WebSocket,
millesecondsInterval: number,
payload: number | null = null
) => {
previousSequenceNumber = payload
setInterval(() => {
socket.send(JSON.stringify({
op: 1,
d: previousSequenceNumber
}))
}, millesecondsInterval)
setInterval(() => {
socket.send(
JSON.stringify({
op: 1,
d: previousSequenceNumber
})
)
}, millesecondsInterval)
}
export const updatePreviousSequenceNumber = (sequence: number | null = null) => {

View File

@@ -1,3 +1,3 @@
export const createChannel = (data: unknown) => {
console.log(data);
};
console.log(data)
}

View File

@@ -1,3 +1,3 @@
export const createEmoji = (data: unknown) => {
console.log(data);
};
console.log(data)
}

View File

@@ -1,3 +1,3 @@
export const createMember = (data: unknown) => {
console.log(data);
};
console.log(data)
}

View File

@@ -1,3 +1,3 @@
export const createPresence = (data: unknown) => {
console.log(data);
};
console.log(data)
}

View File

@@ -1,3 +1,3 @@
export const createRole = (data: unknown) => {
console.log(data);
};
console.log(data)
}

View File

@@ -1,3 +1,3 @@
export const createVoiceState = (data: unknown) => {
console.log(data);
};
console.log(data)
}

View File

@@ -1,156 +1,156 @@
export interface DiscordPayload {
/** OP code for the payload */
op: number
/** The real event data. Any JSON value basically. */
d: unknown
/** The sequence number, used for resuming sessions and heartbeats. ONLY for OPCode 0 */
s?: number
/** The event name for this payload. ONLY for OPCode 0 */
t?: string
/** OP code for the payload */
op: number
/** The real event data. Any JSON value basically. */
d: unknown
/** The sequence number, used for resuming sessions and heartbeats. ONLY for OPCode 0 */
s?: number
/** The event name for this payload. ONLY for OPCode 0 */
t?: string
}
export interface DiscordBotGateway {
/** The WSS URL that can be used for connecting to the gateway. */
url: string
/** The recommended number of shards to use when connecting. */
shards: number
/** Info on the current start limit. */
session_start_limit: {
/** The total number of session starts the current user is allowed. */
total: number
/** The remaining number of session starts the current user is allowed. */
remaining: number
/** Milliseconds left until limit is reset. */
reset_after: number
}
/** The WSS URL that can be used for connecting to the gateway. */
url: string
/** The recommended number of shards to use when connecting. */
shards: number
/** Info on the current start limit. */
session_start_limit: {
/** The total number of session starts the current user is allowed. */
total: number
/** The remaining number of session starts the current user is allowed. */
remaining: number
/** Milliseconds left until limit is reset. */
reset_after: number
}
}
export interface DiscordHeartbeatPayload {
heartbeat_interval: number
heartbeat_interval: number
}
export enum GatewayOpcode {
Dispatch = 0,
Heartbeat,
Identify,
StatusUpdate,
VoiceStateUpdate,
Resume,
Reconnect,
RequestGuildMembers,
InvalidSession,
Hello,
HeartbeatACK
Dispatch = 0,
Heartbeat,
Identify,
StatusUpdate,
VoiceStateUpdate,
Resume,
Reconnect,
RequestGuildMembers,
InvalidSession,
Hello,
HeartbeatACK
}
export enum GatewayCloseEventCode {
UnknownError = 4000,
UnknownOpcode,
DecodeError,
NotAuthenticated,
AuthenticationFailed,
AlreadyAuthenticated,
InvalidSeq = 4007,
RateLimited,
SessionTimeout,
InvalidShard,
ShardingRequired
UnknownError = 4000,
UnknownOpcode,
DecodeError,
NotAuthenticated,
AuthenticationFailed,
AlreadyAuthenticated,
InvalidSeq = 4007,
RateLimited,
SessionTimeout,
InvalidShard,
ShardingRequired
}
export enum VoiceOpcode {
Identify,
SelectProtocol,
Ready,
Heartbeat,
SessionDescription,
Speaking,
HeartbeatACK,
Resume,
Hello,
Resumed,
ClientDisconnect = 13
Identify,
SelectProtocol,
Ready,
Heartbeat,
SessionDescription,
Speaking,
HeartbeatACK,
Resume,
Hello,
Resumed,
ClientDisconnect = 13
}
export enum VoiceCloseEventCode {
UnknownOpcode = 4001,
NotAuthenticated = 4003,
AuthenticationFailed,
AlreadyAuthenticated,
SessionNoLongerValid,
SessionTimeout = 4009,
ServerNotFound = 4011,
UnknownProtocol,
Disconnected = 4014,
VoiceServerCrashed,
UnknownEncryptionMode
UnknownOpcode = 4001,
NotAuthenticated = 4003,
AuthenticationFailed,
AlreadyAuthenticated,
SessionNoLongerValid,
SessionTimeout = 4009,
ServerNotFound = 4011,
UnknownProtocol,
Disconnected = 4014,
VoiceServerCrashed,
UnknownEncryptionMode
}
export enum HttpResponseCode {
Ok = 200,
Created,
NoContent = 204,
NotModified = 304,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound,
MethodNotAllowed,
TooManyRequests = 429,
GatewayUnavailable = 502,
// ServerError left untyped because it's 5xx.
Ok = 200,
Created,
NoContent = 204,
NotModified = 304,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound,
MethodNotAllowed,
TooManyRequests = 429,
GatewayUnavailable = 502
// ServerError left untyped because it's 5xx.
}
export enum JSONErrorCode {
UnknownAccount = 10001,
UnknownApplication,
UnknownChannel,
UnknownGuild,
UnknownIntegration,
UnknownInvite,
UnknownMember,
UnknownMessge,
UnknownOverwrite,
UnknownProvider,
UnknownRole,
UnknownToken = 10012,
UnknownUser,
UnknownEmoji,
UnknownWebhook,
BotsCannotUse = 20001,
OnlyBotsCanUse,
MaxGuildsReached = 30001,
MaxFriendsReached,
MaxPinsReached,
MaxGuildRolesReached = 30005,
MaxReactionsReached = 30010,
MaxGuildChannelsReached = 30013,
MaxInvitesReached = 30016,
Unathorized = 40001,
UserIsBannedFromGuild = 40007,
MissingAccess = 50001,
InvalidAccountType = 50002,
CannotExecuteOnDMChannel,
WidgetDisabled,
CannotEditMessageByAnotherUser,
CannotSendEmptyMessage,
CannotSendMessageToUser,
CannotSendMessageInVoiceChannel,
ChannelVerificationTooHigh,
OAuth2ApplicationNoBot,
OAuth2ApplicationLimitReached,
InvalidOAuthState,
MissingPermissions,
InvalidAuthenticationToken,
NoteIsTooLong,
TooFewOrTooManyMessagesToDelete,
MessageCanOnlyBePinnedInParentChannel = 50019,
InviteCodeTakenOrInvalid,
CannotExecuteOnSystemMessage,
InvalidOAuth2AccessToken,
MessageProvidedTooOldToBulkDelet = 50034,
InvalidFormBody,
InviteAcceptedToGuildApplicationBotNotIn,
InvalidAPIVersion = 50041,
ReactionBlocked = 90001,
ResourceOverloaded = 130000
UnknownAccount = 10001,
UnknownApplication,
UnknownChannel,
UnknownGuild,
UnknownIntegration,
UnknownInvite,
UnknownMember,
UnknownMessge,
UnknownOverwrite,
UnknownProvider,
UnknownRole,
UnknownToken = 10012,
UnknownUser,
UnknownEmoji,
UnknownWebhook,
BotsCannotUse = 20001,
OnlyBotsCanUse,
MaxGuildsReached = 30001,
MaxFriendsReached,
MaxPinsReached,
MaxGuildRolesReached = 30005,
MaxReactionsReached = 30010,
MaxGuildChannelsReached = 30013,
MaxInvitesReached = 30016,
Unathorized = 40001,
UserIsBannedFromGuild = 40007,
MissingAccess = 50001,
InvalidAccountType = 50002,
CannotExecuteOnDMChannel,
WidgetDisabled,
CannotEditMessageByAnotherUser,
CannotSendEmptyMessage,
CannotSendMessageToUser,
CannotSendMessageInVoiceChannel,
ChannelVerificationTooHigh,
OAuth2ApplicationNoBot,
OAuth2ApplicationLimitReached,
InvalidOAuthState,
MissingPermissions,
InvalidAuthenticationToken,
NoteIsTooLong,
TooFewOrTooManyMessagesToDelete,
MessageCanOnlyBePinnedInParentChannel = 50019,
InviteCodeTakenOrInvalid,
CannotExecuteOnSystemMessage,
InvalidOAuth2AccessToken,
MessageProvidedTooOldToBulkDelet = 50034,
InvalidFormBody,
InviteAcceptedToGuildApplicationBotNotIn,
InvalidAPIVersion = 50041,
ReactionBlocked = 90001,
ResourceOverloaded = 130000
}

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 = () => {
const now = new Date();
const hours = now.getHours();
const minute = now.getMinutes();
const now = new Date()
const hours = now.getHours()
const minute = now.getMinutes()
let hour = hours;
let amOrPm = `AM`;
let hour = hours
let amOrPm = `AM`
if (hour > 12) {
amOrPm = `PM`;
hour = hour - 12;
amOrPm = `PM`
hour = hour - 12
}
return `${hour >= 10 ? hour : `0${hour}`}:${minute >= 10
? minute
: `0${minute}`} ${amOrPm}`;
};
return `${hour >= 10 ? hour : `0${hour}`}:${minute >= 10 ? minute : `0${minute}`} ${amOrPm}`
}
export const logGreen = (text: string) => {
console.log(green(`[${getTime()}] => ${text}`));
};
console.log(green(`[${getTime()}] => ${text}`))
}
export const logBlue = (text: string) => {
console.log(blue(`[${getTime()}] => ${text}`));
};
console.log(blue(`[${getTime()}] => ${text}`))
}
export const logRed = (text: string) => {
console.log(red(`[${getTime()}] => ${text}`));
};
console.log(red(`[${getTime()}] => ${text}`))
}
export const logYellow = (text: string) => {
console.log(yellow(`[${getTime()}] => ${text}`));
};
console.log(yellow(`[${getTime()}] => ${text}`))
}