fix: initiate bot in costructor

This commit is contained in:
Igor Kamyshev 2019-03-03 18:37:18 +02:00
parent 0ea830a9b7
commit bbc1d1d9ed

View File

@ -15,30 +15,26 @@ import { InvalidConfigurationException } from './InvalidConfigurationException'
@Injectable() @Injectable()
export class TelegramBot { export class TelegramBot {
private readonly token: string
private readonly sitePublicUrl?: string private readonly sitePublicUrl?: string
private bot: Bot private readonly bot: Bot
private ref: ModuleRef private ref: ModuleRef
public constructor( public constructor(
@Inject(TokenInjectionToken) factory: TelegramModuleOptionsFactory, @Inject(TokenInjectionToken) factory: TelegramModuleOptionsFactory,
) { ) {
const { token, sitePublicUrl } = factory.createOptions() const { token, sitePublicUrl } = factory.createOptions()
this.token = token
this.sitePublicUrl = sitePublicUrl this.sitePublicUrl = sitePublicUrl
this.bot = new Telegraf(token)
} }
public init(ref: ModuleRef) { public init(ref: ModuleRef) {
this.ref = ref this.ref = ref
const bot = new Telegraf(this.token)
const handlers = this.createHandlers() const handlers = this.createHandlers()
this.setupOnStart(bot, handlers) this.setupOnStart(handlers)
this.setupOnCommand(bot, handlers) this.setupOnCommand(handlers)
this.bot = bot
} }
public getMiddleware(path: string) { public getMiddleware(path: string) {
@ -77,21 +73,21 @@ export class TelegramBot {
) )
} }
private setupOnStart(bot: Bot, handlers: Handler[]): void { private setupOnStart(handlers: Handler[]): void {
const onStart = handlers.filter(({ config }) => config.onStart) const onStart = handlers.filter(({ config }) => config.onStart)
if (onStart.length !== 1) { if (onStart.length !== 1) {
throw new Error() throw new Error()
} }
bot.start(this.adoptHandle(head(onStart))) this.bot.start(this.adoptHandle(head(onStart)))
} }
private setupOnCommand(bot: Bot, handlers: Handler[]): void { private setupOnCommand(handlers: Handler[]): void {
const commandHandlers = handlers.filter(({ config }) => config.command) const commandHandlers = handlers.filter(({ config }) => config.command)
commandHandlers.forEach(handler => { commandHandlers.forEach(handler => {
bot.command(handler.config.command, this.adoptHandle(handler)) this.bot.command(handler.config.command, this.adoptHandle(handler))
}) })
} }