Skip to content

Commit

Permalink
Merge pull request #5 from UniqueNetwork/slack-command
Browse files Browse the repository at this point in the history
add /balances command to slack
  • Loading branch information
abdulgalimov authored Jul 20, 2023
2 parents 9580c13 + b25b5dc commit 33da685
Show file tree
Hide file tree
Showing 16 changed files with 364 additions and 241 deletions.
87 changes: 81 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/swagger": "^7.1.1",
"@slack/web-api": "^6.8.1",
"big-number": "^2.0.0",
"@unique-nft/accounts": "0.3.2",
"@unique-nft/sdk": "0.1.5",
"@unique-nft/utils": "0.1.4",
"big-number": "^2.0.0",
"cache-manager": "^4.1.0",
"cache-manager-redis-store": "^2.0.0",
"format-duration": "^2.0.0",
Expand Down
18 changes: 18 additions & 0 deletions src/api/api.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Controller, Get, Logger, Post } from '@nestjs/common';
import { BalancesService } from './balances/balances.service';

@Controller('api')
export class ApiController {
private logger = new Logger(ApiController.name);
constructor(private readonly balancesService: BalancesService) {}

@Post('/balances')
private showBalances() {
this.logger.log('Show balances');
try {
return this.balancesService.showBalances();
} catch (err) {
this.logger.log(`Show balances Error ${err.message}`, err);
}
}
}
10 changes: 10 additions & 0 deletions src/api/api.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { ApiController } from './api.controller';
import { BalancesService } from './balances/balances.service';
import { BalancesNotifications } from './balances/balances.notifications';

@Module({
controllers: [ApiController],
providers: [BalancesService, BalancesNotifications],
})
export class ApiModule {}
100 changes: 100 additions & 0 deletions src/api/balances/balances.notifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { WebClient } from '@slack/web-api';
import { BalancesConfig } from '../../config/balances.config';
import { SlackConfig } from '../../config/config.module';
import { ConfigService } from '@nestjs/config';
import * as BigNumber from 'big-number';
import { BalanceData, ChainBalanceData, markdownTemplate } from './types';
import { BalancesService } from './balances.service';

@Injectable()
export class BalancesNotifications implements OnModuleInit {
private logger = new Logger(BalancesNotifications.name);

private balanceConfig: BalancesConfig;
private slackConfig: SlackConfig;
private adminUsers: number[];

private web: WebClient;

constructor(config: ConfigService, private balancesService: BalancesService) {
this.balanceConfig = config.get<BalancesConfig>('balances');
this.adminUsers = config.get<number[]>('adminUsers');
this.slackConfig = config.get<SlackConfig>('slack');
}

async onModuleInit(): Promise<void> {
const slackNotificationsAvailable =
this.slackConfig.token &&
this.balanceConfig.criticalValue &&
this.slackConfig.channelName;

if (!slackNotificationsAvailable) return;

this.web = new WebClient(this.slackConfig.token);
setInterval(async () => {
await this.checkBalances();
}, 5 * 3_600_000);

await this.checkBalances();
}

private async checkBalances() {
const criticalValue = BigNumber(this.balanceConfig.criticalValue);
this.logger.log(`check balances, critical value: ${criticalValue}`);

const chainBalances = await Promise.all([
this.balancesService.getBalances(this.balanceConfig.unique),
this.balancesService.getBalances(this.balanceConfig.quartz),
]);

this.logger.log('chain balances', JSON.stringify(chainBalances, null, 2));

const criticalBalances = chainBalances
.map((chainBalance) => {
return {
name: chainBalance.name,
balances: chainBalance.balances.filter((balanceData: BalanceData) => {
return BigNumber(balanceData.balance.raw).lt(criticalValue);
}),
};
})
.filter((chainBalance) => chainBalance.balances.length);

if (!criticalBalances.length) return;

const message = criticalBalances
.map((chainBalanceData: ChainBalanceData) => {
return `${chainBalanceData.name}:
${this.balancesService.balancesToString(
chainBalanceData.balances,
markdownTemplate,
)}`;
})
.join('\n\n');

const mentions = this.slackConfig.mentionUsers
.map((id) => `<@${id}>`)
.join(' ');

try {
const postMessageResult = await this.web.chat.postMessage({
link_names: true,
text: `Not enough money on the account
${message}
${mentions}`,
channel: this.slackConfig.channelName,
});
this.logger.log('post message result', postMessageResult);
} catch (err) {
this.logger.error(
'post message error',
err.message,
JSON.stringify(err, null, 2),
);
}
}
}
Loading

0 comments on commit 33da685

Please sign in to comment.