feat: added basic websocket handler and guild rendering
This commit is contained in:
parent
773a18f114
commit
b6d83fea48
2 changed files with 84 additions and 0 deletions
20
src/index.ts
20
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<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', () => {
|
||||
process.exit(0);
|
||||
});
|
||||
|
|
64
src/lib/client.ts
Normal file
64
src/lib/client.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
Reference in a new issue