We’re going to store every translation requested, and the result of the translation, so the user can request it back using the / history
command.
We’ll also allow the user to clear the history using /clear
.
Plus, calling /dnt
we’ll disable storing to the history for this particular user, and using /dt
we can restore this functionality.
Let’s start by storing every message in the session, with its translation, right after we get it in the message
event handler:
const translation = res.data.text[0]
ctx.reply(translation)
let messages = JSON.parse(ctx.session.messages) || []
messages.push({text: ctx.message.text, translation: translation})
ctx.session.messages = JSON.stringify(messages)
Now we can add a /history
command handler:
bot.command('history', ctx => {
try {
ctx.reply(JSON.parse(ctx.session.messages).map(message => `${message.text}: ${message.translation}`).join('\n'))
} catch (err) {
console.error(err)
}
})
See how we reply to the person. We parse the messages from the session (since they are stored as JSON), then we create a new array which is formatted as text: translation
, and we join the array using new lines as separators, so we are pushing a string to the user.
Let’s also add a command to clear the chat history:
bot.command('clear', ctx => {
ctx.session.messages = JSON.stringify([])
ctx.reply('✅ history cleared')
})
We simply assign an empty array (as an array JSON-encoded to a string).
Let’s give the user the “do not track” option by typing the /dnt
command. We store a dnt
flag in the session:
bot.command('dnt', ctx => {
ctx.session.dnt = true
ctx.reply('✅ do not track')
})
and we also add a corresponding /dt
command that restores the option to the original state. By default, we do track.
bot.command('dt', ctx => {
ctx.session.dnt = false
ctx.reply('✅ do track')
})
Let’s now add this flag in the on('message')
callback:
//...
if (ctx.session.dnt === true) {
return
}
let messages = JSON.parse(ctx.session.messages) || []
//...
The code for the project is available at https://glitch.com/edit/#!/node-course-project-telegram-bot-b?path=bot.js