Skip to content

Commit

Permalink
Feature telegram (#109)
Browse files Browse the repository at this point in the history
* add new telegram messager

* release mutex

* add send photo method

* make bot private again

* add image when detect rewards

* swap all stop messages with stop photos

* format pom file

* simplify photos and add during stages
  • Loading branch information
daredoes authored Apr 25, 2023
1 parent 8290d82 commit cbcef51
Show file tree
Hide file tree
Showing 12 changed files with 171 additions and 37 deletions.
9 changes: 7 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

<dependencies>
<dependency>
<groupId>org.jline</groupId>
<groupId>org.jline</groupId>
<artifactId>jline</artifactId>
<version>3.21.0</version>
</dependency>
Expand Down Expand Up @@ -39,6 +39,11 @@
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>6.5.0</version>
</dependency>
</dependencies>

<build>
Expand Down Expand Up @@ -116,4 +121,4 @@
</plugins>
</build>

</project>
</project>
6 changes: 4 additions & 2 deletions src/main/java/bh/bot/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,6 @@ private static void process(String[] args) throws Exception {

if (parseArgumentsResult.enableDebugMessages)
enableDebug();
if (parseArgumentsResult.disableTelegramNoti)
Telegram.disable();

Configuration.loadSystemConfig(parseArgumentsResult);
InteractionUtil.init();
Expand Down Expand Up @@ -250,6 +248,10 @@ private static void process(String[] args) throws Exception {

info(Cu.i().magenta("Please give me a Star").ra(" at my github repository ").cyan("https://github.com/9-9-9-9/Bit-Heroes-bot").magenta(" Thank you").reset());
Rad.print(20, ColorizeUtil.formatAsk, "Visit our repository often to update latest bot version with new features added frequently");
if (parseArgumentsResult.disableTelegramNoti)
Telegram.disable();
else
Telegram.init();
instance.run(parseArgumentsResult);
}

Expand Down
8 changes: 8 additions & 0 deletions src/main/java/bh/bot/app/AbstractApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,14 @@ public void run(ParseArgumentsResult launchInfo) throws Exception {
warn("System is going to shutdown NOW");

try {
Telegram.sendMessage("" + getAppName() + " starting up", false);
Runtime.getRuntime().exec(command);
Telegram.sendMessage("" + getAppName() + " shutting down", false);
} catch (Exception ex) {
ex.printStackTrace();
err("Error occurs while trying to shutdown system");
Telegram.sendMessage("" + getAppName() + " errored while shutting down", true);
Telegram.sendMessage(ex.getMessage(), false);
}
} else {
wrappedInternalRun1(launchInfo);
Expand Down Expand Up @@ -168,6 +172,7 @@ private void wrappedInternalRun3ForWindows(ParseArgumentsResult launchInfo) {
if (mutexHandle != null) {
try {
debug("Releasing mutex handle");
Telegram.botSession.stop();
Kernel32.INSTANCE.ReleaseMutex(mutexHandle);
} catch (Throwable t) {
dev(t);
Expand Down Expand Up @@ -208,6 +213,7 @@ private void showWarningWindowMustClearlyVisible() {
}

private void tryToCloseGameWindow(boolean closeGameWindowAfterExit) {
Telegram.sendPhoto(null, getAppName(), closeGameWindowAfterExit);
if (!closeGameWindowAfterExit)
return;

Expand All @@ -224,6 +230,7 @@ private void tryToCloseGameWindow(boolean closeGameWindowAfterExit) {
} catch (Exception ignored2) {
//
} finally {
Telegram.sendPhoto(null, "" + getAppName() + " Stopped", false);
try {
getJnaInstance().tryToCloseGameWindow();
} catch (Exception ignored) {
Expand Down Expand Up @@ -1120,6 +1127,7 @@ private long detectLeaveDungeon() {

private long detectDailyRewards() {
if (clickImage(BwMatrixMeta.Metas.Globally.Dialogs.dailyRewardsTitle)) {
Telegram.sendPhoto(null, "Daily Rewards", false);
debug("Found Daily Rewards. Claiming.");
spamEscape(2);
return addSec(dailyRewardSleepSecs * 24);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/bh/bot/app/AfkApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,6 @@ protected void internalRun(String[] args) {
), //
() -> doCheckGameScreenOffset(masterSwitch) //
);
Telegram.sendMessage("Stopped", false);
}

private void doLoop(//
Expand Down Expand Up @@ -504,6 +503,7 @@ private boolean isNotBlocked(AtomicLong blockUntil) {

private void tempBlock(AttendablePlace attendablePlace) {
AtomicLong x;
Telegram.sendPhoto(null, "" + attendablePlace.name + " finished for " + attendablePlace.procedureTicketMinutes + " minutes", false);
if (attendablePlace == AttendablePlaces.pvp)
x = blockPvpUntil;
else if (attendablePlace == AttendablePlaces.worldBoss)
Expand Down
1 change: 0 additions & 1 deletion src/main/java/bh/bot/app/ChangeCharacterApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ protected void internalRun(String[] args) {
.build() //
), //
() -> doCheckGameScreenOffset(masterSwitch));
Telegram.sendMessage("Stopped", false);
}

private void doLoopClickImage(int characterSlot, AtomicBoolean masterSwitch) {
Expand Down
1 change: 0 additions & 1 deletion src/main/java/bh/bot/app/FishingApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ protected void internalRun(String[] args) {
), //
() -> doCheckGameScreenOffset(masterSwitch) //
);
Telegram.sendMessage("Stopped", false);
}

private void detectLongTimeNoSee( //
Expand Down
1 change: 0 additions & 1 deletion src/main/java/bh/bot/app/ReRunApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ protected void internalRun(String[] args) {
() -> detectDefeatedOnRaid(masterSwitch),
() -> doCheckGameScreenOffset(masterSwitch)
);
Telegram.sendMessage("Stopped", false);
}

private void doLoopClickImage(int loopCount, AtomicBoolean masterSwitch) {
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/bh/bot/app/dev/ScreenCaptureApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import bh.bot.app.AbstractApplication;
import bh.bot.common.Configuration;
import bh.bot.common.Telegram;
import bh.bot.common.types.annotations.AppMeta;
import bh.bot.common.utils.InteractionUtil;

Expand All @@ -22,6 +23,7 @@ protected void internalRun(String[] args) {
BufferedImage sc = InteractionUtil.Screen.captureScreen(x, y, w, h);
try {
saveImage(sc, "screen-shot");
Telegram.sendPhoto(sc, getDescription(), isRequiredToLoadImages());
} finally {
freeMem(sc);
}
Expand Down
1 change: 0 additions & 1 deletion src/main/java/bh/bot/app/farming/AbstractDoFarmingApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ protected void internalRun(String[] args) {
), //
() -> doCheckGameScreenOffset(masterSwitch) //
);
Telegram.sendMessage("Stopped", false);
}

protected boolean readMoreInput() throws IOException {
Expand Down
1 change: 0 additions & 1 deletion src/main/java/bh/bot/app/farming/WorldBossTeamApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ protected void internalRun(String[] args) {
), //
() -> doCheckGameScreenOffset(masterSwitch)
);
Telegram.sendMessage("Stopped", false);
}

private void doLoopClickImage(int loopCount, AtomicBoolean masterSwitch) {
Expand Down
70 changes: 70 additions & 0 deletions src/main/java/bh/bot/common/BitHeroesTelegramBot.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package bh.bot.common;

import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.objects.InputFile;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import static bh.bot.common.Log.*;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class BitHeroesTelegramBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
}

public void sendMessage(String msg) {
SendMessage sendMsg = new SendMessage();
sendMsg.setChatId(Telegram.channelId);
sendMsg.setText(msg);
try {
execute(sendMsg);
} catch (TelegramApiException ex) {
ex.printStackTrace();
}
}

public void sendPhoto(BufferedImage img, String caption) {
if (caption == null) {
caption = "";
}
SendPhoto sendPic = new SendPhoto();
sendPic.setChatId(Telegram.channelId);
sendPic.setCaption(caption);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, "jpeg", os); // Passing: ​(RenderedImage im, String formatName, OutputStream output)
InputStream is = new ByteArrayInputStream(os.toByteArray());
sendPic.setPhoto(new InputFile(is, caption));
try {
execute(sendPic);
} catch (TelegramApiException ex) {
ex.printStackTrace();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
return "Bit Heroes Bot";
}

@Override
public String getBotToken() {
// Return bot token from BotFather
return Telegram.token;
}
}
106 changes: 79 additions & 27 deletions src/main/java/bh/bot/common/Telegram.java
Original file line number Diff line number Diff line change
@@ -1,34 +1,65 @@
package bh.bot.common;

import bh.bot.common.utils.InteractionUtil;
import bh.bot.common.utils.StringUtil;
import bh.bot.common.utils.InteractionUtil.Screen;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.Buffer;

import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.BotSession;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;

import static bh.bot.common.Log.*;
import static bh.bot.common.utils.StringUtil.isBlank;
import static bh.bot.common.utils.ThreadUtil.sleep;

import static bh.bot.common.utils.ImageUtil.freeMem;

public class Telegram {
private static String appName = "BH-Unknown";

//
private static final String token = Configuration.getFromConfigOrEnv("telegram.token", "TELEGRAM_BOT_KEY");
public static final String token = Configuration.getFromConfigOrEnv("telegram.token", "TELEGRAM_BOT_KEY");
//
private static final String channelId = Configuration.getFromConfigOrEnv("telegram.channel-id", "TELEGRAM_BH_CHANNEL");
public static final String channelId = Configuration.getFromConfigOrEnv("telegram.channel-id", "TELEGRAM_BH_CHANNEL");
//
private static final String _instanceId = Configuration.getFromConfigOrEnv("telegram.instance-id", "TELEGRAM_INSTANCE_ID");
private static final String instanceId = StringUtil.isBlank(_instanceId) ? "" : String.format(":%s", _instanceId.trim());
public static final String instanceId = StringUtil.isBlank(_instanceId) ? "" : String.format(":%s", _instanceId.trim());
//
private static boolean isDisabled = isBlank(token) || isBlank(channelId);

public static boolean isDisabled() {
return isDisabled;
}

public static TelegramBotsApi botApi;

private static BitHeroesTelegramBot bhTelegramBot = new BitHeroesTelegramBot();

public static BotSession botSession;

public static void init() {
try {

botApi = new TelegramBotsApi(DefaultBotSession.class);

dev("init Telegram API");
botSession = botApi.registerBot(bhTelegramBot);

} catch (TelegramApiException ex) {
ex.printStackTrace();
}

}

public static void disable() {
isDisabled = true;
info("Disabled Telegram messages");
Expand Down Expand Up @@ -63,32 +94,53 @@ public static void sendMessage(String msg, boolean critical) {
}
}

public static void sendPhoto(BufferedImage img, String caption, boolean critical) {
if (isDisabled) {
dev("disabled Telegram::sendPhoto");
return;
}
boolean freeAfter = false;
if (img == null) {
freeAfter = true;
int x = Configuration.gameScreenOffset.X.get();
int y = Configuration.gameScreenOffset.Y.get();
int w = Configuration.screenResolutionProfile.getSupportedGameResolutionWidth();
int h = Configuration.screenResolutionProfile.getSupportedGameResolutionHeight();

BufferedImage sc = InteractionUtil.Screen.captureScreen(x, y, w, h);
img = sc;
}

int retry = critical ? 20 : 10;

while (retry > 0) {
try {
if (internalSendPhoto(img, caption, critical))
break;
} catch (Exception e) {
e.printStackTrace();
err("Error while posting Telegram message: %s", e.getMessage());
sleep(30_000);
} finally {
retry--;
}
}
if (freeAfter) {
freeMem(img);
}
}

private static boolean internalSendPhoto(BufferedImage image, String caption, boolean critical) throws Exception {
caption = String.format("[%s%s]%s %s", appName, instanceId, critical ? " *** CRITICAL ***" : "", caption);

bhTelegramBot.sendPhoto(image, caption);
return true;
}

private static boolean internalSendMessage(String msg, boolean critical) throws Exception {
msg = String.format("[%s%s]%s %s", appName, instanceId, critical ? " *** CRITICAL ***" : "", msg);

String my_url = "https://api.telegram.org/bot" + token + "/sendMessage";
URL url = new URL(my_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
try {
httpURLConnection.setDoOutput(true);
httpURLConnection.setChunkedStreamingMode(0);
OutputStream outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write("{\"chat_id\":\"" + channelId + "\",\"text\":\"" + msg + "\"}");
outputStreamWriter.flush();
outputStreamWriter.close();

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == 200)
return true;

err("Telegram::internalSendMessage failure with response code: %d, response msg: %s", responseCode, httpURLConnection.getResponseMessage());
return false;
} finally {
httpURLConnection.disconnect();
}
bhTelegramBot.sendMessage(msg);
return true;
}
}

0 comments on commit cbcef51

Please sign in to comment.