Skip to content

Commit

Permalink
Update bot
Browse files Browse the repository at this point in the history
  • Loading branch information
Volodymyr Saakian committed Mar 6, 2020
1 parent 5a9cf02 commit 72e4f16
Show file tree
Hide file tree
Showing 9 changed files with 197 additions and 74 deletions.
13 changes: 10 additions & 3 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 @@ -23,7 +23,8 @@
"aws-sdk": "^2.628.0",
"dotenv": "^8.2.0",
"got": "^10.6.0",
"telegraf": "^3.36.0"
"telegraf": "^3.36.0",
"uuid": "^7.0.2"
},
"devDependencies": {
"nodemon": "^2.0.2",
Expand Down
43 changes: 43 additions & 0 deletions src/api/FinanceApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const Http = require('../utils/http');

class FinanceApi {
generateMessageTemplate() {
const banks = ['ПриватБанк', 'Укрсиббанк'];
const currencyIgnore = ['RUB'];

const findedBanks = this.data.organizations.reduce((acc, val) => {
if (banks.includes(val.title)) {
return [...acc, val];
}
return [...acc];
}, []);

return findedBanks
.map(bank => {
const firstLine = `${bank.title}: \n`;
const nextLines = Object.keys(bank.currencies).reduce((acc, key) => {
const currency = bank.currencies[key];
if (currencyIgnore.includes(key)) {
return [...acc];
}
return [
...acc,
`${key}: ${parseInt(currency.ask).toFixed(2)}/${parseInt(
currency.bid
).toFixed(2)}`
];
}, []);
return firstLine + nextLines.join('\n');
})
.join('\n\n');
}

async getData() {
this.data = await Http.get(
'http://resources.finance.ua/ru/public/currency-cash.json'
);
return this.data;
}
}

module.exports = FinanceApi;
7 changes: 7 additions & 0 deletions src/api/MinfinApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const Http = require('../utils/http');

class MinfinApi {
static async get() {
return Http.get('http://resources.finance.ua/ru/public/currency-cash.json');
}
}
98 changes: 59 additions & 39 deletions src/bot.js
Original file line number Diff line number Diff line change
@@ -1,62 +1,82 @@
const Telegraf = require('telegraf');
const Telegram = require('telegraf/telegram');
const session = require('telegraf/session');
const Extra = require('telegraf/extra');
const Markup = require('telegraf/markup');
const { TOKEN } = require('./config/env');
const DynamoDatabase = require('./utils/aws/dynamo');
const FinanceApi = require('./utils/api/FinanceApi');
const FinanceApi = require('./api/FinanceApi');
//251408559 user
//978534005 bot

class TelegramExecutor extends DynamoDatabase {
async execute() {
const bot = new Telegraf(TOKEN);
// console.log(await this.putItem());
console.log('Started!');

// bot.use(session());
// bot.use(Telegraf.log());
// bot.use((ctx, next) => {
// ctx.state.text = ctx.message.text;
// return next();
// });
bot.start(async ctx => {
console.log(ctx);
ctx.telegram.setChatPermissions(ctx.botInfo.id, {
can_send_messages: true
});
ctx.reply('Welcome to exchange bot!');
});

bot.help(ctx => ctx.reply('Send me a sticker'));
bot.on('sticker', ctx => ctx.reply('👍'));
bot.command('showratesfinance', async ctx => {
const financeApi = new FinanceApi();
await financeApi.getData();
const template = financeApi.generateMessageTemplate();
// console.log(ctx.state);
ctx.session.counter = ctx.session.counter || 0;
ctx.session.counter++;
console.log(ctx.session.counter);
// return ctx.reply(
// template,
// );
// return ctx.reply(
// template,
// Markup.keyboard([
// 'Every 6 hours',
// 'Every 12 hours',
// 'Every day',
// 'Every 2 days'
// ])
// .oneTime()
// .resize()
// .extra()
// );
return ctx.reply(template);
});
bot.command('showratesminfin', async ctx => {
const financeData = await FinanceApi.get();
const banks = ['ПриватБанк', 'Укрсиббанк'];
const currencyIgnore = ['RUB'];
console.log(ctx.message);
const data = {
...ctx.message.from,
chatId: ctx.message.chat.id,
date: ctx.message.date,
text: ctx.message.text
};
await this.putItem(data);

const findedBanks = financeData.organizations.reduce((acc, val) => {
if (banks.includes(val.title)) {
return [...acc, val];
}
return [...acc];
}, []);
// ctx.state = { A: 2 };
// console.log(ctx.state);
// console.log(123123);
console.log(ctx.session);

const template = findedBanks
.map(bank => {
console.log(bank);
const firstLine = `${bank.title}: \n`;
const nextLines = Object.keys(bank.currencies).reduce((acc, key) => {
const currency = bank.currencies[key];
if (currencyIgnore.includes(key)) {
return [...acc];
}
return [
...acc,
`${key}: ${parseInt(currency.ask).toFixed(2)}/${parseInt(
currency.bid
).toFixed(2)}`
];
}, []);
return firstLine + nextLines.join('\n');
})
.join('\n\n');
// return ctx.telegram.sendMessage(251408559, template);
return ctx.reply(template);
return ctx.reply('Rates from minfin');
});
bot.command('showratesfinance', ctx => {
console.log(123123);
return ctx.reply('Hello');
bot.on('text', async ctx => {
const data = {
...ctx.message.from,
chatId: ctx.message.chat.id,
date: ctx.message.date,
text: ctx.message.text
};
await this.putItem(data);
return ctx.reply(ctx.message.text);
});
bot.launch();
}
Expand Down
11 changes: 0 additions & 11 deletions src/utils/api/FinanceApi.js

This file was deleted.

7 changes: 0 additions & 7 deletions src/utils/api/MinfinApi.js

This file was deleted.

77 changes: 64 additions & 13 deletions src/utils/aws/dynamo.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const got = require('got');
const AWS = require('aws-sdk');
const tableName = 'exchane-rates-ukraine-bot';
const uuid = require('uuid/v4');

class DynamoDatabase {
constructor() {
this.dynamodb = new AWS.DynamoDB({
Expand All @@ -12,6 +14,34 @@ class DynamoDatabase {
return this.dynamodb.listTables({}).promise();
}

async scan() {
var params = {
TableName: tableName
};
this.dynamodb.scan(params, function(err, data) {
if (err) {
console.log('Error', err);
} else {
console.log('Success', data.Items);
}
});
}

async get() {
var params = {
TableName: tableName,
KeyConditionExpression: 'CUSTOMER_ID = :i'
// ExpressionAttributeValues: [(':i': ['2'])]
};
this.dynamodb.query(params, function(err, data) {
if (err) {
console.log('Error', err);
} else {
console.log('Success', data.Items);
}
});
}

async getItem() {
var params = {
TableName: tableName,
Expand All @@ -29,22 +59,43 @@ class DynamoDatabase {
});
}

async putItem() {
var params = {
TableName: tableName,
Item: {
CUSTOMER_ID: { N: '001' },
CUSTOMER_NAME: { S: 'Richard Roe' }
async putItem(data) {
const getType = type => {
// console.log(type);
switch (type) {
case 'string':
return 'S';
case 'number':
return 'N';
case 'bool':
return 'B';
default:
return 'S';
}
};

this.dynamodb.putItem(params, function(err, data) {
if (err) {
console.log('Error', err);
} else {
console.log('Success', data);
}
});
const preparedData = Object.keys(data).reduce((acc, key) => {
return {
...acc,
[key]: { [getType(typeof data[key])]: String(data[key]) }
};
}, {});
console.log(preparedData);

const params = {
TableName: tableName,
Item: {
'exchane-rates-ukraine-bot-primary-key': { S: uuid() },
...preparedData
},
ReturnValues: 'NONE'
};
try {
const data = await this.dynamodb.putItem(params).promise();
console.log(data);
} catch (e) {
throw new Error(e);
}
}

async deleteItem() {
Expand Down
12 changes: 12 additions & 0 deletions src/utils/http.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const got = require('got');

const get = async url => {
try {
const response = await got.get(url).json();
return response;
} catch (error) {
throw error;
}
};

module.exports = { get };

0 comments on commit 72e4f16

Please sign in to comment.