Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

com.github.lamba92:kotlingram-core-jvm

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

com.github.lamba92:kotlingram-core-jvm

Telegram Bot APIs for Kotlin Multiplatform

  • 1.2.7
  • Source
  • Maven
  • Socket score

Version published
Maintainers
1
Source

Kotlingram | Telegram bot API for Kotlin/Multiplatform CI Publication Maven Central

Looking for a Kotlin first Telegram APIs? You are in the right place! This project offers Kotlin/Multiplatform APIs for Telegram bots based on kotlinx.serialization and Ktor client and coroutines.

Index

Usage

For basic API usage you can use the client available in kotlingram-core:

val client = TelegramBotApiClient("botToken")
val user: TelegramResponse<User> = client.getMe()
val user: TelegramResponse<List<Update>> = client.getUpdates()

All methods and types available in the Telegram Bot API documentation should be available as extension of TelegramBotApiClient.

For building a polling bot with you can use the builder available in kotlingram-bot-builder:

val customMessage = buildString {
    append(System.getProperty("java.vm.name"))
    append(", version ")
    append(System.getProperty("java.vm.version"))
}
val media = "https://www.tc-web.it/wp-content/uploads/2019/01/java.jpg"
buildPollingBot {

    options {
        botApiToken = System.getenv("jvmTestBotToken")
        botUsername = "KotlingramJvmTestBot"
    }

    handlers {
        messages {
            respondPhoto(
                photo = media,
                caption = "Hi, i'm Kotlingram JVM test bot",
                replyToMessageId = message.messageId
            )
            respondText("You wrote to me \"${message.text}\", my message is $customMessage")
            val me: User = api.getMe().response
        }
        inlineQueries {

            val responses = buildList {
                repeat(10) { index ->
                    add(
                        InlineQueryResultPhoto(
                            id = "response#$index",
                            title = "Inline response #$index",
                            type = "photo",
                            photoUrl = media,
                            thumbUrl = media
                        )
                    )
                }
            }
            respond(responses)
        }
    }
}

Note that buildPollingBot is an extension of CoroutineScope! To run it you need to either already be in a scope or create one with coroutineScope {}.

See other examples here!

Install

To install add in your Gradle build:

dependenceis {
    implementation("com.github.lamba92:kotlingram-core:{latest_version}")
    implementation("com.github.lamba92:kotlingram-bot-builder:{latest_version}")
}

For Kotlin/Multiplatform:

kotlin {
    // ...
    sourceSets {
        commonMain {
            dependencies {
                implementation("com.github.lamba92:kotlingram-core:{latest_version}")
                implementation("com.github.lamba92:kotlingram-bot-builder:{latest_version}")
            }
        }
    }
}

Add a Ktor Client engine for your platform of choice in your Gradle build.

Versions used:

  • Kotlin 1.4.30
  • Kotlinx.serialization: 1.1.0
  • Ktor: 1.5.1

Platforms available are:

  • jvm, JVM target 1.8
  • js, NodeJS with IR compilation backend
  • mingwX64
  • macosX64
  • linuxX64

mingwx64, macosx64 and linuxx64 require libcurl version 7.63 or higher installed in your system.

The packages are published on Maven Central and snapshots are available on GitHub Package Registry here, but a login is required with a GitHub personal access token (PAT).

Extensible

The implementation of each call is fairly simple, and it is possible to extend missing (or maybe wrongly generated) calls using extension functions:

@Serializable
data class GetUpdatesRequest(
    val offset: Int? = null,
    val limit: Int? = null,
    val timeout: Int? = null,
    @SerialName("allowed_updates") val allowedUpdates: List<String> = emptyList()
)

suspend fun TelegramBotApiClient.getUpdates(
    requestBody: GetUpdatesRequest
): TelegramResponse<List<Update>> =
    httpClient.post<TelegramResponse<List<Update>>> {
        url {
            protocol = apiProtocol
            host = apiHost
            port = apiPort
            path("bot$apiToken", "getUpdates")
        }
        header(HttpHeaders.ContentType, ContentType.Application.Json)
        body = requestBody
    }

suspend fun TelegramBotApiClient.getUpdates(
    offset: Int? = null,
    limit: Int? = null,
    timeout: Int? = null,
    allowedUpdates: List<String> = emptyList(),
): TelegramResponse<List<Update>> =
    getUpdates(
        GetUpdatesRequest(
            offset,
            limit,
            timeout,
            allowedUpdates
        )
    )

If you find any issue please report them in the issue section!

Limitations

Upload of files

At the moment file upload must be handled by passing the url of the file that has already been uploaded somewhere else. See the example above in respondPhoto() function.

Inline query results

When creating a subclass of InlineQueryResult you need to set their field type according to their documentation. For example when creating InlineQueryResultPhoto the type must be set to photo.

When kotlinx.serialization/issues/195 will be implemented this behaviour will be automatized.

Run on NodeJS

In the js example build.gradle.kts file I have created some tasks to webpack the output into a single script (something like a fat jar).

To do so, I've added webpack dependencies using the Kotlin/JS npm extension and then used the com.github.node-gradle.node to run webpack from the yarn environment created by the Kotlin/JS plugin in root build/js.

I've created a custom task to generate the webpack config file and it's available in the buildSrc here and then with a webpackExecutable task webpack is executed with the generated configuration. The Kotlin Team said that one day such functionality will be integrated in the official plugin tho.

Note that due to how NodeJS handles import and stuff the output of the Ktor client has to be modified a little when bundling it with webpack for NodeJS. More information here. The task :examples:js-bot:fixNodeFetchForWebpack does exactly that.

At the moment if webpacking with mode = DEVELOPMENT the output has errors, followup here Fixed in 56cb369

FAQs

Package last updated on 08 Mar 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc