feat(dispatcher): added getCompleteChat and withCompleteChat, similar to getCompleteSender withCompleteSender

This commit is contained in:
alina 🌸 2024-09-28 21:43:40 +03:00
parent 4952d33261
commit 412f1af120
Signed by: teidesu
SSH key fingerprint: SHA256:uNeCpw6aTSU4aIObXLvHfLkDa82HWH9EiOj9AXOIRpI
2 changed files with 38 additions and 1 deletions

View file

@ -1,4 +1,4 @@
import type { OmitInputMessageId, ParametersSkip1, Peer, Sticker } from '@mtcute/core' import type { Chat, OmitInputMessageId, ParametersSkip1, Peer, Sticker } from '@mtcute/core'
import { Message, MtPeerNotFoundError } from '@mtcute/core' import { Message, MtPeerNotFoundError } from '@mtcute/core'
import type { TelegramClient } from '@mtcute/core/client.js' import type { TelegramClient } from '@mtcute/core/client.js'
import type { import type {
@ -67,6 +67,23 @@ export class MessageContext extends Message implements UpdateContext<Message> {
return res return res
} }
/**
* Get complete information about {@link chat}
*
* Learn more: [Incomplete peers](https://mtcute.dev/guide/topics/peers.html#incomplete-peers)
*/
async getCompleteChat(): Promise<Chat> {
if (!this.chat.isMin) return this.chat
const res = await this.client.getChat(this.chat)
if (!res) throw new MtPeerNotFoundError('Failed to fetch chat')
Object.defineProperty(this, 'chat', { value: res })
return res
}
/** Get a message that this message is a reply to */ /** Get a message that this message is a reply to */
getReplyTo(): Promise<Message | null> { getReplyTo(): Promise<Message | null> {
return this.client.getReplyTo(this) return this.client.getReplyTo(this)

View file

@ -296,3 +296,23 @@ export function withCompleteSender<Mod, State extends object>(
return filter(msg, state) return filter(msg, state)
} }
} }
/**
* Middleware-like filter that will fetch the chat of the message
* and make it available to further filters, as well as the handler itself.
*/
export function withCompleteChat<Mod, State extends object>(
filter?: UpdateFilter<MessageContext, Mod, State>,
): UpdateFilter<MessageContext, Mod, State> {
return async (msg, state) => {
try {
await msg.getCompleteChat()
} catch {
return false
}
if (!filter) return true
return filter(msg, state)
}
}