Archived
0
0
Fork 0

feat: added basic websocket handler and guild rendering

This commit is contained in:
Daryl Ronningen 2021-12-29 20:23:48 -08:00
parent 773a18f114
commit b6d83fea48
Signed by: Daryl Ronningen
GPG key ID: FD23F0C934A5EC6B
2 changed files with 84 additions and 0 deletions

View file

@ -5,6 +5,8 @@ import blessed from 'blessed';
import blessedContrib from 'blessed-contrib'; import blessedContrib from 'blessed-contrib';
import config from 'config'; import config from 'config';
import { Client } from './lib/client';
const screen = blessed.screen({ const screen = blessed.screen({
smartCSR: true, smartCSR: true,
title: 'chord', title: 'chord',
@ -156,6 +158,24 @@ const messageBoxInput = blessed.textarea({
screen.append(mainWindow); screen.append(mainWindow);
const client = new Client(config.get('token'), {});
client.on('ready', (evt: Record<string, any>) => {
for (const guild of evt['guilds']) {
serverListList.addItem(guild.name);
}
screen.render();
});
client.on('guild_create', (guild: Record<string, any>) => {
serverListList.addItem(guild['name']);
screen.render();
});
client.connect();
screen.key('S-q', () => { screen.key('S-q', () => {
process.exit(0); process.exit(0);
}); });

64
src/lib/client.ts Normal file
View file

@ -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<void> {
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);
}
});
}
}