import { MessageHandler } from '@wireapp/bot-api' ; import { PayloadBundle , PayloadBundleSource , PayloadBundleType } from '@wireapp/core/src/main/conversation/' ; import { Prompt , Wizardy } from 'wizardy' ; import type { QuotableMessage } from '@wireapp/core/src/main/conversation/message/OtrMessage' ; import type { TextContent } from '@wireapp/core/src/main/conversation/content' ; export { Prompt } ; export class WizardHandler < P > extends MessageHandler { private wizards : { [ id ] : Wizardy ; } = { } ; constructor ( private readonly startCommand , private readonly questionnaire , private readonly onFinish ) { super ( ) ; } private getId ( conversationId , userId ) { return `${ conversationId }@${ userId }` ; } private getWizard ( conversationId , userId ) { const id = this . getId ( conversationId , userId ) ; if ( this . wizards [ id ] ) { return this . wizards [ id ] ; } const wizard = new Wizardy ( ) ; wizard . on ( Wizardy . TOPIC . END , ( answers ) => { this . onFinish ( answers , conversationId , userId ) ; const id = this . getId ( conversationId , userId ) ; delete this . wizards [ id ] ; } ) ; this . initWizard ( wizard ) ; this . wizards [ id ] = wizard ; return this . wizards [ id ] ; } private initWizard ( wizard ) { wizard . reset ( ) ; wizard . addQuestions ( this . questionnaire ) ; } async handleEvent ( payload ) { if ( payload . source === PayloadBundleSource . NOTIFICATION_STREAM ) { return ; } if ( payload . type !== PayloadBundleType . TEXT ) { return ; } const text = ( payload . content as TextContent ) . text . trim ( ) ; if ( text . length === 0 ) { return ; } const { conversation : conversationId , from : userId } = payload ; const wizard = this . getWizard ( conversationId , userId ) ; let reply = '' ; if ( ! wizard . inConversation && text === this . startCommand ) { reply = wizard . ask ( ) ; } else if ( wizard . inConversation ) { reply = wizard . answer ( text ) ; if ( ! wizard . inConversation ) { this . initWizard ( wizard ) ; } else { reply += ` ${ wizard . ask ( ) }` ; } } if ( reply . length > 0 ) { return this . sendReply ( conversationId , payload as QuotableMessage , reply ) ; } } }