-
Notifications
You must be signed in to change notification settings - Fork 2
Middlewares
Alper Kürşat edited this page Feb 14, 2022
·
2 revisions
Botocrat has chain of responsibility
pattern similar to express. Middlewares extends modularity of your bot software and reduce complexity and can be specified via .use(MIDDLEWARE)
method.
One and only built-in middleware is Commands. It catches command calls(like "/start") and routes to function.
Middlewares can work async but also can short-circuit the chain. To continue execution, you should call .next()
method.
const isAdmin = (req, res, next) => {
res.isAdmin = req.from.username === "adminUsername"
next()
}
Botocrat()
.use(isAdmin)
.get("message", (req, res) =>
res.reply(`Hello ${ res.isAdmin ? "admin" : req.from.first_name }!`)
const userMiddleware = async (req, res, next) => {
res.user = await getUser(req.from.id)
next()
}
const onText = (regex, callback) => async (req, res, next) => {
if(res.type !== "message") return next()
const matches = req.text.match(regex)
matches
? callback(req, res, matches)
: next()
}
Botocrat()
.use(onText(/Hello ([a-zA-Z]+)/gm, (req, res, matches) =>
res.send("Hi, " + matches[0] + "! ")))
Feel free to write and share your own middlewares. We suggest following naming convention: botocrat-middleware-*******
to make your library discoverable at npm.