diff --git a/backend/src/services/sinusbot.service.ts b/backend/src/services/sinusbot.service.ts index d911e5d..03e9117 100644 --- a/backend/src/services/sinusbot.service.ts +++ b/backend/src/services/sinusbot.service.ts @@ -7,18 +7,21 @@ import fetch from 'node-fetch'; @Injectable() export class SinusBotService { private host = process.env.HOST - private botInfo = { - id: process.env.SINUSBOT_BOTID, - instanceId: null - } - - private tunaKillURL = `${this.host}/api/v1/bot/i/${this.botInfo.instanceId}/event/tunakill_rank_all_user`; - private loginURL = `${this.host}/api/v1/bot/login`; private credentials = { username: process.env.SINUSBOT_USER, password: process.env.SINUSBOT_PASSWORD } - private bearer?: string; + + private botInfo = { + id: undefined, + instanceId: process.env.SINUSBOT_INSTANCEID + } + + private botIdURL = `${this.host}/api/v1/botId`; + private tunaKillURL = `${this.host}/api/v1/bot/i/${this.botInfo.instanceId}/event/tunakill_rank_all_user`; + private loginURL = `${this.host}/api/v1/bot/login`; + + private bearer: string; public async fetchStats(): Promise { if (this.bearer == null) { @@ -35,7 +38,7 @@ export class SinusBotService { console.log(`I try to fetch user data now!`) return await fetch(this.tunaKillURL, this.requestConfig(null, this.bearer)) .then(res => this.checkStatus(res)) - .then(data => data.json()) + .then(res => res.json()) .then(data => this.consumeTunakillResponse(data)) .catch(error => { throw this.createHttpException(HttpStatus.UNAUTHORIZED, error.message); @@ -46,6 +49,19 @@ export class SinusBotService { * Returns bearer token if login was successful */ private async login(): Promise { + if (this.botInfo.id == null) { + console.log(`I have to fetch a bot ID before I can continue!`); + await this.fetchDefaultBotId() + .then(defaultBotId => this.botInfo.id = defaultBotId) + .catch(() => { + throw this.createHttpException( + HttpStatus.NOT_FOUND, + `Could not fetch enough bot information for further requests.` + ); + }); + console.log(`Looks like everything went fine. The bot ID now is ${this.botInfo.id}`); + } + const body: TunakillLogin = { username: this.credentials.username, password: this.credentials.password, @@ -55,10 +71,17 @@ export class SinusBotService { console.log(`> I try to login now! My credentials are: ${JSON.stringify(body)}`) return await fetch(this.loginURL, this.requestConfig(JSON.stringify(body))) .then(res => this.checkStatus(res)) - .then(data => data.json()) + .then(res => res.json()) .then(data => data.token); } + private async fetchDefaultBotId(): Promise { + return await fetch(this.botIdURL) + .then(res => this.checkStatus(res)) + .then(res => res.json()) + .then(data => data.defaultBotId); + } + private consumeTunakillResponse(data: any): TableEntry[] { if (!(data !== null || data[0] !== null || data[0].data !== null)) { throw Error('Response from SinusBot does not have any data to parse.')