Last active
June 8, 2020 14:20
-
-
Save Siedlerchr/a9446c64d08033e3d68e7b9515d3255f to your computer and use it in GitHub Desktop.
Sample for creating a Telegraf js bot scence with timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as util from 'util' | |
const setTimeoutPromise = util.promisify(setTimeout); | |
const TIMEOUT_MILLI_SECONDS = 10000; | |
export interface MyContext extends SceneContextMessageUpdate { | |
session: any, | |
} | |
const localSession = new LocalSession({ | |
database: 'example_db.json', | |
property: 'session' | |
}); | |
const textScence = new Scene("textScene"); | |
textScence.enter((ctx: MyContext) => { | |
const timeout = setTimeoutPromise<MyContext>(TIMEOUT_MILLI_SECONDS, ctx); | |
ctx.reply("Please send some text"); | |
const textPromise = new Promise<MyContext>((resolve, reject) => { | |
textScence.on("text", (ctx: MyContext) => { | |
ctx.session.text = ctx.message.text; | |
resolve(ctx) | |
}); | |
}) | |
Promise.race([textPromise, timeout]).then(data => { | |
if (data.session.text) { | |
// swtich to next scene | |
this.switchScene(data); | |
} | |
else { | |
data.reply("Timeout! No addtional text received. Exiting); | |
const key = localSession.getSessionKey(ctx) | |
localSession.saveSession(key, null); | |
} | |
}).catch(e => { | |
console.log("Got error in text scene", e); | |
const key = localSession.getSessionKey(ctx) | |
localSession.saveSession(key, null); | |
}) | |
}); | |
this.bot.on('photo', async (ctx) => { | |
console.log("START->Photo"); | |
//get photo ... | |
ctx.scence.enter("textScene") | |
}) | |
const stage = new Stage(["textScene"]) | |
stage.command('cancel', leave()); | |
this.bot.use(stage.middleware()) | |
this.bot.start((ctx) => ctx.reply('Welcome!')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment