Skip to content

Commit

Permalink
Auto reconnect when disconnected
Browse files Browse the repository at this point in the history
  • Loading branch information
ByPikod committed Aug 9, 2023
1 parent 1606b64 commit 78c94e7
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 17 deletions.
27 changes: 21 additions & 6 deletions bot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ bot.on("channelsLoaded", (channels: Channel[]) => {

const channel = bot.getChannelByName("en")
if(!channel) return;

/*
bot.sendAnnouncement("Test announcement", channel, true).then((data: any) => {
info(`Announcement sent, total receivers: ${data[0]}`)
});
*/

})

Expand Down Expand Up @@ -59,17 +62,29 @@ bot.on("close", (err: string) => {
info(`Socket closed: ${err}`)
})

/* Listen heartbeats */
bot.on("heartbeat", () => {
info("Ping sent!")
})

bot.connect(
config.url,
config.apiKey,
Subscriptions.CHAT + Subscriptions.ONLINE
).then(() => {
bot.on("open", () => {

info("Bot connected!")

// Try fetch flag feature
bot.fetchFlag(1).then((data) => {
info(`Flag: ${data[0]}, ID: ${data[1]}`)
})
})

// Try reconnecting feature
setTimeout(() => {
bot._ws?.close()
}, 20000);

})

bot.connect(
config.url,
config.apiKey,
Subscriptions.CHAT + Subscriptions.ONLINE
)
50 changes: 39 additions & 11 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ import { recievedMessage } from "./packets/message"
import { receivedPixel } from "./packets/pixel"
import { createPingPacket } from "./packets/ping"

export type BotConstructor = {
autoReconnect: boolean,
botName: string,
botChatId: number,
botCountry: string
}

/**
* Events:
* @emits open
Expand All @@ -37,30 +44,51 @@ export class Bot extends EventEmitter {
private botName: string
private botChatId: number
private botCountry: string
private autoReconnect: boolean
private url?: string
private apiKey?: string

private timeLastPing: number = 0
private timeLastSent: number = 0
private heartbeatTimer?: NodeJS.Timer

constructor(botName: string="Bot", botChatId: number=0, botCountry: string="zz") {
constructor(
data: BotConstructor = {
autoReconnect: true,
botName: "Bot",
botChatId: 0,
botCountry: "zz"
}
) {
super()
this.botName = botName
this.botChatId = botChatId
this.botCountry = botCountry
this.botName = data.botName
this.botChatId = data.botChatId
this.botCountry = data.botCountry
this.autoReconnect = data.autoReconnect
}

async connect(url: string, apiKey: string, subscriptions: Subscriptions = 0) {

this.url = url
this.apiKey = apiKey
this.subscriptions = subscriptions

await new Promise((resolve, reject) => {
return this._connect()
}

protected async _connect() {

return await new Promise((resolve, reject) => {

if(!this.url || !this.apiKey) {
reject("Malformed URL or Api Key")
return;
}

this._ws = new WebSocket(
url,
this.url,
{
perMessageDeflate: false,
headers: {
'Authorization': `Bearer ${apiKey}`
'Authorization': `Bearer ${this.apiKey}`
}
}
)
Expand Down Expand Up @@ -95,7 +123,6 @@ export class Bot extends EventEmitter {
return

// Subscriptions

if(this.checkSubscribed(Subscriptions.CHAT))
this._ws.send(
JSON.stringify(
Expand Down Expand Up @@ -137,7 +164,8 @@ export class Bot extends EventEmitter {
protected heartbeat(): boolean {

if (this._ws?.readyState !== WebSocket.OPEN) {
this.close("Websocket is closed somehow")
this.close(`Websocket is closed somehow ${this.autoReconnect ? ", reconnecting..." : "."}`)
if(this.autoReconnect) this._connect()
return false
}

Expand Down

0 comments on commit 78c94e7

Please sign in to comment.