Skip to content

Commit

Permalink
Merge pull request #155 from yvasyliev/dev
Browse files Browse the repository at this point in the history
Added lang support to requests. Optimized bot initialization.
  • Loading branch information
yvasyliev authored Mar 7, 2023
2 parents 7eb1f1f + 99357b8 commit c18644d
Show file tree
Hide file tree
Showing 6 changed files with 161 additions and 86 deletions.
165 changes: 109 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,99 +1,150 @@
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.yvasyliev/java-vk-bots-longpoll-api/badge.svg?kill_cache=1)](https://search.maven.org/artifact/com.github.yvasyliev/java-vk-bots-longpoll-api)
[![GitHub tag](https://img.shields.io/github/tag/yvasyliev/java-vk-bots-long-poll-api)](https://github.com/yvasyliev/java-vk-bots-long-poll-api/releases/?include_prereleases&sort=semver "View GitHub releases")
![Build status](https://github.com/yvasyliev/java-vk-bots-long-poll-api/actions/workflows/build-maven-project.yml/badge.svg?branch=master)
[![javadoc](https://javadoc.io/badge2/com.github.yvasyliev/java-vk-bots-longpoll-api/javadoc.svg?kill_cache=1)](https://javadoc.io/doc/com.github.yvasyliev/java-vk-bots-longpoll-api)
[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://github.com/yvasyliev/java-vk-bots-long-poll-api/blob/master/LICENSE)
![Build status](https://github.com/yvasyliev/java-vk-bots-long-poll-api/actions/workflows/build-maven-project.yml/badge.svg?branch=master)
![CodeQL](https://github.com/yvasyliev/java-vk-bots-long-poll-api/workflows/CodeQL/badge.svg)
[![Known Vulnerabilities](https://snyk.io/test/github/yvasyliev/java-vk-bots-long-poll-api/badge.svg)](https://snyk.io/test/github/yvasyliev/java-vk-bots-long-poll-api)
[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=code_smells)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=ncloc)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=sqale_index)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=bugs)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=yvasyliev_java-vk-bots-long-poll-api&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=yvasyliev_java-vk-bots-long-poll-api)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat)](http://makeapullrequest.com)
[![javadoc](https://javadoc.io/badge2/com.github.yvasyliev/java-vk-bots-longpoll-api/javadoc.svg?kill_cache=1)](https://javadoc.io/doc/com.github.yvasyliev/java-vk-bots-longpoll-api)

# Java VK Bots Long Poll API

A Java library to create VK bots using Bots Long Poll API.

## Description
An easy-to-use and lightweight Java library that implements [Bots Long Poll API](https://vk.com/dev/bots_longpoll). Uses API version: `5.131`.

An easy-to-use and lightweight Java library that implements [Bots Long Poll API](https://vk.com/dev/bots_longpoll). Uses
API version: `5.131`.

## Note

This library keeps on improving. Feel free to create issues or pull requests.

## Third-party dependencies

This library uses the next third-party dependencies:

* `Gson`
* `SLF4J`
* `OkHttp`

## Requirements

1. `Java 8` or higher
2. `Maven` or other build tool

## Quickstart

1. Create VK Community.
2. Go to `Manage` - `API usage` - `Access tokens` and create `access_token`.
3. Add the library to your `Maven` project:
```xml
<dependency>
<groupId>com.github.yvasyliev</groupId>
<artifactId>java-vk-bots-longpoll-api</artifactId>
<version>4.0.0</version>
</dependency>
```
3. Add the library to your `Maven` project:
```xml
<dependency>
<groupId>com.github.yvasyliev</groupId>
<artifactId>java-vk-bots-longpoll-api</artifactId>
<version>4.1.0</version>
</dependency>
```
4. Extend `LongPollBot` class and override necessary methods:
```java
public class HelloBot extends LongPollBot {
@Override
public void onMessageNew(MessageNew messageNew) {
try {
```java
import api.longpoll.bots.LongPollBot;
import api.longpoll.bots.exceptions.VkApiException;
import api.longpoll.bots.model.events.messages.MessageNew;
import api.longpoll.bots.model.objects.basic.Message;

public class HelloBot extends LongPollBot {
@Override
public void onMessageNew(MessageNew messageNew) {
try {
Message message = messageNew.getMessage();
if (message.hasText()) {
String response = "Hello! Received your message: " + message.getText();
vk.messages.send()
.setPeerId(message.getPeerId())
.setMessage(response)
.execute();
String response = "Hello! Received your message: " + message.getText();
vk.messages.send()
.setPeerId(message.getPeerId())
.setMessage(response)
.execute();
}
} catch (VkApiException e) {
e.printStackTrace();
}
}

@Override
public String getAccessToken() {
return "your_access_token";
}

public static void main(String[] args) throws VkApiException {
new HelloBot().startPolling();
}
}
```
} catch (VkApiException e) {
e.printStackTrace();
}
}

@Override
public String getAccessToken() {
return "your_access_token";
}

public static void main(String[] args) throws VkApiException {
new HelloBot().startPolling();
}
}
```

## How to send photos or documents?

Easy:

```java
@Override
public void onMessageNew(MessageNew messageNew) {
try {
Message message = messageNew.getMessage();
vk.messages.send()
.setPeerId(message.getPeerId())
.setMessage("Sending some files to you...")
.addPhoto(new File("your_photo.png")) // to send photo as photo
.addDoc(new File("your_photo.png")) // to send photo as document
.execute();
} catch (VkApiException e) {
e.printStackTrace();
}
import api.longpoll.bots.LongPollBot;
import api.longpoll.bots.exceptions.VkApiException;
import api.longpoll.bots.model.events.messages.MessageNew;
import api.longpoll.bots.model.objects.basic.Message;
import java.io.File;

public class HelloBot extends LongPollBot {
@Override
public void onMessageNew(MessageNew messageNew) {
try {
Message message = messageNew.getMessage();
vk.messages.send()
.setPeerId(message.getPeerId())
.setMessage("Sending some files to you...")
.addPhoto(new File("your_photo.png")) // to send photo as photo
.addDoc(new File("your_photo.png")) // to send photo as document
.execute();
} catch (VkApiException e) {
e.printStackTrace();
}
}
}
```

## More Examples

Find more examples of bot usage [here](https://github.com/yvasyliev/java-vk-bots-long-poll-api-examples).

## Async execution

Each API method can be executed asynchronously:

```java
CompletableFuture<Send.ResponseBody> future = vk.messages.send()
.setPeerId(peerId)
.setMessage("Sending message asynchronously...")
.executeAsync();
import api.longpoll.bots.LongPollBot;
import api.longpoll.bots.exceptions.VkApiException;
import api.longpoll.bots.methods.impl.messages.Send;import api.longpoll.bots.model.events.messages.MessageNew;
import api.longpoll.bots.model.objects.basic.Message;
import java.io.File;import java.util.concurrent.CompletableFuture;

public class HelloBot extends LongPollBot {
@Override
public void onMessageNew(MessageNew messageNew) {
CompletableFuture<Send.ResponseBody> future = vk.messages.send()
.setPeerId(message.getPeerId())
.setMessage("Sending message asynchronously...")
.executeAsync();
}
}
```

## Bot events

`LongPollBot` can handle the next events:

| VK event | Handler method |
Expand Down Expand Up @@ -145,6 +196,8 @@ CompletableFuture<Send.ResponseBody> future = vk.messages.send()
| `wall_repost` | `public void onWallRepost(WallPost wallPost)` |

## Logging
This library uses `SLF4J` API to log all events. You can add any `SLF4J` binding to your project to register events the way you want.

This library uses `SLF4J` API to log all events. You can add any `SLF4J` binding to your project to register events the
way you want.

It is highly recommended enabling `DEBUG` log level to see sent and received data.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<groupId>com.github.yvasyliev</groupId>
<artifactId>java-vk-bots-longpoll-api</artifactId>
<packaging>jar</packaging>
<version>4.0.0</version>
<version>4.1.0</version>
<name>Java VK Bots Long Poll API</name>
<description>A Java library to create VK bots using Bots Long Poll API</description>
<url>https://github.com/yvasyliev/java-vk-bots-long-poll-api</url>
Expand Down
35 changes: 9 additions & 26 deletions src/main/java/api/longpoll/bots/LongPollBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import api.longpoll.bots.exceptions.VkApiException;
import api.longpoll.bots.exceptions.VkResponseException;
import api.longpoll.bots.methods.impl.events.GetUpdates;
import api.longpoll.bots.methods.impl.groups.GetLongPollServer;
import com.google.gson.JsonObject;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
Expand All @@ -19,16 +19,6 @@ public abstract class LongPollBot extends VkBot {
*/
private static final long DEFAULT_SESSION_DURATION = 9;

/**
* Group ID.
*/
private Integer groupId;

/**
* Gets VK long poll server.
*/
private GetLongPollServer getLongPollServer;

/**
* Gets VK updates.
*/
Expand Down Expand Up @@ -89,22 +79,15 @@ public void stopPolling() {
public void initialize() throws VkApiException {
initializedAt = LocalDateTime.now();

if (groupId == null) {
groupId = vk.other.execute()
.setCode("return API.groups.getById()@.id[0];")
.execute()
.getResponse()
.getAsInt();
}

if (getLongPollServer == null) {
getLongPollServer = new GetLongPollServer(getAccessToken());
}
JsonObject longPollServer = vk.other.execute()
.setCode("return API.groups.getLongPollServer({\"group_id\":API.groups.getById()@.id[0]});")
.execute()
.getResponse()
.getAsJsonObject();

GetLongPollServer.ResponseBody longPollServer = getLongPollServer.setGroupId(groupId).execute();
getUpdates = new GetUpdates(longPollServer.getResponse().getServer())
.setKey(longPollServer.getResponse().getKey())
.setTs(longPollServer.getResponse().getTs());
getUpdates = new GetUpdates(longPollServer.get("server").getAsString())
.setKey(longPollServer.get("key").getAsString())
.setTs(longPollServer.get("ts").getAsInt());
}

/**
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/api/longpoll/bots/methods/impl/VkMethod.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import api.longpoll.bots.exceptions.VkApiException;
import api.longpoll.bots.exceptions.VkResponseException;
import api.longpoll.bots.http.LoggerInterceptor;
import api.longpoll.bots.model.objects.additional.Lang;
import api.longpoll.bots.validator.VkResponseBodyValidator;
import com.google.gson.Gson;
import okhttp3.Call;
Expand Down Expand Up @@ -176,4 +177,14 @@ public VkMethod<VkResponse> addParam(String key, Object value) {
formBodyBuilder.add(key, String.valueOf(value));
return this;
}

/**
* Sets {@code lang} parameter.
*
* @param lang lang value.
* @return current instance.
*/
public VkMethod<VkResponse> setLang(Lang lang) {
return addParam("lang", lang);
}
}
28 changes: 28 additions & 0 deletions src/main/java/api/longpoll/bots/model/objects/additional/Lang.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package api.longpoll.bots.model.objects.additional;

/**
* Lang.
*/
public enum Lang {
RU(0),
UK(1),
BE(2),
EN(3),
ES(4),
FI(5),
DE(6),
IT(7);

/**
* Lang code.
*/
private final int code;

Lang(int code) {
this.code = code;
}

public int getCode() {
return code;
}
}
6 changes: 3 additions & 3 deletions src/main/java/api/longpoll/bots/model/objects/basic/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public class User {
* City specified on user's page in "Contacts" section.
*/
@SerializedName("city")
private String city;
private City city;

/**
* Number of common friends with current user.
Expand Down Expand Up @@ -698,11 +698,11 @@ public void setNickname(String nickname) {
this.nickname = nickname;
}

public String getCity() {
public City getCity() {
return city;
}

public void setCity(String city) {
public void setCity(City city) {
this.city = city;
}

Expand Down

0 comments on commit c18644d

Please sign in to comment.