Skip to content

Commit

Permalink
Merge pull request #20 from alt-art/tests
Browse files Browse the repository at this point in the history
Tests and small things
  • Loading branch information
alt-art authored Jul 23, 2024
2 parents c2b3483 + 574db30 commit 158275d
Show file tree
Hide file tree
Showing 46 changed files with 3,183 additions and 81 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up JDK 8
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: '8'
Expand Down
28 changes: 28 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Tests

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'corretto'
- name: Run tests
run: ./gradlew
- name: Report test results
uses: mikepenz/action-junit-report@v4
if: success() || failure()
with:
report_paths: '**/build/test-results/test/TEST-*.xml'
2 changes: 2 additions & 0 deletions CONFIG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,6 @@ deathEvent: true
advancementEvent: true
# Log player sleep in telegram chat
sleepEvent: false
# Log when server starts and stops in telegram chat
serverStartStop: false
```
16 changes: 13 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version '8.1.1'
id 'idea'
}

shadowJar {
Expand All @@ -27,14 +28,16 @@ dependencies {
implementation 'org.telegram:telegrambots:6.9.7.1'
implementation 'org.xerial:sqlite-jdbc:3.45.3.0'
compileOnly 'org.jetbrains:annotations:24.1.0'
compileOnly 'org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT'
implementation 'org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT'
testImplementation platform('org.junit:junit-bom:5.10.2')
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
implementation 'org.mockito:mockito-core:5.12.0'
}

def targetJavaVersion = 8
java {
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
if (JavaVersion.current() < javaVersion) {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
Expand All @@ -48,6 +51,13 @@ tasks.withType(JavaCompile).configureEach {
}
}

test {
useJUnitPlatform()
testLogging {
events "passed", "skipped", "failed"
}
}

processResources {
def props = [version: version]
inputs.properties props
Expand Down
55 changes: 37 additions & 18 deletions src/main/java/org/altart/telegrambridge/TelegramBridge.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
import org.altart.telegrambridge.database.SQLite;
import org.altart.telegrambridge.events.ChatEvent;
import org.altart.telegrambridge.events.GameEvent;
import org.altart.telegrambridge.utils.Format;
import org.bukkit.Bukkit;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.telegram.telegrambots.meta.TelegramBotsApi;
Expand Down Expand Up @@ -47,34 +49,51 @@ public void onEnable() {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
botSession = telegramBotsApi.registerBot(telegramBot);
log.info("Telegram bot registered");
if (config.sendToTelegram && config.serverStartStop) {
telegramBot.broadcastMessage(translations.get().serverStart);
}

Bukkit.getPluginManager().registerEvents(new ChatEvent(), plugin);
Bukkit.getPluginManager().registerEvents(new GameEvent(), plugin);
try {
Objects.requireNonNull(getCommand("tbreload")).setExecutor(new ReloadCommand());
PluginCommand replyCommand = Objects.requireNonNull(getCommand("tbreply"));
replyCommand.setExecutor(new ReplyCommand());
replyCommand.setTabCompleter(new UserTabCompletion(2));
PluginCommand mentionCommand = Objects.requireNonNull(getCommand("tbmention"));
mentionCommand.setExecutor(new MentionCommand());
mentionCommand.setTabCompleter(new UserTabCompletion(1));
PluginCommand configCommand = Objects.requireNonNull(getCommand("tbconfig"));
configCommand.setExecutor(new ConfigCommand());
configCommand.setTabCompleter(new ConfigTabCompletion());
} catch (NullPointerException e) {
log.severe("Error registering command: " + e.getMessage());
Arrays.stream(e.getStackTrace()).forEach(line -> TelegramBridge.log.severe(line.toString()));
}
} catch (Exception e) {
log.severe("Error registering bot: " + e.getMessage());
Arrays.stream(e.getStackTrace()).forEach(line -> log.severe(line.toString()));
}

Bukkit.getPluginManager().registerEvents(new ChatEvent(), plugin);
Bukkit.getPluginManager().registerEvents(new GameEvent(), plugin);
try {
Objects.requireNonNull(getCommand("tbreload")).setExecutor(new ReloadCommand());
PluginCommand replyCommand = Objects.requireNonNull(getCommand("tbreply"));
replyCommand.setExecutor(new ReplyCommand());
replyCommand.setTabCompleter(new UserTabCompletion(2));
PluginCommand mentionCommand = Objects.requireNonNull(getCommand("tbmention"));
mentionCommand.setExecutor(new MentionCommand());
mentionCommand.setTabCompleter(new UserTabCompletion(1));
PluginCommand configCommand = Objects.requireNonNull(getCommand("tbconfig"));
configCommand.setExecutor(new ConfigCommand());
configCommand.setTabCompleter(new ConfigTabCompletion());
} catch (NullPointerException e) {
log.severe("Error registering command: " + e.getMessage());
Arrays.stream(e.getStackTrace()).forEach(line -> TelegramBridge.log.severe(line.toString()));
}
}

@Override
public void onDisable() {
database.close();
if (botSession != null) {
if (config.sendToTelegram) {
if (config.joinAndLeaveEvent) {
StringBuilder message = new StringBuilder();
for (Player player : Bukkit.getOnlinePlayers()) {
message.append(Format.string(translations.get().leave, "playername", player.getDisplayName())).append("\n");
}
if (message.length() > 0) {
telegramBot.broadcastMessage(message.toString());
}
}
if (config.serverStartStop) {
telegramBot.broadcastMessage(translations.get().serverStop);
}
}
botSession.stop();
}
}
Expand Down
20 changes: 10 additions & 10 deletions src/main/java/org/altart/telegrambridge/bot/TelegramBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ public class TelegramBot extends TelegramLongPollingBot {
private final Plugin plugin;
private final Map<String, TelegramCommandExecutor> commands = new HashMap<>();

private final List<TelegramFeature> features = new ArrayList<>();
public List<TelegramFeature> features = new ArrayList<>();

public final PinMessage pinMessageFeature = new PinMessage(this);
public final UserAutocomplete userAutocompleteFeature = new UserAutocomplete(this);
public final MessageListener messageListenerFeature = new MessageListener(this);
public PinMessage pinMessageFeature = new PinMessage(this);
public UserAutocomplete userAutocompleteFeature = new UserAutocomplete(this);
public MessageListener messageListenerFeature = new MessageListener(this);
public final SentMedia sentMediaFeature = new SentMedia(this);

public TelegramBot(Plugin plugin) {
Expand Down Expand Up @@ -88,7 +88,7 @@ public void onUpdateReceived(@NotNull Update update) {
}
}

private boolean isNotAdmin(String chatId, Long userId) {
public boolean isNotAdmin(String chatId, Long userId) {
GetChatAdministrators getChatAdministrators = new GetChatAdministrators();
getChatAdministrators.setChatId(chatId);
try {
Expand Down Expand Up @@ -172,7 +172,7 @@ public void pinMessage(String chatId, Integer messageId) {
}
}

public void unpinMessage(String chatId, Integer messageId) {
public void unpinMessage(@NotNull String chatId, Integer messageId) {
try {
execute(new UnpinChatMessage(chatId, messageId));
} catch (TelegramApiException e) {
Expand All @@ -198,7 +198,7 @@ public void editSystemMessage(String message, String chatId, Integer messageId)
}
}

public void deleteMessage(String chatId, Integer messageId) {
public void deleteMessage(@NotNull String chatId, @NotNull Integer messageId) {
try {
execute(new DeleteMessage(chatId, messageId));
} catch (TelegramApiException e) {
Expand All @@ -208,9 +208,9 @@ public void deleteMessage(String chatId, Integer messageId) {
}

public class CommandSender {
public Plugin plugin;
public Message message;
public TelegramBot bot;
public final Plugin plugin;
public final Message message;
public final TelegramBot bot;

private CommandSender(Message message, Plugin plugin, TelegramBot bot) {
this.message = message;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package org.altart.telegrambridge.bot;

abstract public class TelegramCommandExecutor {
public boolean requirePermission;
public final boolean requirePermission;

public TelegramCommandExecutor(boolean requirePermission) {
this.requirePermission = requirePermission;
}
public void onCommand(TelegramBot.CommandSender sender, String[] args) {}

public void onCommand(TelegramBot.CommandSender sender, String[] args) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void onCommand(TelegramBot.CommandSender sender, String[] args) {
sender.sendMessage(response);
}

public HashMap<String, String> makeTimeMap(String time, String emoji, int day, int month, int year) {
private HashMap<String, String> makeTimeMap(String time, String emoji, int day, int month, int year) {
HashMap<String, String> values = new HashMap<>();
values.put("time", time);
values.put("emoji", emoji);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ public void onCommand(TelegramBot.CommandSender sender, String[] args) {
String chatId = String.valueOf(sender.message.getChatId());
for (Config.Chat chat : TelegramBridge.config.chats) {
if (chat.id.equals(chatId)) {
if (chat.pinnedMessageId != null) {
sender.bot.unpinMessage(chatId, chat.pinnedMessageId);
sender.bot.deleteMessage(chatId, chat.pinnedMessageId);
}
TelegramBridge.config.setPinnedMessageId(chatId, null);
sender.bot.unpinMessage(chatId, chat.pinnedMessageId);
sender.bot.deleteMessage(chatId, chat.pinnedMessageId);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public void onUpdateReceived(@NotNull Update update) {

Message reply = message.getReplyToMessage();
if (reply != null && reply.hasText()) {
String replyUsername = reply.getFrom().getUserName();
String replyUsername = getUserName(message);
String replyMessage = reply.getText();
finalComponent.addExtra(replyComponent(replyUsername, replyMessage, lang));
}
Expand Down Expand Up @@ -122,11 +122,6 @@ public void onUpdateReceived(@NotNull Update update) {
username += " " + message.getFrom().getLastName();
}
}

if (username.trim().isEmpty()) {
username = "Anonymous";
}

return username;
}

Expand Down Expand Up @@ -155,10 +150,10 @@ private static TextComponent replyComponent(String username, String message, @Nu
}

private static class MessageInfo {
public String chatId;
public Integer messageId;
public String message;
public String username;
public final String chatId;
public final Integer messageId;
public final String message;
public final String username;

public MessageInfo(String chatId, Integer messageId, String message, String username) {
this.chatId = chatId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ public class PinMessage extends TelegramFeature {

public PinMessage(TelegramBot telegramBot) {
super(telegramBot);
updatePinnedMessage();
}

static public String buildPinnedMessage() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,17 @@ public SentMedia(TelegramBot telegramBot) {

@Override
public void onUpdateReceived(@NotNull Update update) {
Message message = update.getMessage();
if (isMedia(message)) {
String username = message.getFrom().getUserName();
String caption = message.getCaption();
caption = caption == null ? "" : "\n" + caption;
if (TelegramBridge.config.sendToChat) {
if (TelegramBridge.config.sendToChat) {
Message message = update.getMessage();
if (isMedia(message)) {
String username = message.getFrom().getUserName();
String caption = message.getCaption();
caption = caption == null ? "" : "\n" + caption;
HashMap<String, String> values = new HashMap<>();
values.put("caption", caption);
values.put("user", username);
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.hasPermission(Permissions.RECEIVE.getString())) {
HashMap<String, String> values = new HashMap<>();
values.put("user", username);
values.put("caption", caption);
String lang = TelegramBridge.database.getLang(player.getUniqueId());
values.put("type", determineMediaType(message, lang));
String text = Format.string(TelegramBridge.translations.get(lang).telegramMedia, values);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command _comman
if (args[0].equals("default-lang")) {
if (!sender.hasPermission(Permissions.DEFAULT_TRANSLATION_CONFIG.getString())) {
sender.sendMessage("You do not have permission to use this command.");
return true;
return false;
}
try {
TelegramBridge.translations.setDefaultLang(args[1]);
Expand All @@ -31,14 +31,14 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command _comman
if (args[0].equals("lang")) {
if (!sender.hasPermission(Permissions.TRANSLATION_CONFIG.getString())) {
sender.sendMessage("You do not have permission to use this command.");
return true;
return false;
}
try {
if (sender instanceof Player) {
TelegramBridge.database.setLang(((Player) sender).getUniqueId(), args[1]);
} else {
sender.sendMessage("This command can only be used by players.");
return true;
return false;
}
} catch (Exception e) {
sender.sendMessage(e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import java.util.List;

public class UserTabCompletion implements TabCompleter {
int argLength;
final int argLength;

public UserTabCompletion(int argLength) {
this.argLength = argLength;
Expand Down
Loading

0 comments on commit 158275d

Please sign in to comment.