# commander-core

> command-manager

Latest version **3.0.6** (published 2024-02-05) · MIT license · 0 weekly downloads

## Install

```sh
npm install commander-core
pnpm add commander-core
yarn add commander-core
bun add commander-core
```

## Health

**Score 40/100 (D)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned.

## Facts

| | |
|---|---|
| Version | 3.0.6 |
| Published | 2024-02-05 |
| First published | 2020-06-22 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=14.17 |
| Dependencies | 2 |
| Unpacked size | 42.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 3 |
| Author | Frodi1998 |
| Maintainers | frodi |
| Keywords | node, handler, commander-core, commander, bot-handler, core, bot, vk-bot, tg-bot |

## Links

- npm: https://www.npmjs.com/package/commander-core
- Repository: https://github.com/Frodi1998/commander-core
- Homepage: https://github.com/Frodi1998/commander-core#readme
- Issues: https://github.com/Frodi1998/commander-core/issues
- npm.io page: https://npm.io/package/commander-core

## Dependencies (2)

- [debug](https://npm.io/package/debug.md) ^4.3.4
- [walk-sync](https://npm.io/package/walk-sync.md) ^3.0.0

## Alternatives

- [@expo/fingerprint](https://npm.io/package/@expo/fingerprint.md) — 6.2M weekly downloads
- [@azure/monitor-opentelemetry-exporter](https://npm.io/package/@azure/monitor-opentelemetry-exporter.md) — 850.0K weekly downloads
- [@azure/monitor-opentelemetry](https://npm.io/package/@azure/monitor-opentelemetry.md) — 624.0K weekly downloads
- [@posthog/ai](https://npm.io/package/@posthog/ai.md) — 423.3K weekly downloads
- [fakefilter](https://npm.io/package/fakefilter.md) — 63.9K weekly downloads

## Recent versions

- 3.0.6 (latest) — 2024-02-05
- 3.0.7-beta.1 (beta) — 2024-02-29
- 3.0.5 — 2022-12-09
- 3.0.4 — 2022-12-09
- 3.0.4-beta.0 — 2022-12-08
- 3.0.3 — 2022-11-11
- 3.0.2 — 2021-12-04
- 3.0.1 — 2021-10-08
- 3.0.0 — 2021-10-03
- 2.2.1 — 2021-08-19
- 2.2.0-rc.1 — 2021-08-19
- 2.1.2 — 2021-07-28
- 2.1.1-rc.1 — 2021-07-26
- 2.1.0-rc.1 — 2021-07-08
- 2.1.0 — 2021-06-02
- … 17 more at https://npm.io/package/commander-core/versions

## README

<p align="center">
<a href="https://www.npmjs.com/package/commander-core"><img src="https://img.shields.io/npm/v/commander-core.svg?style=flat-square" alt="NPM version"></a>
<a href="https://www.npmjs.com/package/commander-core"><img src="https://img.shields.io/npm/dt/commander-core.svg?style=flat-square" alt="NPM downloads"></a>
</p>

commander-core - это ядро для вашего обработчика команд, основан на [cocoscore](https://www.npmjs.com/package/cocoscore).
Модуль поддерживает:

- [vk-io](https://www.npmjs.com/package/vk-io)
- [puregram](https://www.npmjs.com/package/puregram)

| 📚 [Документация](https://frodi1998.github.io/commander-core/) | 📝 [Примеры](https://github.com/Frodi1998/commander-core/tree/master/examples) | 💬 [Беседа](https://vk.me/join/AJQ1d9IUCxhdW8s6imiygUU1) |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------- |

Установка

## NPM

```shell
npm i commander-core
```

## Yarn

```shell
yarn add commander-core
```

# Использование

Пример основан на [vk-io](https://www.npmjs.com/package/vk-io), вы можете использовать другое
Сначало необходимо проинициализировать ваш проект

# JavaScript

далее в корне проекта создайте файл utils.js
поместите туда следующий код

```js
const { UtilsCore } = require('commander-core');
/**
 * класс утилит, понадобится для использования своих методов и констант в командах
 * bot.testMetods() в теле команды
 */
class Utils extends UtilsCore {
  constructor() {
    super();
    this.adminIds = [1];
  }

  testMetods() {
    return console.log('test');
  }
} // это произвольный пример, можете поместить сюда что угодно

module.exports = Utils;
```

далее создайте файл start.js

```js
const { Handler } = require('commander-core')
const { VK, getRandomId } = require('vk-io')
const path = require('node:path')
const Utils = require('./utils.js') //наши утилиты

const TOKEN = process.env.TOKEN //токен от группы
const vk = new VK({token: TOKEN})

const handler = new Handler({
	commands: {
		directory: path.resolve(__dirname, 'commands')
		// fromArray: [commands] //массив команд, используйте только один из двух методов загрузки команд
	}
	strictLoader: true, //строгость загрузки (проверяет есть ли команды иначе кидает ошибку)
	utils: new Utils() //загружаем наши утилиты в класс обработчика
});

handler.events.on('command_error', async({context, utils, error}) =>{
	context.send(`Произошла непредвиденная ошибка`)
	if(utils.adminIds) {
		vk.api.messages.send({
			user_ids: utils.adminIds,
			random_id: getRandomId(),
			message: `Ошибка в команде ${utils.getCommand.name}:
				${context.senderId} => ${context.$command}
				${error.stack}`
		})
	}
}); //событие срабатывания ошибок в команде

handler.events.on('command_not_found', async({context}) =>{
	if(!context.isChat) {
		context.send(`Введенной вами команды не существует!`)
	}
}); //событие при отсутствие подходящей команды

handler.loadCommands()
.then(() => console.log('commands loaded')) // загружает команды
.catch(err => console.error(err)) // обязательно обрабатывайте ошибку

vk.updates.on('message_new', async(context, next) => {
	context.text = context.text.replace(/^\[club(\d+)\|(.*)\]/i, '').trim();

	await handler.execute(context);
});

vk.updates.start()
.then(() => console.log('Старт'));
```

далее создаем папку commands
внутри папки создаем файл test.js

```js
//здесь и будет код команды
const { Command } = require('commander-core');

//по желанию вы можете объявить тут массив из команд
module.exports = new Command({
  pattern: /^(?:тест|test)$/i,
  name: 'тест',
  description: 'тестирование',

  handler(context, bot) {
    bot.testMetods(); //созданная нами утилита в файле utils.js
    context.send('тест');
  },
});
```

# TypeScript

далее в корне проекта создайте файл utils.ts
поместите туда следующий код

```ts
import { UtilsCore } from 'commander-core';
/**
 * класс утилит, понадобится для использования своих методов и констант в командах
 * bot.testMetods() в теле команды
 */
export class Utils extends UtilsCore {
  public adminIds = [1];

  testMetods(): void {
    return console.log('test');
  }
} // это произвольный пример, можете поместить сюда что угодно
```

далее создайте файл start.ts

```ts
import { Handler, IContext } from 'commander-core';
import { VK, getRandomId, MessageContext } from 'vk-io';
import path from 'node:path';

import Utils from './utils.js'; //наши утилиты

interface IListener {
	context: MessageContext & IContext;
	utils: Utils;
	error?: Error;
}

const TOKEN = process.env.TOKEN //токен от группы
const vk = new VK({token: TOKEN})

const handler = new Handler({
	commands: {
		directory: path.resolve(__dirname, 'commands') //директория команд
		// fromArray: [commands] //массив команд, используйте только один из двух методов загрузки команд
	}
	strictLoader: true, //строгость загрузки (проверяет есть ли команды иначе кидает ошибку)
	utils: new Utils() //загружаем наши утилиты в класс обработчика
});

handler.events.on('command_error', async({context, utils, error}: IListener) =>{
	context.send(`Произошла непредвиденная ошибка`)
	if(utils.adminIds) {
		vk.api.messages.send({
			user_ids: utils.adminIds,
			random_id: getRandomId(),
			message: `Ошибка в команде ${utils.getCommand.name}:
				${context.senderId} => ${context.$command}
				${error.stack}`
		})
	}
}); //событие срабатывания ошибок в команде

handler.events.on('command_not_found', async({context}: IListener) =>{
	if(!context.isChat) {
		context.send(`Введенной вами команды не существует!`)
	}
}); //событие при отсутствие подходящей команды

handler.loadCommands()
.then(() => console.log('commands loaded')) // загружает команды
.catch(err => console.error(err)) // обязательно обрабатывайте ошибку

vk.updates.on('message_new', async(context, next) => {
	context.text = context.text.replace(/^\[club(\d+)\|(.*)\]/i, '').trim();

	await handler.execute(context);
});

vk.updates.start()
.then(() => console.log('Старт'));
```

далее создаем папку commands
внутри папки создаем файл test.ts

```js
//здесь и будет код команды
import { Command, IContext } from 'commander-core';
import { Utils } from '../utils';
import { MessageContext } from 'vk-io';

//по желанию вы можете объявить тут массив из команд
export default new Command({
  pattern: /^(?:тест|test)$/i,
  name: 'тест',
  description: 'тестирование',

  handler(context: MessageContext & IContext, bot: Utils) {
    bot.testMetods(); //созданная нами утилита в файле utils.js
    context.send('тест');
  },
});
```

---
_Source: https://npm.io/package/commander-core · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
