Skip to content

Commit

Permalink
version 3.0
Browse files Browse the repository at this point in the history
chat admins can execute minecraft commands
replay in minecraft is now visible in chat
fix bugs, add new, smol refactoring
  • Loading branch information
SvineruS committed Sep 14, 2020
1 parent 0207948 commit 9920f7d
Show file tree
Hide file tree
Showing 6 changed files with 184 additions and 79 deletions.
8 changes: 2 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>ua.kpi.mc</groupId>
<artifactId>mctotg</artifactId>
<version>2.2.2</version>
<version>3.0</version>
<packaging>jar</packaging>

<name>Mc2TgBridge</name>
Expand Down Expand Up @@ -58,10 +58,6 @@
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>sonatype</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
</repository>
</repositories>

<dependencies>
Expand All @@ -74,7 +70,7 @@
<dependency>
<groupId>com.github.pengrad</groupId>
<artifactId>java-telegram-bot-api</artifactId>
<version>4.7.0</version>
<version>4.9.0</version>
</dependency>


Expand Down
35 changes: 25 additions & 10 deletions src/main/java/ua/kpi/mc/mctotg/Bot.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,8 @@ public Bot(String token, Long chatId) {

bot.setUpdatesListener(updates -> {
for (Update update: updates) {
try {
processUpdate(update);
} catch (Exception e) {
e.printStackTrace();
}
try { processUpdate(update); }
catch (Exception e) { e.printStackTrace(); }
}
return UpdatesListener.CONFIRMED_UPDATES_ALL;
});
Expand Down Expand Up @@ -58,18 +55,36 @@ public GetMeResponse getMe() {
return bot.execute(new GetMe());
}



void processUpdate(Update update) {
if (update.message() == null)
return;
if (!update.message().chat().id().equals(chatId))
return;

if (update.message().text() != null && update.message().text().startsWith("/online")) {
Core.GetOnline();
return;
}
Core.TgToMc(update);
MyMessage message = new MyMessage(update.message());
processMessage(message);
}

void processMessage(MyMessage message) {
if (message.isCommand())
processCommands(message);
else
Core.TgToMc(message);
}

void processCommands(MyMessage message) {
String command = message.getCommand();

if (command.startsWith("online"))
send_msg(Core.getOnline());
else if (message.isAdmin())
Utils.runCommand(command);
else
send_msg("Только для админов");


}

}
10 changes: 3 additions & 7 deletions src/main/java/ua/kpi/mc/mctotg/CommandListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;


import java.util.Arrays;

public class CommandListener implements CommandExecutor {
Expand All @@ -24,19 +25,14 @@ public boolean onCommand(CommandSender sender, Command command, String label, St
}

if (args.length >= 2 && sender instanceof Player) {
String name = sender.getName();
try {
int replyTo = Integer.parseInt(args[0]);
String text = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
String world = ((Player) sender).getWorld().getName();

Core.McToTg(name, text, replyTo, world);
Core.McToTgReplay((Player) sender, text, replyTo);
return true;
}
catch (NumberFormatException e)
{
return false;
}
catch (NumberFormatException e) { return false; }
}

return false;
Expand Down
97 changes: 47 additions & 50 deletions src/main/java/ua/kpi/mc/mctotg/Core.java
Original file line number Diff line number Diff line change
@@ -1,77 +1,74 @@
package ua.kpi.mc.mctotg;

import com.pengrad.telegrambot.Callback;
import com.pengrad.telegrambot.model.*;
import com.pengrad.telegrambot.request.GetChat;
import com.pengrad.telegrambot.request.SetChatDescription;
import com.pengrad.telegrambot.response.BaseResponse;
import com.pengrad.telegrambot.response.GetChatResponse;
import org.bukkit.Bukkit;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;

class Core {

static void TgToMc(Update update) {
String name = update.message().from().firstName();
if (update.message().from().lastName() != null)
name += " " + update.message().from().lastName();
name = name.replaceAll("[^\\x00-\\x7Fа-яА-ЯёЁіІїЇ ]", "✭");

String message_text = "";
String media = null;
if (update.message().text() != null)
message_text = update.message().text();
else {
if (update.message().audio() != null) media = "аудио";
else if (update.message().sticker() != null) media = "стикер";
else if (update.message().animation() != null) media = "гиф";
else if (update.message().photo() != null) media = "фото";
else if (update.message().video() != null) media = "видео";
else if (update.message().videoNote() != null) media = "кругляш";
else if (update.message().voice() != null) media = "войс";
else if (update.message().document() != null) media = "документ";
else media = "медиа";

if (update.message().caption() != null) message_text = update.message().caption();
}

message_text = message_text.replaceAll("[^\\x00-\\x7Fа-яА-ЯёЁіІїЇ]", "✭");
message_text = message_text.replaceAll("\n", " ");

int msg_id = update.message().messageId();
String link = "https://t.me/" + update.message().chat().username() + "/" + msg_id;

static void TgToMc(MyMessage message) {
String cmd =
"{\"text\":\"[" + name + "] \",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"/tg " + msg_id + " \"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Нажми, что бы ответить\"}}," +
(media == null ? "" : "{\"text\":\"[" + media + "] \",\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"" + link + "\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Нажми, что бы открыть телегу\"}},") +
"{\"text\":\"" + message_text + "\",\"color\":\"white\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"" + link + "\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Нажми, что бы открыть телегу\"}}]";

new BukkitRunnable() {
@Override
public void run() {Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw @a [" + cmd + "]");}
}.runTask(Main.instance);
"{\"text\":\"[" + message.senderName + "] \",\"color\":\"aqua\"," +
"\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"/tg " + message.id + " \"}," +
"\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Нажми, что бы ответить\"}}," +
(message.media == null ? "" : "{\"text\":\"[" + message.media + "] \",\"color\":\"gold\"," +
"\"clickEvent\":{\"action\":\"open_url\",\"value\":\"" + message.link + "\"}," +
"\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Нажми, что бы открыть телегу\"}},") +
"{\"text\":\"" + message.text + "\",\"color\":\"white\"," +
"\"clickEvent\":{\"action\":\"open_url\",\"value\":\"" + message.link + "\"}," +
"\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Нажми, что бы открыть телегу\"}}]";

Utils.tellraw(cmd);
Utils.CACHE.put(message.id, message);
}

static void McToTg(String name, String text, Integer replyTo, String world) {

static void McToTg(Player sender, String text, Integer replyTo) {
if (text.equals(""))
return;

String senderName = sender.getName();
String world = sender.getWorld().getName();
world = Main.config.worldNamesDict.getOrDefault(world, world);

String msg = world + "<b>" + name + "</b>" + ": " + text;
String msg = world + "<b>" + senderName + "</b>" + ": " + text;
Main.bot.send_msg(msg, replyTo);
}

static void GetOnline() {
ArrayList<String> players = new ArrayList<>();
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
players.add(p.getName());
}
String text = players.size() + " тел. \n" + String.join(", ", players);
Main.bot.send_msg(text);
static void McToTgReplay(Player sender, String text, Integer replyTo) {
Core.McToTg(sender, text, replyTo);

MyMessage cachedMessage = Utils.CACHE.get(replyTo);
String replyToName = cachedMessage == null ? "" : " " + cachedMessage.senderName;

String cmd =
"{\"text\":\"" + sender.getDisplayName() + " \",\"color\":\"white\"}," +
"{\"text\":\"[в ответ" + replyToName + "] \",\"color\":\"gold\"" +
(cachedMessage == null ? "" : ",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"" + cachedMessage.link + "\"}," +
"\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"" + cachedMessage.text +"\"}") + "}," +
"{\"text\":\"" + text + "\",\"color\":\"white\"}]";

Utils.tellraw(cmd);

}



static String getOnline() {
Collection<? extends Player> players = Bukkit.getServer().getOnlinePlayers();
if (players.size() == 0)
return "Никого..";

return players.size() + " тел. \n" + players.stream().map(HumanEntity::getName).collect(Collectors.joining(", "));
}

static void UpdateDescription(String online) {
Expand Down
9 changes: 3 additions & 6 deletions src/main/java/ua/kpi/mc/mctotg/EventListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,12 @@ public class EventListener implements Listener {

@EventHandler(priority = EventPriority.LOW)
public void onPlayerMessageEvent(AsyncPlayerChatEvent event) {
String name = event.getPlayer().getName();
String world = event.getPlayer().getWorld().getName();
String text = event.getMessage();
if (!text.startsWith(Main.config.msgStartWith))
return;
text = text.substring(Main.config.msgStartWith.length());

if (!text.startsWith(Main.config.msgStartWith)) return;
text = text.substring(Main.config.msgStartWith.length());

Core.McToTg(name, text, null, world);
Core.McToTg(event.getPlayer(), text, null);
}

@EventHandler(priority = EventPriority.LOWEST)
Expand Down
104 changes: 104 additions & 0 deletions src/main/java/ua/kpi/mc/mctotg/Utils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package ua.kpi.mc.mctotg;

import com.pengrad.telegrambot.model.Chat;
import com.pengrad.telegrambot.model.ChatMember;
import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.model.User;
import com.pengrad.telegrambot.request.GetChatMember;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.LinkedHashMap;
import java.util.Map;

public class Utils {

static MaxSizeHashMap<Integer, MyMessage> CACHE = new MaxSizeHashMap<>(100);


public static void runCommand(String cmd) {
new BukkitRunnable() {
@Override
public void run() {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd);
}
}.runTask(Main.instance);

}

public static void tellraw(String cmd) { runCommand("tellraw @a [" + cmd + "]"); }


public static String replaceNonMinecraftSymbols(String text) {
return text
.replaceAll("[^\\x00-\\x7Fа-яА-ЯёЁіІїЇ]", "✭")
.replaceAll("\n", " ")
.replaceAll("\"", "'");
}

}


class MaxSizeHashMap<K, V> extends LinkedHashMap<K, V> {
private final int MAXSIZE;

public MaxSizeHashMap(int max_size) { this.MAXSIZE = max_size; }

@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > MAXSIZE; }
}

class MyMessage {

public Integer id;
public User sender;
public Chat chat;
public String text = "";
public String senderName;
public String media;
public String link;

public MyMessage(Message message) {
id = message.messageId();
sender = message.from();
chat = message.chat();


senderName = getSenderName(sender);
link = "https://t.me/" + chat.username() + "/" + id;

if (message.text() != null)
text = Utils.replaceNonMinecraftSymbols(message.text());
else {
if (message.caption() != null) text = Utils.replaceNonMinecraftSymbols(message.caption());

if (message.audio() != null) media = "аудио";
else if (message.sticker() != null) media = "стикер";
else if (message.animation() != null) media = "гиф";
else if (message.photo() != null) media = "фото";
else if (message.video() != null) media = "видео";
else if (message.videoNote() != null) media = "кругляш";
else if (message.voice() != null) media = "войс";
else if (message.document() != null) media = "документ";
else media = "медиа";
}

}

public boolean isCommand() { return text != null && text.startsWith("/"); }

public String getCommand() { return text.substring(1); }

public boolean isAdmin() {
ChatMember.Status status = Main.bot.bot.execute(
new GetChatMember(chat.id(), sender.id())
).chatMember().status();
return status == ChatMember.Status.administrator || status == ChatMember.Status.creator;
}

private String getSenderName(User user) {
String name = user.firstName();
if (user.lastName() != null) name += " " + user.lastName();
return Utils.replaceNonMinecraftSymbols(name);
}
}

0 comments on commit 9920f7d

Please sign in to comment.