K
Klem565. März 2022 11:34

Vk api на java. Как сделать кнопки

Java, VK, API

Вот код:

public class Bot {
public static void main(String[] args) throws ClientException, ApiException, InterruptedException {
TransportClient transportClient = new HttpTransportClient();
VkApiClient vk = new VkApiClient(transportClient);
Random random = new Random();
Keyboard keyboard = new Keyboard();
List > allKey = new ArrayList<>();
List line1 = new ArrayList<>();
line1.add(new KeyboardButton()).setAction(new KeyboardButtonAction().setLabel("Привет").setType(KeyboardButtonActionType.TEXT).setColor(KeyboardButtonColor.POSITIVE));
line1.add(new KeyboardButton()).setAction(new KeyboardButtonAction().setLabel("Кто я?").setType(KeyboardButtonActionType.TEXT).setColor(KeyboardButtonColor.POSITIVE));
keyboard.setButtons(allKey);
GroupActor actor = new GroupActor(211045078, "Key");
Integer ts = vk.messages().getLongPollServer(actor).execute().getTs();
while(true){
MessagesGetLongPollHistoryQuery historyQuery = vk.messages().getLongPollHistory(actor).ts(ts);
List messages = historyQuery.execute().getMessages().getItems();
if(!messages.isEmpty()){
messages.forEach(message -> {
System.out.println(message.toString());
try {
if (message.getText().equals("Привет")){
vk.messages().send(actor).message("Привет").userId(message.getFromId()).randomId(random.nextInt(10000)).execute();
}
else if (message.getText().equals("Кто я?")) {
vk.messages().send(actor).message("Ты хороший человек.").userId(message.getFromId()).randomId(random.nextInt(10000)).execute();
}
else if (message.getText().equals("Кнопки")){
vk.messages().send(actor).message("А вот и они").userId(message.getFromId()).randomId(random.nextInt(10000)).keyboard(keyboard).execute();
}
else {
vk.messages().send(actor).message("Я тебя не понял").userId(message.getFromId()).randomId(random.nextInt(10000)).execute();
}
}catch (ApiException | ClientException e) {e.printStackTrace();}
});
}
ts = vk.messages().getLongPollServer(actor).execute().getTs();
Thread.sleep(500);
}
}
}

И на строке---
line1.add(new KeyboardButton()).setAction(new KeyboardButtonAction().setLabel("Привет").setType(KeyboardButtonActionType.TEXT).setColor(KeyboardButtonColor.POSITIVE));

Выдаёт ошибку 'setType(com.vk.api.sdk.objects.messages.TemplateActionTypeNames)' in 'com.vk.api.sdk.objects.messages.KeyboardButtonAction' cannot be applied to '(com.vk.api.sdk.objects.messages.KeyboardButtonActionType)'
Как это решить? Для java докуменация просто идиотия:|

Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

1
АМ
  • 24. März 2022 02:12

Првиет
line1.add(new KeyboardButton().setAction(new KeyboardButtonAction().setLabel("Текст кнопки").setType(TemplateActionTypeNames.TEXT)).setColor(KeyboardButtonColor.POSITIVE));

А вообще там градл уже другой

plugins {
id 'java'
id 'application'
}
apply plugin: 'java'
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}

repositories {
mavenCentral()
}

mainClassName = 'class.name'

dependencies {
implementation 'com.vk.api:sdk:1.0.7'
}

    Kommentare

    Nur autorisierte Benutzer können Kommentare posten.
    Bitte Anmelden oder Registrieren
    Letzte Kommentare
    ИМ
    Игорь Максимов5. Oktober 2024 07:51
    Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
    d
    dblas55. Juli 2024 11:02
    QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
    k
    kmssr8. Februar 2024 18:43
    Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
    Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
    EVA
    EVA25. Dezember 2023 10:30
    Boost - statisches Verknüpfen im CMake-Projekt unter Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
    Jetzt im Forum diskutieren
    J
    JacobFib17. Oktober 2024 03:27
    добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
    JW
    Jhon Wick1. Oktober 2024 15:52
    Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
    КГ
    Кирилл Гусарев27. September 2024 09:09
    Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
    F
    Fynjy22. Juli 2024 04:15
    при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

    Folgen Sie uns in sozialen Netzwerken