diff --git a/src/index.ts b/src/index.ts index 11527f1..a7fa233 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,8 @@ import blessed from 'blessed'; import blessedContrib from 'blessed-contrib'; import config from 'config'; +import { Client } from './lib/client'; + const screen = blessed.screen({ smartCSR: true, title: 'chord', @@ -156,6 +158,24 @@ const messageBoxInput = blessed.textarea({ screen.append(mainWindow); +const client = new Client(config.get('token'), {}); + +client.on('ready', (evt: Record) => { + for (const guild of evt['guilds']) { + serverListList.addItem(guild.name); + } + + screen.render(); +}); + +client.on('guild_create', (guild: Record) => { + serverListList.addItem(guild['name']); + + screen.render(); +}); + +client.connect(); + screen.key('S-q', () => { process.exit(0); }); diff --git a/src/lib/client.ts b/src/lib/client.ts new file mode 100644 index 0000000..aaf9d29 --- /dev/null +++ b/src/lib/client.ts @@ -0,0 +1,64 @@ +import { EventEmitter } from 'events'; +import os from 'os'; +import WebSocket from 'ws'; + +export class Client extends EventEmitter { + public ws: WebSocket | null; + + private _config: object; + private _heartbeatInterval: number; + private _token: string; + + public constructor(token: string, config: object) { + super(); + + this.ws = null; + + this._config = config; + this._heartbeatInterval = 0; + this._token = token; + } + + public async connect(): Promise { + this.ws = new WebSocket('wss://gateway.discord.gg/'); + + this.ws.on('error', (err) => { + throw err; + }); + + this.ws.on('close', (_code, reason) => { + throw reason; + }); + + this.ws.on('message', (data: string) => { + const objectData = JSON.parse(data); + + if (objectData.op === 0) { + if (objectData.t === 'GUILD_CREATE') { + this.emit('guild_create', objectData.d); + } else if (objectData.t === 'READY') { + this.emit('ready', objectData.d); + } + } else if (objectData.op === 10) { + this._heartbeatInterval = objectData.d.heartbeat_interval; + + this.ws!.send(JSON.stringify({ + op: 2, + d: { + token: this._token, + intents: 32767, + properties: { + $os: os.platform(), + $browser: 'chord', + $device: 'chord', + }, + }, + })) + + setInterval(() => { + this.ws!.send(JSON.stringify({op: 11})); + }, this._heartbeatInterval); + } + }); + } +}