nexushub-commands 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/Client.d.ts CHANGED
@@ -19,6 +19,11 @@ export interface DepositConfig {
19
19
  agreement: string;
20
20
  menuCommand: any;
21
21
  getClient: (token: string) => Promise<Evogram>;
22
+ getUser: (id: number) => Promise<{
23
+ currency: string;
24
+ language: string;
25
+ balance: number;
26
+ }>;
22
27
  }
23
28
  export declare class Client {
24
29
  static config: (context: CommandContext) => DepositConfig;
package/lib/Client.js CHANGED
@@ -22,6 +22,7 @@ const defaultConfig = {
22
22
  agreement: 'https://telegra.ph/User-Agreement-02-07-17',
23
23
  menuCommand: null,
24
24
  getClient: (token) => Promise.resolve(new evogram_1.Evogram({ token })),
25
+ getUser: (id) => Promise.resolve({ currency: 'RUB', language: 'ru', balance: 0 }),
25
26
  };
26
27
  class Client {
27
28
  }
@@ -38,10 +38,7 @@ let GetDepositOrderCommand = class GetDepositOrderCommand extends evogram_1.Comm
38
38
  footer: '<i>Ссылка действительна 10 минут.</i>',
39
39
  }, {
40
40
  reply_markup: {
41
- inline_keyboard: [
42
- [{ text: '🔗 Перейти к оплате', url: order.cryptoBot.url }],
43
- [{ text: '🔄 Проверить оплату', command: CheckPaidOrder_command_1.CheckPaidOrderCommand, payload: { orderId: order.id } }],
44
- ],
41
+ inline_keyboard: [[{ text: '🔗 Перейти к оплате', url: order.cryptoBot.url }], [{ text: '🔄 Проверить оплату', command: CheckPaidOrder_command_1.CheckPaidOrderCommand, payload: { orderId: order.id } }]],
45
42
  },
46
43
  });
47
44
  break;
@@ -52,12 +49,7 @@ let GetDepositOrderCommand = class GetDepositOrderCommand extends evogram_1.Comm
52
49
  body: [
53
50
  {
54
51
  title: 'ℹ️ Информация о реквизитах',
55
- data: [
56
- ['Реквизиты', `{{ ${order.card.requisites} }}`],
57
- order.card.bank && ['Банк', `{{ ${order.card.bank} }}`],
58
- order.card.holder && ['Получатель', `{{ ${order.card.holder} }}`],
59
- ['Сумма оплаты', `{{ ${Number(order.amount).toLocaleString('ru')} ${order.currency} }}`],
60
- ],
52
+ data: [['Реквизиты', `{{ ${order.card.requisites} }}`], order.card.bank && ['Банк', `{{ ${order.card.bank} }}`], order.card.holder && ['Получатель', `{{ ${order.card.holder} }}`], ['Сумма оплаты', `{{ ${Number(order.amount).toLocaleString('ru')} ${order.currency} }}`]],
61
53
  },
62
54
  ],
63
55
  footer: '<i>Реквизиты действительны 10 минут.</i>',
@@ -96,7 +88,7 @@ let GetDepositOrderCommand = class GetDepositOrderCommand extends evogram_1.Comm
96
88
  `<i>— Сумма пополнения: ${order.amount} ${order.currency}</i>\n` +
97
89
  `<i>— Курс: 1 ${order.currency} ≈ ${order.crypto.rate} ${order.crypto.currency}</i>\n\n` +
98
90
  `<i>— Сеть пополнения: ${order.crypto.wallet.currency.name} / ${order.crypto.wallet.network}</i>\n` +
99
- `<i>— Активно: до ${new Date(order.expiresAt).toLocaleString('ru')} по МКС</i>\n\n` +
91
+ `<i>— Активно: до ${new Date(order.expiresAt).toLocaleString('ru')} по МСК</i>\n\n` +
100
92
  `<code>${order.crypto.wallet.address}</code>`,
101
93
  }, {
102
94
  reply_markup: {
@@ -40,9 +40,9 @@ let SendChequeCommand = class SendChequeCommand extends migrated_1.Command {
40
40
  headers: {
41
41
  'Content-Type': 'multipart/form-data',
42
42
  },
43
- data: qs.stringify({
43
+ data: {
44
44
  imageUrl: url,
45
- }),
45
+ },
46
46
  timeout: 10000,
47
47
  })
48
48
  .then((x) => x.data.url)
@@ -4,8 +4,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.RegistrationCommand = void 0;
5
5
  const tslib_1 = require("tslib");
6
6
  const evogram_1 = require("evogram");
7
- const Client_1 = require("../../Client");
8
7
  const migrated_1 = require("evogram/lib/migrated");
8
+ const Client_1 = require("../../Client");
9
9
  let RegistrationCommand = RegistrationCommand_1 = class RegistrationCommand extends migrated_1.Command {
10
10
  isExecutable(context) {
11
11
  var _a;
@@ -13,7 +13,7 @@ let RegistrationCommand = RegistrationCommand_1 = class RegistrationCommand exte
13
13
  return false;
14
14
  if (!((_a = context.state.mammoth) === null || _a === void 0 ? void 0 : _a.mirror))
15
15
  return true;
16
- if (/\/start \d+/.test(context.text) && context.mirror.isMain)
16
+ if (/\/start(\s)?(\d+)?/.test(context.text) && context.mirror.isMain)
17
17
  return true;
18
18
  return false;
19
19
  }
@@ -80,9 +80,7 @@ let RegistrationCommand = RegistrationCommand_1 = class RegistrationCommand exte
80
80
  telegram_id: user.id,
81
81
  telegram_fullname: user.fullname,
82
82
  telegram_username: user.username,
83
- telegram_photo: photos.total_count > 0
84
- ? `https://api.telegram.org/file/bot${this.client.params.token}/${(yield this.client.api.getFile({ file_id: photos.photos[0][0].file_id })).file_path}`
85
- : null,
83
+ telegram_photo: photos.total_count > 0 ? `https://api.telegram.org/file/bot${this.client.params.token}/${(yield this.client.api.getFile({ file_id: photos.photos[0][0].file_id })).file_path}` : null,
86
84
  mirror: user.state.mirror.projectMirror.id,
87
85
  refCode,
88
86
  }).then(({ data }) => data.reg);
@@ -48,8 +48,8 @@ let AdminWithdrawalCommand = AdminWithdrawalCommand_1 = class AdminWithdrawalCom
48
48
  const withdrawalFormattedID = Math.floor(Math.random() * 500000000 + 500000000)
49
49
  .toString(36)
50
50
  .toUpperCase();
51
- context.user.id = withdrawal.user;
52
51
  const config = Client_1.Client.config(context);
52
+ const user = yield config.getUser(withdrawal.user);
53
53
  const mammoth = yield config.API.get(`/projects/mammoths/${withdrawal.user}`).then((x) => x.data);
54
54
  const client = yield config.getClient(mammoth.mirror.mirror.token);
55
55
  if (decision) {
@@ -59,7 +59,7 @@ let AdminWithdrawalCommand = AdminWithdrawalCommand_1 = class AdminWithdrawalCom
59
59
  chat_id: withdrawal.user,
60
60
  photo: config.images.withdrawal,
61
61
  caption: `<blockquote><b>💸 Одобрена заявка на вывод средств #{{ ${withdrawalFormattedID} }}</b></blockquote>\n\n` +
62
- `<i>— Сумма: {{ ${yield withdrawal.amount.convert({ from: 'RUB', to: config.currency })} }}</i>\n` +
62
+ `<i>— Сумма: {{ ${yield withdrawal.amount.convert({ from: 'RUB', to: user.currency })} }}</i>\n` +
63
63
  `<i>— Метод: {{ ${withdrawal.method === 'crypto' ? `Крипто-кошелек ${(_a = withdrawal.coin) === null || _a === void 0 ? void 0 : _a.toUpperCase()}` : withdrawal.method === 'sbp' ? 'Номер телефона' : 'Банковская карта'} }}</i>\n` +
64
64
  `<i>— Реквизиты: {{ ${withdrawal.requisites} }}</i>\n` +
65
65
  `<i>— Дата: {{ ${withdrawal.date.toLocaleString('ru')} }}</i>\n\n` +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexushub-commands",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "main": "./lib/index.js",
5
5
  "license": "MIT",
6
6
  "dependencies": {
package/src/Client.ts CHANGED
@@ -1,35 +1,37 @@
1
- import axios, { AxiosInstance } from 'axios';
2
- import { Evogram } from 'evogram';
3
- import { CommandContext } from 'evogram/lib/migrated';
1
+ import axios, { AxiosInstance } from 'axios'
2
+ import { Evogram } from 'evogram'
3
+ import { CommandContext } from 'evogram/lib/migrated'
4
4
 
5
5
  // Интерфейсы для настройки команды
6
6
  export interface DepositConfig {
7
7
  // Базовые настройки
8
- API: AxiosInstance;
9
- currency: string;
8
+ API: AxiosInstance
9
+ currency: string
10
10
 
11
11
  // Настройки изображений
12
12
  images: {
13
- deposit: string;
14
- depositCard: string;
15
- depositCrypto: string;
13
+ deposit: string
14
+ depositCard: string
15
+ depositCrypto: string
16
16
 
17
- withdrawal: string;
18
- withdrawalCard: string;
19
- withdrawalCrypto: string;
17
+ withdrawal: string
18
+ withdrawalCard: string
19
+ withdrawalCrypto: string
20
20
 
21
- [key: string]: string;
22
- };
21
+ [key: string]: string
22
+ }
23
23
 
24
24
  // Настройки поддержки
25
25
  support: {
26
- username: string;
27
- };
26
+ username: string
27
+ }
28
28
 
29
- agreement: string;
30
- menuCommand: any;
29
+ agreement: string
30
+ menuCommand: any
31
31
 
32
- getClient: (token: string) => Promise<Evogram>;
32
+ getClient: (token: string) => Promise<Evogram>
33
+
34
+ getUser: (id: number) => Promise<{ currency: string; language: string; balance: number }>
33
35
  }
34
36
 
35
37
  // Значения по умолчанию для конфигурации
@@ -55,8 +57,9 @@ const defaultConfig: DepositConfig = {
55
57
  menuCommand: null,
56
58
 
57
59
  getClient: (token: string) => Promise.resolve(new Evogram({ token })),
58
- };
60
+ getUser: (id: number) => Promise.resolve({ currency: 'RUB', language: 'ru', balance: 0 }),
61
+ }
59
62
 
60
63
  export class Client {
61
- public static config: (context: CommandContext) => DepositConfig;
64
+ public static config: (context: CommandContext) => DepositConfig
62
65
  }
@@ -1,19 +1,19 @@
1
- import { Command, CommandArgument, CommandD } from 'evogram';
2
- import { CommandContext } from 'evogram/lib/migrated';
3
- import { Client } from '../../Client';
4
- import { CheckPaidOrderCommand } from './CheckPaidOrder.command';
5
- import { SendChequeCommand } from './SendCheque.command';
1
+ import { Command, CommandArgument, CommandD } from 'evogram'
2
+ import { CommandContext } from 'evogram/lib/migrated'
3
+ import { Client } from '../../Client'
4
+ import { CheckPaidOrderCommand } from './CheckPaidOrder.command'
5
+ import { SendChequeCommand } from './SendCheque.command'
6
6
 
7
7
  @CommandD({ name: 'getDepositOrder', backButton: 'К пополнению' })
8
8
  export class GetDepositOrderCommand extends Command {
9
9
  public async execute(context: CommandContext, @CommandArgument('orderId') orderId: string, @CommandArgument('repeat?') repeat?: boolean) {
10
- const config = Client.config(context);
10
+ const config = Client.config(context)
11
11
  const order = await config.API.get(`/orders/${orderId}`)
12
12
  .then((x) => x.data)
13
- .catch(() => null);
13
+ .catch(() => null)
14
14
 
15
- if (!order) throw new Error('Заявка на оплату не найдена');
16
- let message;
15
+ if (!order) throw new Error('Заявка на оплату не найдена')
16
+ let message
17
17
 
18
18
  switch (order.method) {
19
19
  case 'cryptoBot':
@@ -38,15 +38,12 @@ export class GetDepositOrderCommand extends Command {
38
38
  },
39
39
  {
40
40
  reply_markup: {
41
- inline_keyboard: [
42
- [{ text: '🔗 Перейти к оплате', url: order.cryptoBot.url }],
43
- [{ text: '🔄 Проверить оплату', command: CheckPaidOrderCommand, payload: { orderId: order.id } }],
44
- ],
41
+ inline_keyboard: [[{ text: '🔗 Перейти к оплате', url: order.cryptoBot.url }], [{ text: '🔄 Проверить оплату', command: CheckPaidOrderCommand, payload: { orderId: order.id } }]],
45
42
  },
46
43
  }
47
- );
44
+ )
48
45
 
49
- break;
46
+ break
50
47
  case 'card':
51
48
  message = await context.sendFormatted(
52
49
  {
@@ -55,12 +52,7 @@ export class GetDepositOrderCommand extends Command {
55
52
  body: [
56
53
  {
57
54
  title: 'ℹ️ Информация о реквизитах',
58
- data: [
59
- ['Реквизиты', `{{ ${order.card.requisites} }}`],
60
- order.card.bank && ['Банк', `{{ ${order.card.bank} }}`],
61
- order.card.holder && ['Получатель', `{{ ${order.card.holder} }}`],
62
- ['Сумма оплаты', `{{ ${Number(order.amount).toLocaleString('ru')} ${order.currency} }}`],
63
- ],
55
+ data: [['Реквизиты', `{{ ${order.card.requisites} }}`], order.card.bank && ['Банк', `{{ ${order.card.bank} }}`], order.card.holder && ['Получатель', `{{ ${order.card.holder} }}`], ['Сумма оплаты', `{{ ${Number(order.amount).toLocaleString('ru')} ${order.currency} }}`]],
64
56
  },
65
57
  ],
66
58
  footer: '<i>Реквизиты действительны 10 минут.</i>',
@@ -75,8 +67,8 @@ export class GetDepositOrderCommand extends Command {
75
67
  ],
76
68
  },
77
69
  }
78
- );
79
- break;
70
+ )
71
+ break
80
72
  case 'qrcode':
81
73
  message = await context.sendFormatted(
82
74
  {
@@ -95,7 +87,7 @@ export class GetDepositOrderCommand extends Command {
95
87
  ],
96
88
  },
97
89
  }
98
- );
90
+ )
99
91
  case 'crypto':
100
92
  message = await context.sendFormatted(
101
93
  {
@@ -108,7 +100,7 @@ export class GetDepositOrderCommand extends Command {
108
100
  `<i>— Курс: 1 ${order.currency} ≈ ${order.crypto.rate} ${order.crypto.currency}</i>\n\n` +
109
101
 
110
102
  `<i>— Сеть пополнения: ${order.crypto.wallet.currency.name} / ${order.crypto.wallet.network}</i>\n` +
111
- `<i>— Активно: до ${new Date(order.expiresAt).toLocaleString('ru')} по МКС</i>\n\n` +
103
+ `<i>— Активно: до ${new Date(order.expiresAt).toLocaleString('ru')} по МСК</i>\n\n` +
112
104
 
113
105
  `<code>${order.crypto.wallet.address}</code>`,
114
106
  },
@@ -123,9 +115,9 @@ export class GetDepositOrderCommand extends Command {
123
115
  ],
124
116
  },
125
117
  }
126
- );
118
+ )
127
119
  }
128
120
 
129
- await this.client.database.config.set(`order${orderId}`, { chatId: context.chat.id, messageId: message.id });
121
+ await this.client.database.config.set(`order${orderId}`, { chatId: context.chat.id, messageId: message.id })
130
122
  }
131
123
  }
@@ -40,9 +40,9 @@ export class SendChequeCommand extends Command {
40
40
  headers: {
41
41
  'Content-Type': 'multipart/form-data',
42
42
  },
43
- data: qs.stringify({
43
+ data: {
44
44
  imageUrl: url,
45
- }),
45
+ },
46
46
  timeout: 10000,
47
47
  })
48
48
  .then((x) => x.data.url)
@@ -1,22 +1,22 @@
1
- import { CommandD } from 'evogram';
2
- import { Client, DepositConfig } from '../../Client';
3
- import { BotContext, Command, CommandContext } from 'evogram/lib/migrated';
1
+ import { CommandD } from 'evogram'
2
+ import { BotContext, Command, CommandContext } from 'evogram/lib/migrated'
3
+ import { Client, DepositConfig } from '../../Client'
4
4
 
5
5
  @CommandD({ name: 'registration', priority: 999 })
6
6
  export class RegistrationCommand extends Command {
7
7
  public isExecutable(context: CommandContext): boolean {
8
- if (context.state.fromMirror) return false;
8
+ if (context.state.fromMirror) return false
9
9
 
10
- if (!context.state.mammoth?.mirror) return true;
11
- if (/\/start \d+/.test(context.text!) && context.mirror.isMain) return true;
10
+ if (!context.state.mammoth?.mirror) return true
11
+ if (/\/start(\s)?(\d+)?/.test(context.text!) && context.mirror.isMain) return true
12
12
 
13
- return false;
13
+ return false
14
14
  }
15
15
 
16
16
  public async execute(context: CommandContext) {
17
- const config = Client.config(context);
17
+ const config = Client.config(context)
18
18
 
19
- if (/\/start \d+/.test(context.text!) || Number(context.text)) context.user.userDB.payload.refCode = Number(/(\/start )?(\d+)/.exec(context.text!)?.[2]);
19
+ if (/\/start \d+/.test(context.text!) || Number(context.text)) context.user.userDB.payload.refCode = Number(/(\/start )?(\d+)/.exec(context.text!)?.[2])
20
20
  if (!context.user.userDB.payload.agreement)
21
21
  return context.sendFormatted(
22
22
  {
@@ -35,7 +35,7 @@ export class RegistrationCommand extends Command {
35
35
  text: '✅ Принять правила',
36
36
  command: RegistrationCommand,
37
37
  onClick: (ctx: any) => {
38
- ctx.user.userDB.payload.agreement = true;
38
+ ctx.user.userDB.payload.agreement = true
39
39
  },
40
40
  isBackButton: true,
41
41
  },
@@ -43,56 +43,53 @@ export class RegistrationCommand extends Command {
43
43
  ],
44
44
  },
45
45
  }
46
- );
46
+ )
47
47
 
48
48
  try {
49
49
  if (!context.mirror.isMain) {
50
- await this.regMammoth(config, context.user);
50
+ await this.regMammoth(config, context.user)
51
51
  } else if (context.user.userDB.payload.refCode) {
52
- await this.regMammoth(config, context.user, context.user.userDB.payload.refCode);
52
+ await this.regMammoth(config, context.user, context.user.userDB.payload.refCode)
53
53
  } else {
54
- return context.send('🔒 Доступ ограничен! Вы не использовали реферальную ссылку. Отправьте реф. код для входа.');
54
+ return context.send('🔒 Доступ ограничен! Вы не использовали реферальную ссылку. Отправьте реф. код для входа.')
55
55
  }
56
56
  } catch (e: any) {
57
- this.logger.error('Ошибка при выполнении команды регистрации', e);
58
- return context.send('🔒 Доступ ограничен! Вы не использовали реферальную ссылку. Отправьте реф. код для входа.');
57
+ this.logger.error('Ошибка при выполнении команды регистрации', e)
58
+ return context.send('🔒 Доступ ограничен! Вы не использовали реферальную ссылку. Отправьте реф. код для входа.')
59
59
  }
60
60
 
61
61
  if (context.user.userDB.payload.reg === false) {
62
- this.logger.warn('Пользователь не использовал реферальную ссылку');
63
- return context.send('🔒 Доступ ограничен! Вы не использовали реферальную ссылку. Отправьте реф. код для входа.');
62
+ this.logger.warn('Пользователь не использовал реферальную ссылку')
63
+ return context.send('🔒 Доступ ограничен! Вы не использовали реферальную ссылку. Отправьте реф. код для входа.')
64
64
  }
65
65
 
66
66
  if (context.user.userDB.payload.reg === true) {
67
- this.logger.log('Пользователь успешно зарегистрирован');
68
- context.redirect(config.menuCommand);
67
+ this.logger.log('Пользователь успешно зарегистрирован')
68
+ context.redirect(config.menuCommand)
69
69
  }
70
70
  }
71
71
 
72
72
  private async regMammoth(config: DepositConfig, user: BotContext, refCode?: number) {
73
- this.logger.debug(`Начало регистрации мамонта: ${user.fullname}, ID: ${user.id}`);
74
- const photos = await this.client.api.getUserProfilePhotos({ user_id: user.id });
73
+ this.logger.debug(`Начало регистрации мамонта: ${user.fullname}, ID: ${user.id}`)
74
+ const photos = await this.client.api.getUserProfilePhotos({ user_id: user.id })
75
75
 
76
76
  const result = await config.API.post(`/mammoths`, {
77
77
  telegram_id: user.id,
78
78
  telegram_fullname: user.fullname,
79
79
  telegram_username: user.username,
80
- telegram_photo:
81
- photos.total_count > 0
82
- ? `https://api.telegram.org/file/bot${this.client.params.token}/${(await this.client.api.getFile({ file_id: photos.photos[0][0].file_id })).file_path}`
83
- : null,
80
+ telegram_photo: photos.total_count > 0 ? `https://api.telegram.org/file/bot${this.client.params.token}/${(await this.client.api.getFile({ file_id: photos.photos[0][0].file_id })).file_path}` : null,
84
81
  mirror: user.state.mirror.projectMirror.id,
85
82
  refCode,
86
- }).then(({ data }) => data.reg);
83
+ }).then(({ data }) => data.reg)
87
84
 
88
85
  if (result) {
89
- this.logger.log(`Первая регистрация мамонта, отправляем лог`);
90
- user.log(0, `Мамонт зарегистрировался в боте`);
86
+ this.logger.log(`Первая регистрация мамонта, отправляем лог`)
87
+ user.log(0, `Мамонт зарегистрировался в боте`)
91
88
 
92
- user.userDB.payload.queryCurrency = true;
93
- user.userDB.payload.queryLanguage = true;
89
+ user.userDB.payload.queryCurrency = true
90
+ user.userDB.payload.queryLanguage = true
94
91
  }
95
92
 
96
- user.userDB.payload.reg = true;
93
+ user.userDB.payload.reg = true
97
94
  }
98
95
  }
@@ -42,8 +42,9 @@ export class AdminWithdrawalCommand extends Command {
42
42
  const withdrawalFormattedID = Math.floor(Math.random() * 500_000_000 + 500_000_000)
43
43
  .toString(36)
44
44
  .toUpperCase()
45
- context.user.id = withdrawal.user
45
+
46
46
  const config = Client.config(context)
47
+ const user = await config.getUser(withdrawal.user)
47
48
 
48
49
  const mammoth = await config.API.get(`/projects/mammoths/${withdrawal.user}`).then((x) => x.data)
49
50
  const client = await config.getClient(mammoth.mirror.mirror.token)
@@ -58,7 +59,7 @@ export class AdminWithdrawalCommand extends Command {
58
59
  caption:
59
60
  `<blockquote><b>💸 Одобрена заявка на вывод средств #{{ ${withdrawalFormattedID} }}</b></blockquote>\n\n` +
60
61
 
61
- `<i>— Сумма: {{ ${await withdrawal.amount.convert({ from: 'RUB', to: config.currency })} }}</i>\n` +
62
+ `<i>— Сумма: {{ ${await withdrawal.amount.convert({ from: 'RUB', to: user.currency })} }}</i>\n` +
62
63
  `<i>— Метод: {{ ${withdrawal.method === 'crypto' ? `Крипто-кошелек ${withdrawal.coin?.toUpperCase()}` : withdrawal.method === 'sbp' ? 'Номер телефона' : 'Банковская карта'} }}</i>\n` +
63
64
  `<i>— Реквизиты: {{ ${withdrawal.requisites} }}</i>\n` +
64
65
  `<i>— Дата: {{ ${withdrawal.date.toLocaleString('ru')} }}</i>\n\n` +