Skip to content

Commit

Permalink
Merge pull request #53 from Mazawrath/rebalance_update
Browse files Browse the repository at this point in the history
Rebalance update
  • Loading branch information
Mazawrath authored Jan 11, 2020
2 parents 6cf1ee7 + 8aef84f commit f6087f1
Show file tree
Hide file tree
Showing 12 changed files with 558 additions and 42 deletions.
4 changes: 3 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repositories {
}

dependencies {
implementation 'org.javacord:javacord:3.0.0'
implementation 'org.javacord:javacord:3.0.5'

compileOnly('org.projectlombok:lombok:1.18.4')
annotationProcessor 'org.projectlombok:lombok:1.18.4'
Expand Down Expand Up @@ -55,6 +55,8 @@ dependencies {
'javax.activation:activation:1.1',

'org.toile-libre.libe:curl:0.0.23',

'com.github.origma:Google-PerspectiveAPI-Java-Client:0.0.5',

'com.google.api-client:google-api-client:1.24.1',

Expand Down
8 changes: 7 additions & 1 deletion src/main/java/com/mazawrath/beanbot/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
import com.mazawrath.beanbot.commands.copypasta.GiveModCommand;
import com.mazawrath.beanbot.commands.beancoin.*;
import com.mazawrath.beanbot.commands.copypasta.*;
import com.mazawrath.beanbot.commands.googleperspectiveapi.ToxicCommand;
import com.mazawrath.beanbot.commands.googlevision.AnalyzeCommand;
import com.mazawrath.beanbot.commands.image.*;
import com.mazawrath.beanbot.commands.poll.PollCommand;
import com.mazawrath.beanbot.commands.poll.StrawPollCommand;
import com.mazawrath.beanbot.utilities.*;
import com.mazawrath.beanbot.commands.admin.*;
import com.mazawrath.beanbot.utilities.jersey.RestServer;
import com.mazawrath.beanbot.utilities.pesrspectiveapi_requests.MessageRequest;
import com.rethinkdb.net.Connection;
import de.btobastian.sdcf4j.CommandHandler;
import de.btobastian.sdcf4j.handler.JavacordHandler;
Expand Down Expand Up @@ -45,6 +47,7 @@ public static void main(String[] args) {
Thread restServer = new Thread(new RestServer());
restServer.start();
Twitch twitch = new Twitch(args[1], args[2], conn);
MessageRequest.apiKey = args[3];

new DiscordApiBuilder().setToken(args[0]).login().thenAccept(api -> {
System.out.println("You can invite the bot by using the following url: " + api.createBotInvite());
Expand Down Expand Up @@ -74,9 +77,10 @@ public static void main(String[] args) {
// beanCoin
cmdHandler.registerCommand(new BeanBalanceCommand(points));
cmdHandler.registerCommand(new BeanFreeCommand(points));
cmdHandler.registerCommand(new BeanBetCommand(points));
// cmdHandler.registerCommand(new BeanBetCommand(points));
cmdHandler.registerCommand(new BeanTransferCommand(points));
cmdHandler.registerCommand(new BeanBoardCommand(points));
cmdHandler.registerCommand(new BeanTriviaCommand(points, new Trivia()));
// Bean Market
cmdHandler.registerCommand(new BeanMarketCommand());
cmdHandler.registerCommand(new BeanInvestCommand(points, stockMarket));
Expand All @@ -94,6 +98,8 @@ public static void main(String[] args) {
cmdHandler.registerCommand(new HistogramCommand(points));
// Google Vision Commands
cmdHandler.registerCommand(new AnalyzeCommand(points));
// Perspective AI Commands
cmdHandler.registerCommand(new ToxicCommand(points));
// Poll Commands
cmdHandler.registerCommand(new PollCommand(points));
cmdHandler.registerCommand(new StrawPollCommand(points));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,26 +40,24 @@ public void onCommand(String[] args, DiscordApi api, ServerTextChannel serverTex

private String getRecentChangeLog() {
return "**New beanBOT update released.**\n" +
"Release can be found on https://github.com/Mazawrath/beanBOT/releases/tag/v3.5.0\n" +
"Detailed changelog can be found on https://github.com/Mazawrath/beanBOT/compare/v3.4.0...v3.5.0\n" +
"Release can be found on https://github.com/Mazawrath/beanBOT/releases/tag/v3.6.0\n" +
"Detailed changelog can be found on https://github.com/Mazawrath/beanBOT/compare/v3.5.0...v3.6.0\n" +
"\n" +
"**v3.5.0**\n" +
"**v3.6.0**\n" +
"**New**\n" +
"\t- Added photo manipulation.\n" +
"\t\t- Added `.deepfry`.\n" +
"\t\t- Added `.emboss`.\n" +
"\t\t- Added `.invert`.\n" +
"\t\t- Added `.diffuse`.\n" +
"\t\t- Added `.mosaic`.\n" +
"\t\t- Added `.sepia`.\n" +
"\t- Added polling.\n" +
"\t\t- Added `.poll`.\n" +
"\t\t- Added `.strawpoll`.\n" +
"\t- Added `.beantrivia`.\n" +
"\t\t- Earn beanCoin by answering trivia questions! After using the command you will have 8 seconds to react to the correct answer, anyone can participate and win beanCoin. Don't try to cheat, you will regret it!\n" +
"\t- Added `.toxic`.\n" +
"\t\t- Analyze messages to measure their toxicity. Leave the command blank to analyze the most recent message. Enter text in to analyze that text. Or mention a user with `@` to analyze their most recent message.\n" +
"**Changes**\n" +
"\t- Changed limit to how many lottery tickets can be bought at the start of a new drawing from 200 to 100.\n" +
"\t\t- After every drawing without a winner users will be able to buy up to 50 more tickets.\n" +
"\t- Disabled `.beanbet`.\n" +
"\t- User now start with ß1000.00 when they use a command that uses beanCoin.\n" +
"\t- Changed amount users received from `.beanfree` from ß25.69 to ß50.00.\n" +
"\t- Changed the cooldown of `.beanfree` from 24 hours to 7 days.\n" +
"\t- Changed price of standard commands from ß2.00 to ß10.00.\n" +
"\t- Changed price of special commands from ß10 to ß15.\n" +
"\t- Changed price of bean lottery tickets from ß40 to ß45.\n" +
"**Bug Fixes**\n" +
"\t- Fixed a file reading issue with `.analyze`.\n" +
"\t- Fixed a issue with records getting added to the lottery database when they did not buy a ticket.";
"\t- Fixed an issue with bean lottery crashing if someone tried buying too many tickets when they didn't have any in the first place.";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class BeanFreeCommand implements CommandExecutor {
private Points points;
Expand Down Expand Up @@ -41,7 +42,7 @@ public void onCommand(ServerTextChannel serverTextChannel, User author, Server s
String dateStart = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new java.util.Date(System.currentTimeMillis()));
String dateStop = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new java.util.Date(timeLeft + 24 * 60 * 60 * 1000));
.format(new java.util.Date(timeLeft + Points.FREE_COIN_TIME_LIMIT));

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Expand All @@ -56,17 +57,16 @@ public void onCommand(ServerTextChannel serverTextChannel, User author, Server s
//in milliseconds
long diff = d2.getTime() - d1.getTime();

long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;

if (diffHours == 1)
message.append(diffHours).append(" hour ");
else
message.append(diffHours).append(" hours ");
if (diffMinutes == 1)
message.append(diffMinutes).append(" minute.");
else
message.append(diffMinutes).append(" minutes.");
long days = TimeUnit.MILLISECONDS.toDays(diff);
diff -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(diff);
diff -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
diff -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);

message.append(String.format("%d days, %d hours, %d mins, and %d seconds.",
days, hours, minutes, seconds));

serverTextChannel.sendMessage(message.toString());

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
package com.mazawrath.beanbot.commands.beancoin;

import com.mazawrath.beanbot.utilities.Points;
import com.mazawrath.beanbot.utilities.PointsUser;
import com.mazawrath.beanbot.utilities.SentryLog;
import com.mazawrath.beanbot.utilities.Trivia;
import com.vdurmont.emoji.EmojiParser;
import de.btobastian.sdcf4j.Command;
import de.btobastian.sdcf4j.CommandExecutor;
import io.sentry.Sentry;
import org.javacord.api.DiscordApi;
import org.javacord.api.entity.channel.ServerTextChannel;
import org.javacord.api.entity.message.Message;
import org.javacord.api.entity.message.Reaction;
import org.javacord.api.entity.message.embed.EmbedBuilder;
import org.javacord.api.entity.server.Server;
import org.javacord.api.entity.user.User;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class BeanTriviaCommand implements CommandExecutor {
private Points points;
private Trivia trivia;

public BeanTriviaCommand(Points points, Trivia trivia) {
this.points = points;
this.trivia = trivia;
}

@Command(
aliases = {"beantrivia", "cointrivia"},
usage = "beantrivia",
description = "Post a trivia question that anyone can answer to earn beanCoin",
privateMessages = false
)

public void onCommand(ServerTextChannel serverTextChannel, DiscordApi api, User author, Server server) {
SentryLog.addContext(null, author, server);

long timeLeft = points.useTriviaQuestion(new PointsUser(author, server), false);

if (timeLeft == 0) {
String emojiCorrectAnswer;

JSONObject jsonObject = trivia.getTrivia();
JSONArray results = (JSONArray) jsonObject.get("results");
JSONObject questionObject = (JSONObject) results.get(0);

String question = new String(Base64.getDecoder().decode(questionObject.get("question").toString()));
String difficulty = new String(Base64.getDecoder().decode(questionObject.get("difficulty").toString()));
String category = new String(Base64.getDecoder().decode(questionObject.get("category").toString()));
String correctAnswer = new String(Base64.getDecoder().decode(questionObject.get("correct_answer").toString()));

// I'm honestly ashamed of this code, please forgive me if you're thinking about hiring me and run across this snippet.
JSONArray incorrectAnswersObject = (JSONArray) questionObject.get("incorrect_answers");
String[] incorrectAnswers = new String[incorrectAnswersObject.size()];
for (int i = 0; i < incorrectAnswers.length; i++)
incorrectAnswers[i] = new String(Base64.getDecoder().decode(incorrectAnswersObject.get(i).toString()));

ArrayList<String> answers = new ArrayList<>();
answers.add(correctAnswer);
Collections.addAll(answers, incorrectAnswers);
Collections.shuffle(answers);
int correctAnswerIndex = answers.indexOf(correctAnswer);
switch (correctAnswerIndex) {
case 0:
emojiCorrectAnswer = ":one:";
break;
case 1:
emojiCorrectAnswer = ":two:";
break;
case 2:
emojiCorrectAnswer = ":three:";
break;
case 3:
emojiCorrectAnswer = ":four:";
break;
default:
serverTextChannel.sendMessage("Attempted to send trivia message but failed.");
return;
}
EmbedBuilder embed = new EmbedBuilder()
.setTitle(question)
.setDescription("Category: " + category)
.setFooter("Difficulty: " + difficulty);
for (int i = 0; i < answers.size(); i++)
embed.addField("Answer " + (i + 1), answers.get(i));
try {
Message triviaMessage = serverTextChannel.sendMessage(embed).get();
triviaMessage.addReaction(EmojiParser.parseToUnicode(":one:"));
triviaMessage.addReaction(EmojiParser.parseToUnicode(":two:"));
triviaMessage.addReaction(EmojiParser.parseToUnicode(":three:"));
triviaMessage.addReaction(EmojiParser.parseToUnicode(":four:"));

Thread.sleep(8000);
List<Reaction> reactions = triviaMessage.getReactions();

ArrayList<User> contestants = new ArrayList<>();
ArrayList<User> winners = new ArrayList<>();
ArrayList<User> cheaters = new ArrayList<>();

// Get the winners
for (int i = 0; i < reactions.size(); i++) {
if (reactions.get(i).getEmoji().equalsEmoji(EmojiParser.parseToUnicode(emojiCorrectAnswer))) {
Reaction correctEmoji = reactions.get(i);
for (int j = 0; j < correctEmoji.getUsers().get().size(); j++) {
if (correctEmoji.getUsers().get().get(j) != api.getYourself())
winners.add(correctEmoji.getUsers().get().get(j));
}
} else if (reactions.get(i).getUsers().get().contains(api.getYourself())) {
Reaction incorrectEmoji = reactions.get(i);
for (int j = 0; j < incorrectEmoji.getUsers().get().size(); j++) {
if (incorrectEmoji.getUsers().get().get(j) != api.getYourself())
contestants.add(incorrectEmoji.getUsers().get().get(j));
}
}
}

// Check for cheaters
for (int i = 0; i < reactions.size(); i++) {
if (!reactions.get(i).getEmoji().equalsEmoji(EmojiParser.parseToUnicode(emojiCorrectAnswer)) && reactions.get(i).getUsers().get().contains(api.getYourself())) {
Reaction correctEmoji = reactions.get(i);
for (int j = 0; j < correctEmoji.getUsers().get().size(); j++) {
for (int k = 0; k < winners.size(); k++) {
// Found a cheater!
if (correctEmoji.getUsers().get().get(j) == winners.get(k)) {
winners.remove(winners.get(k));
cheaters.add(correctEmoji.getUsers().get().get(j));
}
}
}
}
}
// Anyone who reacted more then once but got it wrong also cheated
ArrayList<User> duplicates = (ArrayList<User>) getDuplicate(contestants);
for (User duplicate : duplicates) {
if (!cheaters.contains(duplicate))
cheaters.add(duplicate);
}

StringBuilder winnersMessage = new StringBuilder();

if (winners.size() == 0) {
winnersMessage.append("No one got the answer correct!\n");
} else {
winnersMessage.append("The following users have won:\n");
for (int i = 0; i < winners.size(); i++) {
winnersMessage.append(winners.get(i).getDisplayName(server)).append(" got the correct answer!\n");
points.depositCoins(new PointsUser(author, server), Points.TRIVIA_CORRECT_ANSWER);
}
}
winnersMessage.append("\n");
for (int i = 0; i < cheaters.size(); i++) {
winnersMessage.append(cheaters.get(i).getDisplayName(server)).append(" has cheated and has been fined ").append(Points.pointsToString(Points.TRIVIA_CHEAT_FINE)).append("!\n");
if (points.checkBalance(new PointsUser(cheaters.get(i), server)).compareTo(Points.TRIVIA_CHEAT_FINE) <= 0)
points.makePurchase(new PointsUser(cheaters.get(i), server), new PointsUser(api.getYourself(), server), points.checkBalance(new PointsUser(cheaters.get(i), server)));
else
points.makePurchase(new PointsUser(cheaters.get(i), server), new PointsUser(api.getYourself(), server), Points.TRIVIA_CHEAT_FINE);
// Reset their trivia too.
points.useTriviaQuestion(new PointsUser(author, server), true);
}
if (cheaters.size() != 0)
winnersMessage.append("\n");
winnersMessage.append("The correct answer was: ").append(correctAnswer).append(".\nAnyone who answered correctly received ").append(Points.pointsToString(Points.TRIVIA_CORRECT_ANSWER)).append(".");

serverTextChannel.sendMessage(winnersMessage.toString());
} catch (Exception e) {
serverTextChannel.sendMessage("Attempted to send trivia message but failed.");
return;
}
} else {
StringBuilder message = new StringBuilder();

message.append("You have already did trivia today. You can use your trivia again in ");

String dateStart = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new java.util.Date(System.currentTimeMillis()));
String dateStop = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new java.util.Date(timeLeft + Points.FREE_COIN_TIME_LIMIT));

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date d1;
Date d2;

try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);

//in milliseconds
long diff = d2.getTime() - d1.getTime();

long days = TimeUnit.MILLISECONDS.toDays(diff);
diff -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(diff);
diff -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
diff -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);

message.append(String.format("%d hours, %d mins, and %d seconds.",
hours, minutes, seconds));

serverTextChannel.sendMessage(message.toString());

} catch (Exception e) {
e.printStackTrace();
}
}

Sentry.clearContext();
}

public static <T> List getDuplicate(Collection<T> list) {

final List<T> duplicatedObjects = new ArrayList<T>();
Set<T> set = new HashSet<T>() {
@Override
public boolean add(T e) {
if (contains(e)) {
duplicatedObjects.add(e);
}
return super.add(e);
}
};
for (T t : list) {
set.add(t);
}
return duplicatedObjects;
}
}
Loading

0 comments on commit f6087f1

Please sign in to comment.