GithubHelp home page GithubHelp logo

vksdk / vk-sdk-kotlin Goto Github PK

View Code? Open in Web Editor NEW
70.0 3.0 16.0 3.76 MB

Unofficial VK SDK, written in Kotlin: make bots, use the API

Home Page: https://vksdk.github.io/vk-sdk-kotlin

License: MIT License

Kotlin 98.36% Shell 1.64%
vk-api vk java social-network sdk-java kotlin multiplatform bot vk-sdk kotlin-multiplatform

vk-sdk-kotlin's Introduction

VK SDK Kotlin

cover

Create a chat-bot for VK.com in a few lines of code, use the API and forget about the limitations

https://vk.com/vk_sdk


Build Documentation Kotlin 1.5.30 API version GitHub license

Unofficial VK.com SDK, written in Kotlin. Based on Kotlin Multiplatform project, but has Java-friendly API.

See the documentation: https://vksdk.github.io/vk-sdk-kotlin

Latest version: maven-central

For Kotlin 1.3.72 use version 0.0.5 and below.

Minimal example of the echo-chatbot

Kotlin

// From here: https://vk.com/club151083290 take the ID
val groupId = 151083290

// Read more: https://vk.com/dev/access_token
val accessToken = "abcdef123456..."

// There are two http clients available for now: 
// JVM-only OkHttp-based
// and common ktor-based
val vkHttpClient = VkOkHttpClient()

val client = VkApiClient(groupId, accessToken, VkApiClient.Type.Community, VkSettings(vkHttpClient))

client.onMessage { messageEvent ->
    client.sendMessage {
        peerId = messageEvent.message.peerId
        message = "Hello, World!"

        // You can use stickers, replies, location, etc.
        // All of the message parameters are supported.
    }.execute()
}

client.startLongPolling()

Java

int groupId = 151083290;
String accessToken = "abcdef123456...";
HttpClient vkHttpClient = new VkOkHttpClient();

VkApiClient client = new VkApiClient(groupId, accessToken, VkApiClient.Type.Community, new VkSettings(vkHttpClient));

client.onMessage(event -> {
    new Message()
        .peerId(event.getMessage().getPeerId())
        .text("Hello, world!")
        .sendFrom(client)
        .execute();
});

client.startLongPolling();

Features

The primary goal of the library is to cover most of the possible needs but in an abstract way. You can't find here a hundred of pre-defined data classes for each API method, but you can write the highly customizable solution in most convenient way.

  • Supported platforms: JVM (+ Android), JS, darwin (iOS, macOS, tvOS, watchOS), mingwX64 (Windows), linuxX64
  • Big and detailed examples: Multiplatform project (iOS & Android), Kotlin project, Java-only project. See the examples directory and the documentation.
  • Written in Kotlin, but has JVM-friendly API with methods overloading, static methods, etc.
  • Modularized and highly customizable: use pre-defined HTTP-clients or write your own; combine API calls, make queues or calls lists, etc.
  • Use the client created from the code or from access_token.
  • Bots Long Poll API
    • Event is a data class MessageNew for message_new event
    • and the JsonElement for all the other events
  • Batch requests queue using execute method under the hood: make up to 75+ requests per second and don't think about the VK API limitations
    • Putting into batch requests queue is optional, but done by default for asynchronous requests
    • Synchronous calls always sent immediately
  • API calls:
  • messages.send: use DSL for sending messages and building keyboards. All method capabilities are covered.
    • Attach files in a couple of lines of code, using a file from disk, URL, etc.

Install

Library is uploaded to the Maven Central Repository.

For Gradle 6.0+ or with metadata enabled, add the dependencies in this way:

// core module is required
implementation "com.petersamokhin.vksdk:core:$vkSdkVersion"

// One of the HTTP clients is also required.
// You can use pre-defined OkHttp-based client, but only for JVM.
implementation "com.petersamokhin.vksdk:http-client-jvm-okhttp:$vkSdkVersion"

// Or else you can use the common HTTP client, which is based on ktor 
// and available for all of the platforms, including JVM.
// In this case, you also must specify the ktor engine.
implementation "com.petersamokhin.vksdk:http-client-common-ktor:$vkSdkVersion"

Otherwise, add enableFeaturePreview("GRADLE_METADATA") to settings.gradle or else you should specify the platform. Example for JVM:

implementation "com.petersamokhin.vksdk:core-jvm:$vkSdkVersion"
implementation "com.petersamokhin.vksdk:http-client-common-ktor-jvm:$vkSdkVersion"

// and OkHttp-based client is already JVM-only
implementation "com.petersamokhin.vksdk:http-client-jvm-okhttp:$vkSdkVersion"

Limitations

Unsupported platforms

Unsupported functionality

  • Attachment of a file (i.e. access to filesystem) is available only for JS, JVM and darwin. The other platform implementations may be in todo.
  • Synchronous calls for js platform

3rd party

License

See the License

vk-sdk-kotlin's People

Contributors

4uf04eg avatar petersamokhin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vk-sdk-kotlin's Issues

Добавить conversation_message_id

Привет. Просьба добавить conversation_message_id и всю работу с этой штукой. Очень нужно для ботов, работающих в беседах!
Заранее спасибо.

Получаю null при обращение к IncomingMessage#getRefSource()

        client.onMessage(event -> {
                Bootstrap.getConfig().getStringList("configuration.admins").forEach(adminId -> new Message()
                        .peerId(adminId)
                        .text("Новое сообщение от @" + event.getMessage().getRefSource())
                        .sendFrom(client)
                        .execute());
            }
        });

Получаемое сообщение: Новый тикет от @null

Вопрос: Это ошибка в SDK или я не правильно использую метод getRefSource?

Ошибка в json

При попытке отправить кнопку vk_pay json разбирается неверно(если в строке есть &, переносит в отдельный объект)

Слишком детальный вывод в лог для уровня INFO

Недавно начал использовать эту библиотеку в своем проекте, но столкнулся с проблемой излишней детализированности логов - то, что как правило скрывают под DEBUG/TRACE, оказалось на уровне INFO, и сообщения от моего приложения теряются среди сообщений этой библиотеки.

Я не очень знаком с Log4j, использовал для ведения логов библиотеку logback. Есть ли возможность поменять уровень выводимых в лог сообщений?

Ответ с ошибкой #2 от сервера Longpoll

В ходе работы бот сообщений для паблика ВК пускает в лог такие сообщения:

[threadLongpollListener/ERROR] [com.petersamokhin.bots.sdk.longpoll.LongPoll] Response of VK LongPoll fallen with error code 2

В документации к Vk Bot Long Poll API указано, что ошибка #⁠2 означает, что "истекло время действия ключа".
Также заметил, что бот либо игнорирует эту ошибку и дальше получает события, либо действительно получает ключ заново. В таком случае, вывод этой ошибки в лог следует заглушить.

Ошибка

Ошибка такая же, как и тут #17
Подробные логи:
Screenshot_546
Screenshot_547

Поломана отправка. (0.0.8)

Не может отправить текст в чат через LongPolling.

D:\Workspace\VK\WaifusBot\app\src\main\java\com\github\lkapitman\App.java:29: error: method execute in class VkRequest cannot be applied to given types;
.execute();
^
required: Continuation<? super String>
found: no arguments
reason: actual and formal argument lists differ in length

Не работает disableMentions, forwardedMessages и replyTo

Здравствуйте! Пишу бота, хочу выключить упоминания в сообщении (пытался как disableMentions = 1, так и disableMentions(true), оба не работают) и сделать ответ на сообщение (пытался replyTo(event.message.id)(то же самое с event.message.randomId), и повторные методы с forwardMessages).

Полный код:

client.sendMessage {
                    peerId = peer
                    message = "Привет пока"
                    forwardMessages(msg.randomId)
                    disableMentions = 1
                }.execute()

Не работает java пример из readme.md, client.startLongPolling() выдает ошибку.

при выполнении client.startLongPolling() он перехватывает ошибку BotsLongPollApi::exceptionHandler::error = com.petersamokhin.vksdk.core.error.VkResponseException: BotsLongPollApi initiation error: bad VK response: Error occurred during the VK response
В настройках группы Long Poll API включен, версия стоит 5.103, в коде версию не указывал.
Пробовал менять и в коде new VkSettings(vkHttpClient, 5.107) и в группе на 5.107, 5.50.
Как можно узнать что конкретно за ошибку возвращает вк? Может я что-то делаю не так?

Application hangs on java.net.SocketInputStream.socketRead0

Hello!
I tried to use your SDK on Ubuntu 16.04. Sometimes they stop receiving messages.
I tried with Java 8 and Java 9:

openjdk version "1.8.0_171"
OpenJDK Runtime Environment (build 1.8.0_171-8u171-b11-0ubuntu0.16.04.1-b11)
OpenJDK 64-Bit Server VM (build 25.171-b11, mixed mode)
openjdk version "9-internal"
OpenJDK Runtime Environment (build 9-internal+0-2016-04-14-195246.buildd.src)
OpenJDK 64-Bit Server VM (build 9-internal+0-2016-04-14-195246.buildd.src, mixed mode)

jstack prints this stacktrace:

"threadLongpollListener" #39 prio=5 os_prio=0 tid=0x00007f76ac6a2000 nid=0x5df3 runnable [0x00007f76753ae000]
java.lang.Thread.State: RUNNABLE
        at java.net.SocketInputStream.socketRead0(java.base@9-internal/Native Method)
        at java.net.SocketInputStream.socketRead(java.base@9-internal/SocketInputStream.java:116)
        at java.net.SocketInputStream.read(java.base@9-internal/SocketInputStream.java:170)
        at java.net.SocketInputStream.read(java.base@9-internal/SocketInputStream.java:141)
        at sun.security.ssl.SSLSocketInputRecord.read(java.base@9-internal/SSLSocketInputRecord.java:425)
        at sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(java.base@9-internal/SSLSocketInputRecord.java:65)
        at sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(java.base@9-internal/SSLSocketImpl.java:900)
        - locked <0x00000000e3100560> (a java.lang.Object)
        at sun.security.ssl.AppInputStream.read(java.base@9-internal/AppInputStream.java:144)
        - locked <0x00000000e3102580> (a sun.security.ssl.AppInputStream)
        at java.io.BufferedInputStream.fill(java.base@9-internal/BufferedInputStream.java:246)
        at java.io.BufferedInputStream.read1(java.base@9-internal/BufferedInputStream.java:286)
        at java.io.BufferedInputStream.read(java.base@9-internal/BufferedInputStream.java:345)
        - locked <0x00000000e378a078> (a java.io.BufferedInputStream)
        at sun.net.www.http.HttpClient.parseHTTPHeader(java.base@9-internal/HttpClient.java:704)
        at sun.net.www.http.HttpClient.parseHTTP(java.base@9-internal/HttpClient.java:647)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(java.base@9-internal/HttpURLConnection.java:1534)
        - locked <0x00000000e37888b8> (a sun.net.www.protocol.https.DelegateHttpsURLConnection)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(java.base@9-internal/HttpURLConnection.java:1439)
        - locked <0x00000000e37888b8> (a sun.net.www.protocol.https.DelegateHttpsURLConnection)
        at java.net.HttpURLConnection.getResponseCode(java.base@9-internal/HttpURLConnection.java:480)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(java.base@9-internal/HttpsURLConnectionImpl.java:319)
        at com.petersamokhin.bots.sdk.utils.web.Connection.getRequestResponse(Connection.java:38)
        at com.petersamokhin.bots.sdk.longpoll.LongPoll.startListening(LongPoll.java:228)
        at com.petersamokhin.bots.sdk.longpoll.LongPoll$$Lambda$18/707161353.run(Unknown Source)
        at java.lang.Thread.run(java.base@9-internal/Thread.java:804)

Геолокация

Геолокация приходит как RawEvent, но не как MessageNew

BotsLongPollApi::exceptionHandler::error = java.net.SocketTimeoutException: timeout

Раз в сутки примерно вылезает это исключение, причём авторестарт стоит, но он не реагирует на это. Просто зависает

BotsLongPollApi::exceptionHandler::error = java.net.SocketTimeoutException: timeout
java.net.SocketTimeoutException: timeout
        at okhttp3.internal.http2.Http2Stream$StreamTimeout.newTimeoutException(Http2Stream.kt:677)
        at okhttp3.internal.http2.Http2Stream$StreamTimeout.exitAndThrowIfTimedOut(Http2Stream.kt:686)
        at okhttp3.internal.http2.Http2Stream.takeHeaders(Http2Stream.kt:143)
        at okhttp3.internal.http2.Http2ExchangeCodec.readResponseHeaders(Http2ExchangeCodec.kt:96)
        at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.kt:106)
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.kt:79)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:34)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:82)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at com.petersamokhin.vksdk.http.VkOkHttpClient$applyConfig$$inlined$-addInterceptor$1.intercept(Interceptor.kt:90)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
        at okhttp3.internal.connection.RealCall.execute(RealCall.kt:148)
        at com.petersamokhin.vksdk.http.VkOkHttpClient.executeSync(VkOkHttpClient.kt:138)
        at com.petersamokhin.vksdk.http.VkOkHttpClient.getSync(VkOkHttpClient.kt:87)
        at com.petersamokhin.vksdk.core.api.VkApi.getLongPollUpdates$core(VkApi.kt:125)
        at com.petersamokhin.vksdk.core.api.botslongpoll.VkBotsLongPollApi.getUpdatesResponse(VkBotsLongPollApi.kt:168)
        at com.petersamokhin.vksdk.core.api.botslongpoll.VkBotsLongPollApi.access$getUpdatesResponse(VkBotsLongPollApi.kt:26)
        at com.petersamokhin.vksdk.core.api.botslongpoll.VkBotsLongPollApi$startPolling$1.invokeSuspend(VkBotsLongPollApi.kt:108)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:738)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

Бот из example выключается через час.

В одном потоке запустил бота, в другом выводил в консоль текущее время. Бот выключился ровно через час бездействия(без обращений к боту от пользователей).
Вывел ошибку
BotsLongPollApi::exceptionHandler::error = com.petersamokhin.vksdk.core.error.VkResponseException: BotsLongPollApi failed retrieving server info after error: bad VK response: Error occurred during the VK response parsing or handling.
После этого при повторном запуске выходит та же самая ошибка.

Клавиатура

Можно ли вставить клавиатуру в сообщение используя эту библиотеку?

Небезопасное обращение к queue из разных потоков

Объект queue используется из потока UpdatesHandler (в методе run) и из основного потока (посредством вызова UpdatesHandler.handleCommands(..) ).

https://github.com/petersamokhin/vk-bot-java-sdk/blob/2f38387ce4668f537df3fefcafc4dda7993a0b69/src/main/java/com/petersamokhin/bots/sdk/longpoll/UpdatesHandler.java#L40

https://github.com/petersamokhin/vk-bot-java-sdk/blob/2f38387ce4668f537df3fefcafc4dda7993a0b69/src/main/java/com/petersamokhin/bots/sdk/longpoll/UpdatesHandler.java#L49

При этом сласс Queue сам по себе не является синхронизированным, а данные в нем хранятся в ArrayList<>, который так же не является потокобезопасным.
https://github.com/petersamokhin/vk-bot-java-sdk/blob/2f38387ce4668f537df3fefcafc4dda7993a0b69/src/main/java/com/petersamokhin/bots/sdk/longpoll/Queue.java#L16

Таким образом во время работы программы велика вероятность разрушения данных.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.