diff --git a/tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/utils/PrivateChatToUser.kt b/tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/utils/PrivateChatToUser.kt new file mode 100644 index 0000000000..23342b4126 --- /dev/null +++ b/tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/utils/PrivateChatToUser.kt @@ -0,0 +1,21 @@ +package dev.inmo.tgbotapi.utils + +import dev.inmo.tgbotapi.types.chat.* + +/** + * Trying to convert current [PrivateChat] to [User] + * + * * If [this] actually is [User] or some [Bot], will return this as is + * * If [this] is some [PreviewPrivateChat], will create new [CommonUser] + * + * !!!WARNING!!! The returned [User] CAN BE NOT EQUAL to user from some + * [dev.inmo.tgbotapi.types.message.abstracts.ContentMessage] due to absence of some fields (like premium flag or + * language) + */ +fun PrivateChat.toUser(): User = when (this) { + is ExtendedPrivateChatImpl -> CommonUser(id, firstName, lastName, username) + is CommonUser -> this + is CommonBot -> this + is PrivateChatImpl -> CommonUser(id, firstName, lastName, username) + is ExtendedBot -> this +} diff --git a/tgbotapi.utils/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/utils/extensions/UpdateChatRetriever.kt b/tgbotapi.utils/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/utils/extensions/UpdateChatRetriever.kt index a7d8f76cfb..a1edb4b0b1 100644 --- a/tgbotapi.utils/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/utils/extensions/UpdateChatRetriever.kt +++ b/tgbotapi.utils/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/utils/extensions/UpdateChatRetriever.kt @@ -9,12 +9,14 @@ import dev.inmo.tgbotapi.types.InlineQueries.ChosenInlineResult.LocationChosenIn import dev.inmo.tgbotapi.types.InlineQueries.query.BaseInlineQuery import dev.inmo.tgbotapi.types.InlineQueries.query.LocationInlineQuery import dev.inmo.tgbotapi.types.chat.Chat +import dev.inmo.tgbotapi.types.chat.PrivateChat import dev.inmo.tgbotapi.types.chat.User import dev.inmo.tgbotapi.types.queries.callback.* import dev.inmo.tgbotapi.types.update.* import dev.inmo.tgbotapi.types.update.abstracts.BaseMessageUpdate import dev.inmo.tgbotapi.types.update.abstracts.Update import dev.inmo.tgbotapi.utils.PreviewFeature +import dev.inmo.tgbotapi.utils.toUser fun CallbackQuery.sourceChat() = when (this) { is InlineMessageIdDataCallbackQuery -> null @@ -86,9 +88,13 @@ fun Update.sourceChatWithConverters( @PreviewFeature fun Update.sourceChat(): Chat? = sourceChatWithConverters() +/** + * Trying to get the user from [Update]. In some cases it can be the user without actual fields like + * [dev.inmo.tgbotapi.types.chat.CommonUser.isPremium] due to in these cases will be used [toUser] cast + */ @PreviewFeature fun Update.sourceUser(): User? = when (val data = data) { is FromUser -> data.from is WithUser -> data.user - else -> sourceChat()?.asUser() + else -> sourceChat() ?.asUser() ?: ((sourceChat() as? PrivateChat) ?.toUser()) }