Closed sqiao7 closed 2 months ago
You need to filter down the updates before letting them reach onlyAdmin
. Perhaps check out the two sections about middleware first. They explain thoroughly how updates flow through the handlers, and what you can do to influence this.
https://grammy.dev/guide/middleware https://grammy.dev/advanced/middleware
If you have any concrete question about the docs or how to apply them to your code, please don't hesitate to ask them.
This means that I need to write a filter function,right?
import { Composer, Keyboard } from 'grammy'
import moduleInfo from '../minfo.js'
import onlyAdmin from '../../middleware/onlyAdmin.js'
const composer = new Composer()
composer.command(moduleInfo.tradeBill .cmd, async (ctx) => {
// ...
})
composer.filter(/* only this module filter func */).use(onlyAdmin)
export default composer
This means that I need to write a filter function,right?
Yes
import { Composer, Keyboard } from 'grammy' import moduleInfo from '../minfo.js' import onlyAdmin from '../../middleware/onlyAdmin.js' const composer = new Composer() composer.command(moduleInfo.tradeBill .cmd, async (ctx) => { // ... }) composer.filter(/* only this module filter func */).use(onlyAdmin) export default composer
This would mean that onlyAdmin
is only executed when the filter function returns true. However, the command would always be run. That's probably not what you meant.
Instead, something like this is better:
const composer = new Composer()
const protected = composer.filter(/* only this module filter func */);
protected.use(onlyAdmin)
protected.command(moduleInfo.tradeBill .cmd, async (ctx) => {
// ...
})
export default composer
That being said, why don't you refactor onlyAdmin
in such a way that it can be passed to bot.filter
? Instead of calling next after some checks, you could just return true or false, and then do
const protected = composer.filter(betterOnlyAdmin)
protected.command(..)
// …
export default composer
Wow, this is a good idea. Maybe I have to ask whether this composer in Grammy is independent, like this.
The reason for my problem is that UPDATE will be executed in order in the order of bot.use()
or composer.use()
. When I add a filter function with a module middleware , there will be no such problem, UPDATE after the complete walk
I have now learned how to use filter correctly, thanks. hava a nice day!
Great to hear!
when i use the onlyAdmin middleware, i only want it work in some Composer, how to do that. Or do I need to filter message text in the middleware myself?