UNPKG

erium

Version:

Erium is Discord Bot Library made in typescript

134 lines (114 loc) 4.06 kB
import { WebSocket } from "ws"; import Client, { ClientOptions } from "../structures/Client"; import { Endpoints } from "../Endpoints"; import { OPCodes } from "../OPCodes"; import { Heartbeat } from "./Payload"; import { Intents } from "../structures/Intents"; import { GatewayDispatchEvents } from "discord-api-types/v10"; import { RequestHandler } from "../handlers/RequestHandler"; import { GatewayHandler } from "../handlers/GatewayHandler"; import { Presence } from "../types/Presence"; export default class WebSocketCore { private socket: WebSocket | undefined; private interval: any public intents: number; public presence?: Presence private gateway: GatewayHandler; public requestHandler = null; public readonly disableEvents?: (keyof typeof GatewayDispatchEvents)[]; constructor(private client: Client, options: ClientOptions) { let intents = 32765; if (options.disableIntents) { for (const intent of options.disableIntents) { intents -= Intents[intent]; } } this.intents = intents; this.disableEvents = options.disableEvents; this.presence = options.presence; this.gateway = new GatewayHandler(client); // @ts-ignore this.requestHandler = new RequestHandler(client); } async login(token: string) { try { this.socket = new WebSocket(Endpoints.BASE_URL); const payload = { op: 2, d: { token: token, intents: 513, heartbeat_interval: 4, properties: { $os: "linux", $browser: "erium", $device: "erium" } } } this.socket.on("open", () => { // @ts-ignore this.socket.send(JSON.stringify(payload)); }); this.socket.on("message", async (data: string) => { let payload = JSON.parse(data); const { t: event, op } = payload; switch (op) { case OPCodes.ZERO: break; case OPCodes.NINE: break; case OPCodes.TEN: const { t: event, s, op, d } = payload; const { heartbeat_interval } = d; this.interval = this.heartbeat(heartbeat_interval); await this.identify(token); break; case OPCodes.ELEVEN: break; } if (event) { try { const { default: module } = await import(`../events/${event}_EVENT`); module(this.client, payload); // console.log(`Current Event: ${event}`); } catch (err) { console.log(err); } } }); } catch (err) { console.log(err); } } public setPresence(presence?: Presence) { if (!presence) presence = this.presence; if (!presence) return; this.gateway.updatePresence(presence); } public get ping(): number { return this.gateway.latency; } private heartbeat(ms: number) { return setInterval(() => { // @ts-ignore this.socket.send(JSON.stringify(Heartbeat)) }, ms); } private async identify(token: string) { return { op: 2, d: { token, properties: { $os: "linux", $browser: "erium", $device: "erium" } }, compress: false, intents: this.intents, presence: this.presence } } }