Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
ZooMMaX committed Feb 8, 2024
0 parents commit 29e47b1
Show file tree
Hide file tree
Showing 11 changed files with 581 additions and 0 deletions.
38 changes: 38 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/

### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr

### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/

### VS Code ###
.vscode/

### Mac OS ###
.DS_Store
46 changes: 46 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>ru.zoommax</groupId>
<artifactId>TelegramBotApp</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>com.github.pengrad</groupId>
<artifactId>java-telegram-bot-api</artifactId>
<version>7.0.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.11.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.11</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.11</version>
</dependency>
</dependencies>

</project>
107 changes: 107 additions & 0 deletions src/main/java/ru/zoommax/botapp/BotApp.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package ru.zoommax.botapp;

import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.UpdatesListener;
import com.pengrad.telegrambot.impl.UpdatesHandler;
import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.User;
import com.pengrad.telegrambot.request.SendMessage;
import org.slf4j.Logger;
import ru.zoommax.botapp.db.pojo.MessageType;
import ru.zoommax.botapp.db.pojo.UserPojo;
import ru.zoommax.botapp.view.ViewMessage;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BotApp implements Runnable {

public static TelegramBot bot;
private final Listener listener;
private final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

public BotApp(String token, Listener listener) {
bot = new TelegramBot(token);
this.listener = listener;
}
@Override
public void run() {
Logger logger = org.slf4j.LoggerFactory.getLogger(BotApp.class);
bot.setUpdatesListener(updates -> {
// ... process updates
// return id of last processed update or confirm them all
for (Update update : updates) {
UserPojo userPojo = new UserPojo();
long chatId = 0;
if (update.message() != null) {
chatId = update.message().chat().id();
}else if (update.callbackQuery() != null) {
chatId = update.callbackQuery().message().chat().id();
} else if (update.inlineQuery() != null) {
chatId = update.inlineQuery().from().id();
} else if (update.chosenInlineResult() != null) {
chatId = update.chosenInlineResult().from().id();
}

long lastMessageId = 0;
if (update.message() != null) {
lastMessageId = update.message().messageId();
}else if (update.callbackQuery() != null) {
lastMessageId = update.callbackQuery().message().messageId();
}

userPojo.setChatId(chatId);
userPojo = userPojo.find();
if (userPojo == null) {
userPojo = new UserPojo();
userPojo.setChatId(update.message().chat().id());
userPojo.setLastMessageId(update.message().messageId());
userPojo.setViewMessageId(bot.execute(new SendMessage(update.message().chat().id(), "Bot starting...")).message().messageId());
userPojo.setMessageType(MessageType.TEXT);
userPojo.insert();
}else {
if (update.callbackQuery() != null){
userPojo.setLastMessageId(-1);
userPojo.insert();
}else {
userPojo.setLastMessageId(lastMessageId);
userPojo.insert();
}
}


ViewMessage viewMessage = null;
if (update.message() != null) {
if (update.message().text().startsWith("/")) {
viewMessage = listener.onCommand(update.message().text(), update.message().messageId(), update.message().chat().id(), update);
}else {
viewMessage = listener.onMessage(update.message().text(), update.message().messageId(), update.message().chat().id(), update);
}
}
if (update.callbackQuery() != null) {
viewMessage = listener.onCallbackQuery(update.callbackQuery().data(), update.callbackQuery().message().messageId(), update.callbackQuery().message().chat().id(), update);
}
if (update.inlineQuery() != null) {
viewMessage = listener.onInlineQuery(update.inlineQuery().query(), update.inlineQuery().id(), update.inlineQuery().from().id(), update);
}
if (update.chosenInlineResult() != null) {
viewMessage = listener.onChosenInlineResult(update.chosenInlineResult().resultId(), update.chosenInlineResult().from().id(), update.chosenInlineResult().query(), update);
}
assert viewMessage != null;
executor.submit(viewMessage);
}
return UpdatesListener.CONFIRMED_UPDATES_ALL;
// Create Exception Handler
}, e -> {
if (e.response() != null) {
// got bad response from telegram
e.response().errorCode();
e.response().description();
} else {
// probably network error
e.printStackTrace();
}
});
}
}
12 changes: 12 additions & 0 deletions src/main/java/ru/zoommax/botapp/Listener.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ru.zoommax.botapp;

import com.pengrad.telegrambot.model.Update;
import ru.zoommax.botapp.view.ViewMessage;

public interface Listener {
ViewMessage onMessage(String message, int messageId, long chatId, Update update);
ViewMessage onCommand(String command, int messageId, long chatId, Update update);
ViewMessage onCallbackQuery(String data, int messageId, long chatId, Update update);
ViewMessage onInlineQuery(String query, String queryId, long chatId, Update update);
ViewMessage onChosenInlineResult(String resultId, long queryId, String chatId, Update update);
}
30 changes: 30 additions & 0 deletions src/main/java/ru/zoommax/botapp/db/DBConnector.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package ru.zoommax.botapp.db;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;

import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

public class DBConnector {

private MongoClient mongoClient = null;
public Object getCollection(String name, Class cls){
CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));

String uri = "mongodb://127.0.0.1:27017/?retryWrites=true&w=majority";
mongoClient = MongoClients.create(uri);
MongoDatabase database = mongoClient.getDatabase("BotApp").withCodecRegistry(pojoCodecRegistry);
return database.getCollection(name, cls);
}

public void close(){
mongoClient.close();
}
}
6 changes: 6 additions & 0 deletions src/main/java/ru/zoommax/botapp/db/pojo/MessageType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package ru.zoommax.botapp.db.pojo;

public enum MessageType {
TEXT,
MEDIA
}
49 changes: 49 additions & 0 deletions src/main/java/ru/zoommax/botapp/db/pojo/UserPojo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package ru.zoommax.botapp.db.pojo;

import com.mongodb.client.MongoCollection;
import lombok.Data;
import ru.zoommax.botapp.db.DBConnector;

import static com.mongodb.client.model.Filters.eq;

@Data
public class UserPojo extends DBConnector {
private long chatId;
private long ViewMessageId;
private long lastMessageId;
private MessageType messageType;

public UserPojo(){}

@SuppressWarnings("unchecked")
private MongoCollection<UserPojo> collection() {
return (MongoCollection<UserPojo>) getCollection("users", UserPojo.class);
}

private boolean exist() {
return collection().find(eq("chatId", this.chatId)).first() != null;
}

public boolean insert() {
if (exist())
return update();

final String result = collection().insertOne(this).toString();
return result.contains("insertedId");
}

private boolean update() {
final String result = collection().replaceOne(eq("chatId", this.chatId), this).toString();
return result.contains("matchedCount=1");
}

public boolean delete() {
final String result = collection().deleteOne(eq("chatId", this.chatId)).toString();
return result.contains("deletedCount=1");
}

public UserPojo find() {
final UserPojo userPojo = collection().find(eq("chatId", this.chatId)).first();
return userPojo;
}
}
67 changes: 67 additions & 0 deletions src/main/java/ru/zoommax/botapp/view/KeyboardMarkup.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package ru.zoommax.botapp.view;

import com.pengrad.telegrambot.model.request.*;
import lombok.Builder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Builder
public class KeyboardMarkup {
String buttonsNames;
String buttonsCallbackData;

public InlineKeyboardMarkup getInlineKeyboard() {
List<List<String>> names = new ArrayList<>();
List<List<String>> callbackData = new ArrayList<>();

for (String name : buttonsNames.split("\n")) {
List<String> row = new ArrayList<>(Arrays.asList(name.split(";")));
names.add(row);
}

for (String data : buttonsCallbackData.split("\n")) {
List<String> row = new ArrayList<>(Arrays.asList(data.split(";")));
callbackData.add(row);
}


InlineKeyboardMarkup markup = new InlineKeyboardMarkup();
for (int i = 0; i < names.size(); i++) {
List<InlineKeyboardButton> buttons = new ArrayList<>();
for (int j = 0; j < names.get(i).size(); j++) {
buttons.add(new InlineKeyboardButton(names.get(i).get(j)).callbackData(callbackData.get(i).get(j)));
}
markup.addRow(Arrays.copyOf(buttons.toArray(), buttons.size(), InlineKeyboardButton[].class));
}
return markup;
}

public ReplyKeyboardMarkup getReplyKeyboard() {
List<List<String>> names = new ArrayList<>();

for (String name : buttonsNames.split("\n")) {
List<String> row = new ArrayList<>(Arrays.asList(name.split(";")));
names.add(row);
}


List<List<KeyboardButton>> rows = new ArrayList<>();
for (int i = 0; i < names.size(); i++) {
List<KeyboardButton> buttons = new ArrayList<>();
for (int j = 0; j < names.get(i).size(); j++) {
buttons.add(new KeyboardButton(names.get(i).get(j)));
}
rows.add(buttons);
}
KeyboardButton[][] buttons = new KeyboardButton[rows.size()][];
for (int i = 0; i < rows.size(); i++) {
buttons[i] = Arrays.copyOf(rows.get(i).toArray(), rows.get(i).size(), KeyboardButton[].class);
}
ReplyKeyboardMarkup markup = new ReplyKeyboardMarkup(buttons);
markup.oneTimeKeyboard(true);
markup.resizeKeyboard(true);
return markup;
}
}
Loading

0 comments on commit 29e47b1

Please sign in to comment.