feat(core): getPeerSettings method

This commit is contained in:
alina sireneva
2025-03-01 12:15:48 +03:00
parent 0de21b34b5
commit d93fe92726
6 changed files with 154 additions and 64 deletions

View File

@@ -24,7 +24,7 @@ import type { QuoteParamsFrom } from './methods/messages/send-quote.js'
import type { CanApplyBoostResult } from './methods/premium/can-apply-boost.js'
import type { CanSendStoryResult } from './methods/stories/can-send-story.js'
import type { ITelegramStorageProvider } from './storage/provider.js'
import type { AllStories, ArrayPaginated, ArrayWithTotal, Boost, BoostSlot, BoostStats, BotChatJoinRequestUpdate, BotCommands, BotReactionCountUpdate, BotReactionUpdate, BotStoppedUpdate, BusinessCallbackQuery, BusinessChatLink, BusinessConnection, BusinessMessage, BusinessWorkHoursDay, CallbackQuery, Chat, ChatEvent, ChatInviteLink, ChatInviteLinkMember, ChatJoinRequestUpdate, ChatlistPreview, ChatMember, ChatMemberUpdate, ChatPreview, ChosenInlineResult, CollectibleInfo, DeleteBusinessMessageUpdate, DeleteMessageUpdate, DeleteStoryUpdate, Dialog, FactCheck, FileDownloadLocation, FileDownloadParameters, ForumTopic, FullChat, FullUser, GameHighScore, HistoryReadUpdate, InlineCallbackQuery, InlineQuery, InputChatEventFilters, InputDialogFolder, InputFileLike, InputInlineResult, InputMediaLike, InputMediaSticker, InputMessageId, InputPeerLike, InputPrivacyRule, InputReaction, InputStarGift, InputStickerSet, InputStickerSetItem, InputText, InputWebview, MaybeDynamic, Message, MessageEffect, MessageMedia, MessageReactions, ParametersSkip2, ParsedUpdate, Peer, PeerReaction, PeerStories, Photo, Poll, PollUpdate, PollVoteUpdate, PreCheckoutQuery, RawDocument, ReplyMarkup, SavedStarGift, SentCode, StarGift, StarGiftUnique, StarsStatus, StarsTransaction, Sticker, StickerSet, StickerType, StoriesStealthMode, Story, StoryInteractions, StoryUpdate, StoryViewer, StoryViewersList, TakeoutSession, TextWithEntities, TypingStatus, UploadedFile, UploadFileLike, User, UserStarGift, UserStatusUpdate, UserTypingUpdate, WebPageMedia, WebviewResult } from './types/index.js'
import type { AllStories, ArrayPaginated, ArrayWithTotal, Boost, BoostSlot, BoostStats, BotChatJoinRequestUpdate, BotCommands, BotReactionCountUpdate, BotReactionUpdate, BotStoppedUpdate, BusinessCallbackQuery, BusinessChatLink, BusinessConnection, BusinessMessage, BusinessWorkHoursDay, CallbackQuery, Chat, ChatEvent, ChatInviteLink, ChatInviteLinkMember, ChatJoinRequestUpdate, ChatlistPreview, ChatMember, ChatMemberUpdate, ChatPreview, ChosenInlineResult, CollectibleInfo, DeleteBusinessMessageUpdate, DeleteMessageUpdate, DeleteStoryUpdate, Dialog, FactCheck, FileDownloadLocation, FileDownloadParameters, ForumTopic, FullChat, FullUser, GameHighScore, HistoryReadUpdate, InlineCallbackQuery, InlineQuery, InputChatEventFilters, InputDialogFolder, InputFileLike, InputInlineResult, InputMediaLike, InputMediaSticker, InputMessageId, InputPeerLike, InputPrivacyRule, InputReaction, InputStarGift, InputStickerSet, InputStickerSetItem, InputText, InputWebview, MaybeDynamic, Message, MessageEffect, MessageMedia, MessageReactions, ParametersSkip2, ParsedUpdate, Peer, PeerReaction, PeerSettings, PeerStories, Photo, Poll, PollUpdate, PollVoteUpdate, PreCheckoutQuery, RawDocument, ReplyMarkup, SavedStarGift, SentCode, StarGift, StarGiftUnique, StarsStatus, StarsTransaction, Sticker, StickerSet, StickerType, StoriesStealthMode, Story, StoryInteractions, StoryUpdate, StoryViewer, StoryViewersList, TakeoutSession, TextWithEntities, TypingStatus, UploadedFile, UploadFileLike, User, UserStatusUpdate, UserTypingUpdate, WebPageMedia, WebviewResult } from './types/index.js'
import type { ParsedUpdateHandlerParams } from './updates/parsed.js'
import type { RawUpdateInfo } from './updates/types.js'
import type { InputStringSessionData } from './utils/string-session.js'
@@ -228,12 +228,10 @@ import { getSavedStarGiftsById } from './methods/premium/get-saved-star-gifts-by
import { getSavedStarGifts } from './methods/premium/get-saved-star-gifts.js'
import { getStarGiftOptions } from './methods/premium/get-star-gift-options.js'
import { getStarGiftWithdrawalUrl } from './methods/premium/get-star-gift-withdrawal-url.js'
import { getStarGifts } from './methods/premium/get-star-gifts.js'
import { getStarsTransactions } from './methods/premium/get-stars-transactions.js'
import { getUniqueStarGift } from './methods/premium/get-unique-star-gift.js'
import { iterBoosters } from './methods/premium/iter-boosters.js'
import { iterSavedStarGifts } from './methods/premium/iter-saved-star-gifts.js'
import { iterStarGifts } from './methods/premium/iter-star-gifts.js'
import { iterStarsTransactions } from './methods/premium/iter-stars-transactions.js'
import { sendStarGift } from './methods/premium/send-star-gift.js'
import { setBusinessIntro } from './methods/premium/set-business-intro.js'
@@ -278,6 +276,7 @@ import { getCommonChats } from './methods/users/get-common-chats.js'
import { getGlobalTtl } from './methods/users/get-global-ttl.js'
import { getMe } from './methods/users/get-me.js'
import { getMyUsername } from './methods/users/get-my-username.js'
import { getPeerSettings } from './methods/users/get-peer-settings.js'
import { getProfilePhoto } from './methods/users/get-profile-photo.js'
import { getProfilePhotos } from './methods/users/get-profile-photos.js'
import { getUsers } from './methods/users/get-users.js'
@@ -4758,30 +4757,6 @@ export interface TelegramClient extends ITelegramClient {
/** 2FA password */
password: string
}): Promise<string>
/**
* Get a list of gifts sent to a user.
*
* **Available**: ✅ both users and bots
*
* @param userId User whose gifts to fetch
* @deprecated Use {@link getSavedStarGifts} instead
* @returns Gifts sent to the user
*/
getStarGifts(
userId: InputPeerLike,
params?: {
/**
* Offset for pagination.
*/
offset?: string
/**
* Maximum number of gifts to fetch.
*
* @default 100
*/
limit?: number
}): Promise<ArrayPaginated<SavedStarGift, string>>
/**
* Get Telegram Stars transactions for a given peer.
*
@@ -4875,35 +4850,6 @@ export interface TelegramClient extends ITelegramClient {
/** Limit for pagination */
limit?: number
}): AsyncIterableIterator<SavedStarGift>
/**
* Iterate over gifts sent to a given user.
*
* Wrapper over {@link getStarGifts}
*
* **Available**: 👤 users only
*
* @param peerId Peer ID
* @param params Additional parameters
*/
iterStarGifts(
peerId: InputPeerLike,
params?: Parameters<typeof getStarGifts>[2] & {
/**
* Total number of gifts to fetch
*
* @default Infinity, i.e. fetch all gifts
*/
limit?: number
/**
* Number of gifts to fetch per request
* Usually you don't need to change this
*
* @default 100
*/
chunkSize?: number
}): AsyncIterableIterator<UserStarGift>
/**
* Iterate over Telegram Stars transactions for a given peer.
*
@@ -5801,6 +5747,9 @@ export interface TelegramClient extends ITelegramClient {
*
*/
getMyUsername(): Promise<string | null>
/** Get {@link PeerSettings} for a peer */
getPeerSettings(
peerId: InputPeerLike): Promise<PeerSettings>
/**
* Get a single profile picture of a user by its ID
*
@@ -6905,9 +6854,6 @@ TelegramClient.prototype.getStarGiftOptions = function (...args) {
TelegramClient.prototype.getStarGiftWithdrawalUrl = function (...args) {
return getStarGiftWithdrawalUrl(this._client, ...args)
}
TelegramClient.prototype.getStarGifts = function (...args) {
return getStarGifts(this._client, ...args)
}
TelegramClient.prototype.getStarsTransactions = function (...args) {
return getStarsTransactions(this._client, ...args)
}
@@ -6920,9 +6866,6 @@ TelegramClient.prototype.iterBoosters = function (...args) {
TelegramClient.prototype.iterSavedStarGifts = function (...args) {
return iterSavedStarGifts(this._client, ...args)
}
TelegramClient.prototype.iterStarGifts = function (...args) {
return iterStarGifts(this._client, ...args)
}
TelegramClient.prototype.iterStarsTransactions = function (...args) {
return iterStarsTransactions(this._client, ...args)
}
@@ -7061,6 +7004,9 @@ TelegramClient.prototype.getMe = function (...args) {
TelegramClient.prototype.getMyUsername = function (...args) {
return getMyUsername(this._client, ...args)
}
TelegramClient.prototype.getPeerSettings = function (...args) {
return getPeerSettings(this._client, ...args)
}
TelegramClient.prototype.getProfilePhoto = function (...args) {
return getProfilePhoto(this._client, ...args)
}

View File

@@ -228,12 +228,10 @@ export { getSavedStarGiftsById } from './methods/premium/get-saved-star-gifts-by
export { getSavedStarGifts } from './methods/premium/get-saved-star-gifts.js'
export { getStarGiftOptions } from './methods/premium/get-star-gift-options.js'
export { getStarGiftWithdrawalUrl } from './methods/premium/get-star-gift-withdrawal-url.js'
export { getStarGifts } from './methods/premium/get-star-gifts.js'
export { getStarsTransactions } from './methods/premium/get-stars-transactions.js'
export { getUniqueStarGift } from './methods/premium/get-unique-star-gift.js'
export { iterBoosters } from './methods/premium/iter-boosters.js'
export { iterSavedStarGifts } from './methods/premium/iter-saved-star-gifts.js'
export { iterStarGifts } from './methods/premium/iter-star-gifts.js'
export { iterStarsTransactions } from './methods/premium/iter-stars-transactions.js'
export { sendStarGift } from './methods/premium/send-star-gift.js'
export { setBusinessIntro } from './methods/premium/set-business-intro.js'
@@ -281,6 +279,7 @@ export { getCommonChats } from './methods/users/get-common-chats.js'
export { getGlobalTtl } from './methods/users/get-global-ttl.js'
export { getMe } from './methods/users/get-me.js'
export { getMyUsername } from './methods/users/get-my-username.js'
export { getPeerSettings } from './methods/users/get-peer-settings.js'
export { getProfilePhoto } from './methods/users/get-profile-photo.js'
export { getProfilePhotos } from './methods/users/get-profile-photos.js'
export { getUsers } from './methods/users/get-users.js'

View File

@@ -81,6 +81,7 @@ import {
ParsedUpdate,
Peer,
PeerReaction,
PeerSettings,
PeersIndex,
PeerStories,
Photo,

View File

@@ -0,0 +1,18 @@
import type { ITelegramClient } from '../../client.types.js'
import { type InputPeerLike, PeerSettings, PeersIndex } from '../../types/index.js'
import { resolvePeer } from './resolve-peer.js'
/** Get {@link PeerSettings} for a peer */
export async function getPeerSettings(
client: ITelegramClient,
peerId: InputPeerLike,
): Promise<PeerSettings> {
const res = await client.call({
_: 'messages.getPeerSettings',
peer: await resolvePeer(client, peerId),
})
const peers = PeersIndex.from(res)
return new PeerSettings(res.settings, peers)
}

View File

@@ -14,6 +14,7 @@ export * from './chatlist-preview.js'
export * from './forum-topic.js'
export * from './full-chat.js'
export * from './full-user.js'
export * from './peer-settings.js'
export * from './peer.js'
export * from './peers-index.js'
export * from './typing-status.js'

View File

@@ -0,0 +1,125 @@
import type { tl } from '@mtcute/tl'
import type { PeersIndex } from './peers-index.js'
import { makeInspectable } from '../../utils/inspectable.js'
import { memoizeGetters } from '../../utils/memoize.js'
import { User } from './user.js'
/**
* Action bar that should be displayed in the chat with the user,
* containing the suggested actions to do with the user.
*/
export type ChatActionBar =
| {
/** The user is an administrator of a chat to which we sent a join request */
type: 'join_request'
/** Title of the chat */
chatTitle: string
/** Whether the chat is a broadcast channel */
isBroadcast: boolean
/** Date when the join request was sent */
requestDate: Date
}
| {
/** The chat is a recently created group chat to which new members are suggested to be invited */
type: 'invite_members'
}
| {
/**
* The chat is with a user, and adding them to contacts is suggested
* (normally this happens when they added us to their contacts)
*/
type: 'add_contact'
/** Whether we will need to explicitly share phone number with the user when adding them to contacts */
needPhoneNumberPrivacyException: boolean
}
| {
/**
* The chat is with a user, and sharing a phone number with them is suggested
* (normally this happens when they shared their phone number with us)
*/
type: 'share_phone_number'
}
| {
/** This chat is with a new user who is not in our contacts, and either adding them to contacts or block+report-ing them is suggested */
type: 'add_or_report'
/** Whether we can report this user for spamming */
canReportSpam?: boolean
/** Whether this chat was automatically archived and we can unarchive it */
canUnarchive: boolean
}
| {
/** This chat is managed with a business bot */
type: 'business_bot'
/** The business bot that manages this chat */
bot: User
/** Deep link to the bot's management menu */
manageUrl: string
}
export class PeerSettings {
constructor(
readonly raw: tl.RawPeerSettings,
readonly _peers?: PeersIndex | undefined,
) {}
/** Action bar that should be displayed in the chat with the user */
get actionBar(): ChatActionBar | null {
if (this.raw.requestChatTitle) {
return {
type: 'join_request',
chatTitle: this.raw.requestChatTitle,
isBroadcast: this.raw.requestChatBroadcast!,
requestDate: new Date(this.raw.requestChatDate ?? 0),
}
}
if (this.raw.reportGeo) {
// geo chats are deprecated
return null
}
if (this.raw.inviteMembers) {
return { type: 'invite_members' }
}
if (this.raw.shareContact) {
return { type: 'share_phone_number' }
}
if (this.raw.blockContact || this.raw.reportSpam) {
return {
type: 'add_or_report',
canReportSpam: this.raw.reportSpam!,
canUnarchive: this.raw.autoarchived!,
}
}
if (this.raw.addContact) {
return {
type: 'add_contact',
needPhoneNumberPrivacyException: this.raw.needContactsException!,
}
}
if (this.raw.businessBotId && this._peers) {
return {
type: 'business_bot',
bot: new User(this._peers.user(this.raw.businessBotId)),
manageUrl: this.raw.businessBotManageUrl ?? '',
}
}
return null
}
/** Distance in meters between us and the user */
get geoDistance(): number | null {
return this.raw.geoDistance ?? null
}
}
makeInspectable(PeerSettings)
memoizeGetters(PeerSettings, ['actionBar'])