docs: add versioned docs (#1)

This commit is contained in:
Maxim Slipenko 2023-07-23 15:28:11 +03:00 committed by GitHub
parent 7c8d746863
commit 25bd4bb4ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 1379 additions and 5683 deletions

View File

@ -1,8 +1,8 @@
module.exports = { module.exports = {
parser: '@typescript-eslint/parser', parser: '@typescript-eslint/parser',
parserOptions: { parserOptions: {
project: 'tsconfig.json', // project: 'tsconfig.json',
sourceType: 'module', // sourceType: 'module',
}, },
plugins: ['@typescript-eslint/eslint-plugin'], plugins: ['@typescript-eslint/eslint-plugin'],
extends: [ extends: [

View File

@ -6,7 +6,7 @@ slug: /
--- ---
```bash ```bash
$ npm i nestjs-telegraf telegraf $ npm i maks1ms nestjs-telegraf telegraf
``` ```
Once the installation process is complete, we can import the `TelegrafModule` into the root `AppModule`. Once the installation process is complete, we can import the `TelegrafModule` into the root `AppModule`.

View File

@ -1,18 +1,28 @@
function getNextVersionName() {
return 'Canary';
}
const BASE_GH_URL = 'https://github.com/maks1ms/nestjs-telegraf';
module.exports = { module.exports = {
title: 'NestJS Telegraf', title: 'NestJS Telegraf',
tagline: 'Powerful Nest module for easy and fast creation Telegram bots', tagline: 'Powerful Nest module for easy and fast creation Telegram bots',
url: 'https://nestjs-telegraf.hypeer.company', url: 'https://nestjs-telegraf-maks1ms.vercel.app',
baseUrl: '/', baseUrl: '/',
onBrokenLinks: 'throw', onBrokenLinks: 'throw',
favicon: 'img/favicon.ico', favicon: 'img/favicon.ico',
organizationName: 'hypeertech', organizationName: 'maks1ms',
projectName: 'nestjs-telegraf', projectName: 'nestjs-telegraf',
themeConfig: { themeConfig: {
navbar: { navbar: {
title: 'NestJS Telegraf', title: 'NestJS Telegraf',
items: [ items: [
{ {
href: 'https://github.com/hypeertech/nestjs-telegraf', type: 'docsVersionDropdown',
position: 'right',
},
{
href: BASE_GH_URL,
label: 'GitHub', label: 'GitHub',
position: 'right', position: 'right',
}, },
@ -35,11 +45,7 @@ module.exports = {
items: [ items: [
{ {
label: 'Discussions', label: 'Discussions',
href: 'https://github.com/hypeertech/nestjs-telegraf/discussions', href: `${BASE_GH_URL}/discussions`,
},
{
label: 'Telegram',
href: 'https://t.me/nestjs_telegraf',
}, },
], ],
}, },
@ -48,16 +54,17 @@ module.exports = {
items: [ items: [
{ {
label: 'Issues', label: 'Issues',
href: 'https://github.com/hypeertech/nestjs-telegraf/issues', href: `${BASE_GH_URL}/issues`,
}, },
{ {
label: 'Examples', label: 'Examples',
to: 'https://github.com/hypeertech/nestjs-telegraf/tree/master/sample/', to: `${BASE_GH_URL}/tree/master/sample/`,
} },
], ],
}, },
], ],
copyright: `Copyright © 2019 - ${new Date().getFullYear()}, <a target="_blank" href="https://hypeer.company">Hypeer</a>, <a target="_blank" href="mailto:arthur.asimov.z0@gmail.com">Arthur Asimov</a> and <a target="_blank" href="https://github.com/bukhalo/nestjs-telegraf/graphs/contributors">Others</a>.`, copyright: `Copyright © 2019 - 2023 <a target="_blank" href="https://hypeer.company">Hypeer</a>, <a target="_blank" href="mailto:arthur.asimov.z0@gmail.com">Arthur Asimov</a> and <a target="_blank" href="https://github.com/hypeertech/nestjs-telegraf/graphs/contributors">Others</a>.<br>
Copyright 2023 - <a target="_blank" href="https://github.com/Maks1mS">Maks1mS</a> and <a target="_blank" href="${BASE_GH_URL}/graphs/contributors">Others</a>`,
}, },
}, },
presets: [ presets: [
@ -67,10 +74,17 @@ module.exports = {
docs: { docs: {
sidebarPath: require.resolve('./sidebars.js'), sidebarPath: require.resolve('./sidebars.js'),
routeBasePath: '/', routeBasePath: '/',
editUrl: editUrl: ({ docPath }) => {
'https://github.com/hypeertech/nestjs-telegraf/edit/master/website/', const nextVersionDocsDirPath = 'docs';
return `${BASE_GH_URL}/edit/main/website/${nextVersionDocsDirPath}/${docPath}`;
},
showLastUpdateAuthor: true, showLastUpdateAuthor: true,
showLastUpdateTime: true, showLastUpdateTime: true,
versions: {
current: {
label: `${getNextVersionName()} 🚧`,
},
},
}, },
theme: { theme: {
customCss: require.resolve('./src/css/custom.css'), customCss: require.resolve('./src/css/custom.css'),
@ -78,12 +92,4 @@ module.exports = {
}, },
], ],
], ],
plugins: [
[
require.resolve('docusaurus-gtm-plugin'),
{
id: 'GTM-PRP5KRP',
}
]
],
}; };

6608
website/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -11,8 +11,8 @@
"serve": "docusaurus serve" "serve": "docusaurus serve"
}, },
"dependencies": { "dependencies": {
"@docusaurus/core": "2.2.0", "@docusaurus/core": "2.4.1",
"@docusaurus/preset-classic": "2.1.0", "@docusaurus/preset-classic": "2.4.1",
"@mdx-js/react": "1.6.22", "@mdx-js/react": "1.6.22",
"clsx": "1.1.1", "clsx": "1.1.1",
"docusaurus-gtm-plugin": "^0.0.2", "docusaurus-gtm-plugin": "^0.0.2",
@ -32,7 +32,7 @@
] ]
}, },
"devDependencies": { "devDependencies": {
"@docusaurus/module-type-aliases": "2.2.0", "@docusaurus/module-type-aliases": "2.4.1",
"@tsconfig/docusaurus": "1.0.6", "@tsconfig/docusaurus": "1.0.6",
"@types/react": "17.0.39", "@types/react": "17.0.39",
"@types/react-helmet": "6.1.5", "@types/react-helmet": "6.1.5",

View File

@ -1,4 +1,4 @@
{ {
"extends": "@tsconfig/docusaurus/tsconfig.json", "extends": "@tsconfig/docusaurus/tsconfig.json",
"include": ["src/"] "exclude": ["src/sw.js"]
} }

View File

@ -0,0 +1,60 @@
---
id: async-configuration
title: Async configuration
sidebar_label: Async configuration
slug: /async-configuration
---
When you need to pass module options asynchronously instead of statically, use the forRootAsync() method. As with most dynamic modules, Nest provides several techniques to deal with async configuration.
One technique is to use a factory function:
```typescript
TelegrafModule.forRootAsync({
useFactory: () => ({
token: 'TELEGRAM_BOT_TOKEN',
}),
});
```
Like other [factory providers](https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory), our factory function can be async and can inject dependencies through inject.
```typescript
TelegrafModule.forRootAsync({
imports: [ConfigModule.forFeature(telegrafModuleConfig)],
useFactory: async (configService: ConfigService) => ({
token: configService.get<string>('TELEGRAM_BOT_TOKEN'),
}),
inject: [ConfigService],
});
```
Alternatively, you can configure the TelegrafModule using a class instead of a factory, as shown below:
```typescript
TelegrafModule.forRootAsync({
useClass: TelegrafConfigService,
});
```
The construction above instantiates `TelegrafConfigService` inside `TelegrafModule`, using it to create the required options object. Note that in this example, the `TelegrafConfigService` has to implement the `TelegrafOptionsFactory` interface, as shown below. The `TelegrafModule` will call the `createTelegrafOptions()` method on the instantiated object of the supplied class.
```typescript
@Injectable()
class TelegrafConfigService implements TelegrafOptionsFactory {
createTelegrafOptions(): TelegrafModuleOptions {
return {
token: 'TELEGRAM_BOT_TOKEN',
};
}
}
```
If you want to reuse an existing options provider instead of creating a private copy inside the `TelegrafModule`, use the `useExisting` syntax.
```typescript
TelegrafModule.forRootAsync({
imports: [ConfigModule.forFeature(telegrafModuleConfig)],
useExisting: ConfigService,
});
```

View File

@ -0,0 +1,36 @@
---
id: bot-injection
title: Bot injection
sidebar_label: Bot injection
slug: /extras/bot-injection
---
At times you may need to access the native `Telegraf` instance. You can inject the Telegraf by using the `@InjectBot()` decorator as follows:
```typescript {8} title="src/echo/echo.service.ts"
import { Injectable } from '@nestjs/common';
import { InjectBot } from 'nestjs-telegraf';
import { Telegraf } from 'telegraf';
import { TelegrafContext } from '../common/interfaces/telegraf-context.interface.ts';
@Injectable()
export class EchoService {
constructor(@InjectBot() private bot: Telegraf<TelegrafContext>) {}
...
}
```
If you run [multiple bots](/extras/multiple-bots) in the same application, explicitly specify the bot name:
```typescript {8} title="src/echo/echo.service.ts"
import { Injectable } from '@nestjs/common';
import { InjectBot } from 'nestjs-telegraf';
import { Telegraf } from 'telegraf';
import { TelegrafContext } from '../common/interfaces/telegraf-context.interface.ts';
@Injectable()
export class EchoService {
constructor(@InjectBot('cats') private bot: Telegraf<TelegrafContext>) {}
...
}
```

View File

@ -0,0 +1,13 @@
---
id: middlewares
title: Middlewares
sidebar_label: Middlewares
slug: /extras/middlewares
---
`nestjs-telegraf` has support of the Telegraf middleware packages. To use an existing middleware package, simply import it and add it to the middlewares array:
```typescript
TelegrafModule.forRoot({
middlewares: [session()],
}),
```

View File

@ -0,0 +1,74 @@
---
id: multiple-bots
title: Multiple bots
sidebar_label: Multiple bots
slug: /extras/multiple-bots
---
In some cases, you may need to run multiple bots at the same time. This can also be achieved with this module. To work with multiple bots, first create the bots. In this case, bot naming becomes mandatory.
```typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TelegrafModule } from 'nestjs-telegraf';
@Module({
imports: [
ConfigModule.forRoot(),
TelegrafModule.forRootAsync({
imports: [ConfigModule],
botName: 'cat',
useFactory: (configService: ConfigService) => ({
token: configService.get<string>('CAT_BOT_TOKEN'),
}),
inject: [ConfigService],
}),
TelegrafModule.forRootAsync({
imports: [ConfigModule.forFeature(telegrafModuleConfig)],
botName: 'dog',
useFactory: async (configService: ConfigService) => ({
token: configService.get<string>('DOG_BOT_TOKEN'),
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}
```
:::caution
Please note that you shouldn't have multiple bots without a name, or with the same name, otherwise they will get overridden.
:::
You can also inject the `Bot` for a given bot:
```typescript
import { Injectable } from '@nestjs/common';
import { InjectBot, Telegraf, Context } from 'nestjs-telegraf';
@Injectable()
export class EchoService {
constructor(@InjectBot('cat') private catBot: Telegraf<Context>) {}
}
```
To inject a given `Bot` to a custom provider (for example, factory provider), use the `getBotToken()` function passing the name of the bot as an argument.
```typescript
{
provide: CatsService,
useFactory: (catBot: Telegraf<Context>) => {
return new CatsService(catBot);
},
inject: [getBotToken('cat')],
}
```
Another useful feature of the `nestjs-telegraf` module is the ability to choose which modules should handle updates for each launched bot. By default, module searches for handlers throughout the whole app. To limit this scan to only a subset of modules, use the include property.
```typescript
TelegrafModule.forRootAsync({
imports: [ConfigModule],
botName: 'cat',
useFactory: (configService: ConfigService) => ({
token: configService.get<string>('CAT_BOT_TOKEN'),
include: [CatsModule],
}),
inject: [ConfigService],
}),
```

View File

@ -0,0 +1,27 @@
---
id: standalone-applications
title: Standalone applications
sidebar_label: Standalone applications
slug: standalone-applications
---
If you initialized your application with the [Nest CLI](https://docs.nestjs.com/cli/overview), [Express](https://expressjs.com/) framework will be installed by default along with Nest. Nest and NestJS Telegraf does not require Express for work. So if you don't plan to getting bot updates through webhooks, and you don't need a web server, you can remove Express.
To do this, change the `bootstrap` function in the `main.ts` file of your project on something like that:
```typescript
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);
}
bootstrap();
```
This initializes Nest as a **standalone application** (without any network listeners).
All that remains is to remove unused dependencies:
```bash
npm un @nestjs/platform-express @types/express
```
:::info
More information about standalone applications located at [Nest documentation](https://docs.nestjs.com/standalone-applications)
:::

View File

@ -0,0 +1,44 @@
---
id: getting-updates
title: Getting updates
sidebar_label: Getting updates
slug: getting-updates
---
## Long polling
By default, the bot receives updates using long-polling and requires no additional action.
## Webhooks
If you want to configure a telegram bot webhook, you need to get a middleware via `getBotToken` helper in your `main.ts` file.
To access it, you must use the `app.get()` method, followed by the provider reference:
```typescript
import { getBotToken } from 'nestjs-telegraf';
// ...
const bot = app.get(getBotToken());
```
Now you can connect middleware:
```typescript
app.use(bot.webhookCallback('/secret-path'));
```
The last step is to specify launchOptions in `forRoot` method:
```typescript
TelegrafModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
token: configService.get<string>('TELEGRAM_BOT_TOKEN'),
launchOptions: {
webhook: {
domain: 'domain.tld',
hookPath: '/secret-path',
}
}
}),
inject: [ConfigService],
});
```

View File

@ -0,0 +1,28 @@
---
id: installation
title: Installation
sidebar_label: Installation
slug: /
---
```bash
$ npm i nestjs-telegraf telegraf
```
Once the installation process is complete, we can import the `TelegrafModule` into the root `AppModule`.
```typescript title="src/app.module.ts"
import { Module } from '@nestjs/common';
import { TelegrafModule } from 'nestjs-telegraf';
@Module({
imports: [
TelegrafModule.forRoot({
token: 'TELEGRAM_BOT_TOKEN',
})
],
})
export class AppModule {}
```
The `forRoot()` method accepts the same configuration object as Telegraf class constructor from the Telegraf package, as described [here](https://telegraf.js.org/#/?id=constructor).

View File

@ -0,0 +1,41 @@
---
id: from-v1-to-v2
title: From v1 to v2
sidebar_label: From v1 to v2
slug: /migrating/from-v1-to-v2
---
## Remove `Telegraf` prefix
If you previously used decorators with the prefix `Telegraf` in the decorator name (such as `@TelegrafOn()` or `@TelegrafHelp()`) replace them with the same decorators but without the prefix `Telegraf`, such as `@On()`, `@Start()`, `@Command()` and so on.
## `@Update()` decorator
Since v2, `nestjs-telegraf` looks for all update handlers only inside individual classes, under the `@Update()` decorator.
Previously, you could declare a handler anywhere, for example:
```typescript title="src/cats/cats.provider.ts"
import { Injectable } from '@nestjs/common';
import { Command } from 'nestjs-telegraf';
@Injectable()
export class CatsProvider {
@Command('cats')
async helpCommand(ctx: TelegrafContext) {
await ctx.reply('Meow.');
}
}
```
Now you must explicitly bind the class, for Telegram Bot Api update handlers:
```typescript {3} title="src/cats/cats.updates.ts"
import { Update, Ctx } from 'nestjs-telegraf';
@Update()
export class HelpUpdate {
@Command('help')
async helpCommand(@Ctx() ctx: TelegrafContext) {
await ctx.reply('Help command.');
}
}
```
Treat the `@Update()` decorator like the `@Controller()` decorator, but to capture Telegram Bot Api updates.

View File

@ -0,0 +1,45 @@
---
id: telegraf-methods
title: Telegraf methods
sidebar_label: Telegraf methods
slug: /telegraf-methods
---
Each Telegraf instance method has own decorator in `nestjs-telegraf` package. The name of the decorator corresponds to the name of the Telegraf method. For example [`@Hears`](https://telegraf.js.org/classes/telegraf.html#hears), [`@On`](https://telegraf.js.org/classes/telegraf.html#on), [`@Action`](https://telegraf.js.org/classes/telegraf.html#action) and so on.
Now let's try simple example:
```typescript title="src/app.update.ts"
import {
Update,
Ctx,
Start,
Help,
On,
Hears,
} from 'nestjs-telegraf';
import { TelegrafContext } from './common/interfaces/telegraf-context.interface.ts';
@Update()
export class AppUpdate {
@Start()
async start(@Ctx() ctx: TelegrafContext) {
await ctx.reply('Welcome');
}
@Help()
async help(@Ctx() ctx: TelegrafContext) {
await ctx.reply('Send me a sticker');
}
@On('sticker')
async on(@Ctx() ctx: TelegrafContext) {
await ctx.reply('👍');
}
@Hears('hi')
async hears(@Ctx() ctx: TelegrafContext) {
await ctx.reply('Hey there');
}
}
```

View File

@ -0,0 +1,19 @@
{
"docs": {
"Getting Started": [
"installation",
"getting-updates",
"telegraf-methods",
"async-configuration"
],
"Extras": [
"extras/bot-injection",
"extras/middlewares",
"extras/multiple-bots",
"extras/standalone-applications"
],
"Migrating": [
"migrating/from-v1-to-v2"
]
}
}

3
website/versions.json Normal file
View File

@ -0,0 +1,3 @@
[
"2.6"
]