Browse Source

Bissel Reddit und so

master
Paul Glaß 4 years ago
parent
commit
2cca8e9553
6 changed files with 136 additions and 70 deletions
  1. +11
    -9
      app/build.gradle
  2. +23
    -16
      app/src/main/java/de/yannicpunktdee/yoshibot/command/YoshiCommand.java
  3. +9
    -9
      app/src/main/java/de/yannicpunktdee/yoshibot/main/Main.java
  4. +30
    -29
      app/src/main/java/de/yannicpunktdee/yoshibot/main/YoshiBot.java
  5. +38
    -0
      app/src/main/java/de/yannicpunktdee/yoshibot/utils/RedditProvider.java
  6. +25
    -7
      app/src/main/java/de/yannicpunktdee/yoshibot/utils/Resources.java

+ 11
- 9
app/build.gradle View File

@ -22,15 +22,17 @@ dependencies {
// This dependency is used by the application. // This dependency is used by the application.
implementation 'com.google.guava:guava:29.0-jre' implementation 'com.google.guava:guava:29.0-jre'
implementation group: 'org.json', name: 'json', version: '20210307'
implementation 'net.dv8tion:JDA:4.2.0_247'
implementation 'com.sedmelluq:lavaplayer:1.3.73'
implementation group: 'org.json', name: 'json', version: '20210307'
implementation 'net.dv8tion:JDA:4.2.0_247'
implementation 'com.sedmelluq:lavaplayer:1.3.73'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.0' implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
implementation "net.dean.jraw:JRAW:1.1.0"
compileOnly 'org.projectlombok:lombok:1.18.16' compileOnly 'org.projectlombok:lombok:1.18.16'
annotationProcessor 'org.projectlombok:lombok:1.18.16' annotationProcessor 'org.projectlombok:lombok:1.18.16'
} }
@ -42,11 +44,11 @@ application {
mainClass = "$mainClassName" mainClass = "$mainClassName"
} }
jar{
manifest{
jar {
manifest {
attributes "Main-Class": "$mainClassName" attributes "Main-Class": "$mainClassName"
} }
from { from {
configurations.runtimeClasspath.findAll({!it.path.endsWith(".pom")}).collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.findAll({ !it.path.endsWith(".pom") }).collect { it.isDirectory() ? it : zipTree(it) }
} }
} }

+ 23
- 16
app/src/main/java/de/yannicpunktdee/yoshibot/command/YoshiCommand.java View File

@ -3,6 +3,7 @@ package de.yannicpunktdee.yoshibot.command;
import de.yannicpunktdee.yoshibot.main.YoshiBot; import de.yannicpunktdee.yoshibot.main.YoshiBot;
import de.yannicpunktdee.yoshibot.utils.Logger; import de.yannicpunktdee.yoshibot.utils.Logger;
import de.yannicpunktdee.yoshibot.utils.Resources; import de.yannicpunktdee.yoshibot.utils.Resources;
import lombok.NonNull;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message.Attachment; import net.dv8tion.jda.api.entities.Message.Attachment;
import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.MessageEmbed;
@ -55,26 +56,29 @@ public abstract class YoshiCommand {
} }
return true; return true;
} }
protected final void sendMessage(String message){
protected final void sendMessage(String message) {
EmbedBuilder eb = new EmbedBuilder(); EmbedBuilder eb = new EmbedBuilder();
eb.setColor(Color.pink); eb.setColor(Color.pink);
eb.setDescription(message); eb.setDescription(message);
context.getEvent().getTextChannel().sendMessage(eb.build()).queue(); context.getEvent().getTextChannel().sendMessage(eb.build()).queue();
} }
protected final void sendFile(File file, String description){
protected final void sendFile(File file, String description) {
EmbedBuilder eb = new EmbedBuilder(); EmbedBuilder eb = new EmbedBuilder();
eb.setColor(Color.pink); eb.setColor(Color.pink);
if(description != null) eb.setDescription(description);
if (description != null) eb.setDescription(description);
context.getEvent().getTextChannel().sendFile(file).queue(); context.getEvent().getTextChannel().sendFile(file).queue();
} }
protected final void sendInfoMessage(String message){
protected final void sendInfoMessage(String message) {
EmbedBuilder eb = new EmbedBuilder(); EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("INFO"); eb.setTitle("INFO");
eb.setColor(Color.blue); eb.setColor(Color.blue);
eb.setDescription(message); eb.setDescription(message);
context.getEvent().getTextChannel().sendMessage(eb.build()).queue(); context.getEvent().getTextChannel().sendMessage(eb.build()).queue();
} }
protected final void sendErrorMessage(String message) { protected final void sendErrorMessage(String message) {
EmbedBuilder eb = new EmbedBuilder(); EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("ERROR"); eb.setTitle("ERROR");
@ -82,10 +86,11 @@ public abstract class YoshiCommand {
eb.setDescription(message); eb.setDescription(message);
context.getEvent().getTextChannel().sendMessage(eb.build()).queue(); context.getEvent().getTextChannel().sendMessage(eb.build()).queue();
} }
protected final void sendCustomMessage(MessageEmbed messageEmbed) { protected final void sendCustomMessage(MessageEmbed messageEmbed) {
context.getEvent().getTextChannel().sendMessage(messageEmbed).queue(); context.getEvent().getTextChannel().sendMessage(messageEmbed).queue();
} }
protected File downloadAttachmentToFile(String directoryPath, String name) { protected File downloadAttachmentToFile(String directoryPath, String name) {
if (directoryPath == null) directoryPath = Resources.getTempPath(); if (directoryPath == null) directoryPath = Resources.getTempPath();
@ -122,23 +127,25 @@ public abstract class YoshiCommand {
return file; return file;
} }
protected VoiceChannel getVoiceChannelByParam(){
protected VoiceChannel getVoiceChannelByParam() {
VoiceChannel vc; VoiceChannel vc;
if(context.containsArguments(new String[]{"channel"})){
if(context.getArgument("channel") == null) return null;
List<VoiceChannel> channels = YoshiBot.getInstance().jda.getVoiceChannelsByName(context.getArgument("channel"), true);
if (context.containsArguments(new String[]{"channel"})) {
if (context.getArgument("channel") == null) return null;
List<VoiceChannel> channels = YoshiBot.getInstance().jda
.getVoiceChannelsByName(context.getArgument("channel"), true);
if (!(channels.size() > 0)) { if (!(channels.size() > 0)) {
sendErrorMessage("Der Kanalname konnte nicht gefunden werden."); sendErrorMessage("Der Kanalname konnte nicht gefunden werden.");
return null; return null;
} }
vc = channels.get(0); vc = channels.get(0);
}else {
try{
} else {
try {
vc = context.getEvent().getMember().getVoiceState().getChannel(); vc = context.getEvent().getMember().getVoiceState().getChannel();
if(vc == null) vc = YoshiBot.getInstance().getGuild().getAudioManager().getConnectedChannel();
}catch (Exception e){
sendErrorMessage("Es konnte kein Voicekanal gefunden werden in dem die Audio-Datei abgespielt werden kann.");
if (vc == null) vc = YoshiBot.getInstance().getGuild().getAudioManager().getConnectedChannel();
} catch (Exception e) {
sendErrorMessage(
"Es konnte kein Voicekanal gefunden werden in dem die Audio-Datei abgespielt werden kann.");
return null; return null;
} }
} }


+ 9
- 9
app/src/main/java/de/yannicpunktdee/yoshibot/main/Main.java View File

@ -7,30 +7,30 @@ import java.net.URISyntaxException;
/** /**
* Main-Klasse und Startpunkt für die Bot-Applikation. * Main-Klasse und Startpunkt für die Bot-Applikation.
*
* @author Yannic Link * @author Yannic Link
*/ */
public class Main { public class Main {
/** /**
* Eintrittspunkt für die Applikation. Erzeugen eines neuen Yoshi-Bots und Starten. * Eintrittspunkt für die Applikation. Erzeugen eines neuen Yoshi-Bots und Starten.
*
* @param args Aufrufargumente. Werden später zum Konfigurieren genutzt. * @param args Aufrufargumente. Werden später zum Konfigurieren genutzt.
* @throws URISyntaxException
*
* @throws URISyntaxException
*/ */
public static void main(String[] args) throws URISyntaxException { public static void main(String[] args) throws URISyntaxException {
YoshiBot yoshiBot = YoshiBot.getInstance(); YoshiBot yoshiBot = YoshiBot.getInstance();
if(!yoshiBot.init((args.length > 0)? args[0] : null)){
if (!yoshiBot.init((args.length > 0) ? args[0] : null)) {
Logger.logError("Es ist ein Fehler beim Initialisieren der Ressourcen aufgetreten."); Logger.logError("Es ist ein Fehler beim Initialisieren der Ressourcen aufgetreten.");
return; return;
} }
Logger.logInfo("Ressourcen erfolgreich initialisiert. Starte Yoshi Bot ..."); Logger.logInfo("Ressourcen erfolgreich initialisiert. Starte Yoshi Bot ...");
try {
yoshiBot.start();
}catch(LoginException e) {
System.err.println("Es ist ein Fehler beim Login aufgetreten.");
}
yoshiBot.start();
} }
} }

+ 30
- 29
app/src/main/java/de/yannicpunktdee/yoshibot/main/YoshiBot.java View File

@ -13,6 +13,7 @@ import de.yannicpunktdee.yoshibot.command.YoshiCommandDistributor;
import de.yannicpunktdee.yoshibot.listeners.CommandLine; import de.yannicpunktdee.yoshibot.listeners.CommandLine;
import de.yannicpunktdee.yoshibot.listeners.DiscordEventListener; import de.yannicpunktdee.yoshibot.listeners.DiscordEventListener;
import de.yannicpunktdee.yoshibot.utils.Logger; import de.yannicpunktdee.yoshibot.utils.Logger;
import de.yannicpunktdee.yoshibot.utils.RedditProvider;
import de.yannicpunktdee.yoshibot.utils.Resources; import de.yannicpunktdee.yoshibot.utils.Resources;
import de.yannicpunktdee.yoshibot.utils.SauceProvider; import de.yannicpunktdee.yoshibot.utils.SauceProvider;
import lombok.Getter; import lombok.Getter;
@ -60,7 +61,7 @@ public final class YoshiBot {
* LavaPlayer AudioPlayerManager. * LavaPlayer AudioPlayerManager.
*/ */
public AudioPlayerManager audioPlayerManager; public AudioPlayerManager audioPlayerManager;
@Getter @Getter
private Guild guild; private Guild guild;
@ -80,11 +81,9 @@ public final class YoshiBot {
/** /**
* Startet den Bot und schaltet ihn online. Beginnt auf Konsoleneingaben für administrative Zwecke zu lauschen. * Startet den Bot und schaltet ihn online. Beginnt auf Konsoleneingaben für administrative Zwecke zu lauschen.
*
* @throws LoginException Falls das Token ungültig ist.
*/
**/
@SneakyThrows @SneakyThrows
public void start() throws LoginException {
public void start() {
System.out.println("Starte YoshiBot."); System.out.println("Starte YoshiBot.");
jdaBuilder = JDABuilder.createDefault(Resources.getJda_builder_string()); jdaBuilder = JDABuilder.createDefault(Resources.getJda_builder_string());
@ -120,8 +119,10 @@ public final class YoshiBot {
new SauceProvider(300); new SauceProvider(300);
//RedditProvider.init();
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(YoshiBot::setRandomActivity, 0, 10, TimeUnit.HOURS); Executors.newScheduledThreadPool(1).scheduleAtFixedRate(YoshiBot::setRandomActivity, 0, 10, TimeUnit.HOURS);
joinVoiceChannelWithMostMembers(); joinVoiceChannelWithMostMembers();
} }
@ -158,47 +159,47 @@ public final class YoshiBot {
yoshiBot.jda.getPresence().setActivity(Activity.playing(activity)); yoshiBot.jda.getPresence().setActivity(Activity.playing(activity));
Logger.logInfo("Setze Aktivität auf " + activity); Logger.logInfo("Setze Aktivität auf " + activity);
} }
public synchronized void joinVoiceChannel(VoiceChannel vc){
if(vc == null) {
public synchronized void joinVoiceChannel(VoiceChannel vc) {
if (vc == null) {
guild.getAudioManager().closeAudioConnection(); guild.getAudioManager().closeAudioConnection();
return; return;
} }
if(guild.getAudioManager().getConnectedChannel() != null &&
vc.getIdLong() == guild.getAudioManager().getConnectedChannel().getIdLong()) return;
if (guild.getAudioManager().getConnectedChannel() != null &&
vc.getIdLong() == guild.getAudioManager().getConnectedChannel().getIdLong()) return;
guild.getAudioManager().openAudioConnection(vc); guild.getAudioManager().openAudioConnection(vc);
} }
public void joinVoiceChannelWithMostMembers(){
public void joinVoiceChannelWithMostMembers() {
VoiceChannel maxVoiceChannel = null; VoiceChannel maxVoiceChannel = null;
int maxMembers = 0; int maxMembers = 0;
for(VoiceChannel vc : guild.getVoiceChannels()){
for (VoiceChannel vc : guild.getVoiceChannels()) {
int membersInChannel = 0; int membersInChannel = 0;
for(Member m : vc.getMembers())
if(!m.getUser().isBot()) membersInChannel++;
if(membersInChannel > maxMembers){
for (Member m : vc.getMembers())
if (!m.getUser().isBot()) membersInChannel++;
if (membersInChannel > maxMembers) {
maxVoiceChannel = vc; maxVoiceChannel = vc;
maxMembers = membersInChannel;
maxMembers = membersInChannel;
} }
} }
if(maxMembers < 1) joinVoiceChannel(null);
else if(maxMembers > 0 && maxVoiceChannel != null)
if (maxMembers < 1) joinVoiceChannel(null);
else if (maxMembers > 0 && maxVoiceChannel != null)
joinVoiceChannel(maxVoiceChannel); joinVoiceChannel(maxVoiceChannel);
} }
public boolean playSound(File file, VoiceChannel vc){
public boolean playSound(File file, VoiceChannel vc) {
if (!file.isFile()) return false; if (!file.isFile()) return false;
joinVoiceChannel(vc); joinVoiceChannel(vc);
audioPlayerManager.loadItem(file.getAbsolutePath(), new AudioLoadResultHandlerImpl()); audioPlayerManager.loadItem(file.getAbsolutePath(), new AudioLoadResultHandlerImpl());
return true; return true;
} }
public boolean sayTTS(String text, VoiceChannel vc) { public boolean sayTTS(String text, VoiceChannel vc) {
String path = Resources.getTempPath() + UUID.randomUUID() + ".opus"; String path = Resources.getTempPath() + UUID.randomUUID() + ".opus";
try { try {
ProcessBuilder pb = new ProcessBuilder( ProcessBuilder pb = new ProcessBuilder(
"python3", "python3",
@ -209,7 +210,7 @@ public final class YoshiBot {
"de", "de",
"--out", "--out",
path); path);
Process p = pb.start(); Process p = pb.start();
BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream())); BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -224,7 +225,7 @@ public final class YoshiBot {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
return playSound(new File(path), vc); return playSound(new File(path), vc);
} }


+ 38
- 0
app/src/main/java/de/yannicpunktdee/yoshibot/utils/RedditProvider.java View File

@ -0,0 +1,38 @@
package de.yannicpunktdee.yoshibot.utils;
import lombok.Getter;
import net.dean.jraw.RedditClient;
import net.dean.jraw.http.NetworkAdapter;
import net.dean.jraw.http.OkHttpNetworkAdapter;
import net.dean.jraw.http.UserAgent;
import net.dean.jraw.oauth.Credentials;
import net.dean.jraw.oauth.OAuthHelper;
public final class RedditProvider {
@Getter
private static boolean isInit = false;
private static RedditClient reddit;
public static void init() {
if (isInit) Logger.logWarning("RedditProvider wird reinitialisiert");
String username = Resources.getRedditData().get("username");
String password = Resources.getRedditData().get("password");
String clientId = Resources.getRedditData().get("client_id");
String clientSecret = Resources.getRedditData().get("client_secret");
UserAgent userAgent = new UserAgent("bot", "de.yannicpunktdee.yoshibot", "v1", username);
Credentials creds = Credentials.script(username, password, clientId, clientSecret);
NetworkAdapter adapter = new OkHttpNetworkAdapter(userAgent);
reddit = OAuthHelper.automatic(adapter, creds);
isInit = true;
}
}

+ 25
- 7
app/src/main/java/de/yannicpunktdee/yoshibot/utils/Resources.java View File

@ -13,6 +13,7 @@ import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
public final class Resources { public final class Resources {
@ -23,7 +24,7 @@ public final class Resources {
private static String configPath; private static String configPath;
@Getter @Getter
private static String audioPath; private static String audioPath;
private static String tempPath; private static String tempPath;
@Getter @Getter
private static String activitiesPath; private static String activitiesPath;
@ -45,6 +46,9 @@ public final class Resources {
@Getter @Getter
private static String jda_builder_string; private static String jda_builder_string;
@Getter
private static Map<String, String> redditData;
@Getter @Getter
private static Long guild_id; private static Long guild_id;
@ -62,6 +66,7 @@ public final class Resources {
private static final Map<String, List<String>> feedDetails = new HashMap<>(); private static final Map<String, List<String>> feedDetails = new HashMap<>();
private static Properties propertiesFile; private static Properties propertiesFile;
private static Properties redditCreds;
public synchronized static boolean init(String resourcePathArg) { public synchronized static boolean init(String resourcePathArg) {
@ -80,6 +85,7 @@ public final class Resources {
if (isOk) isOk = initPatPngPath(); if (isOk) isOk = initPatPngPath();
if (isOk) isOk = initImages(); if (isOk) isOk = initImages();
if (isOk) isOk = initBonkPngPath(); if (isOk) isOk = initBonkPngPath();
if (isOk) isOk = initReddit();
if (isOk) Logger.logInfo("Die Konfigurationen wurden erfolgreich geladen."); if (isOk) Logger.logInfo("Die Konfigurationen wurden erfolgreich geladen.");
else Logger.logError("Die Konfiguration konnte nicht geladen werden"); else Logger.logError("Die Konfiguration konnte nicht geladen werden");
@ -107,6 +113,9 @@ public final class Resources {
propertiesFile = new Properties(); propertiesFile = new Properties();
propertiesFile.load(new FileInputStream(configPath)); propertiesFile.load(new FileInputStream(configPath));
redditCreds = new Properties();
redditCreds.load(new FileInputStream(resourcePath + "RedditCredentials.properties"));
return true; return true;
} }
@ -137,14 +146,23 @@ public final class Resources {
return false; return false;
} }
} }
public static String getTempPath(){
public static String getTempPath() {
if (tempPath == null){
initTemp();
}
File tempDir = new File(tempPath); File tempDir = new File(tempPath);
if(!tempDir.isDirectory())
if(!tempDir.mkdir()) return null;
if (!tempDir.isDirectory())
if (!tempDir.mkdir()) throw new Error("Could not make Temp directory");
return tempPath; return tempPath;
} }
private static boolean initReddit() {
redditData = redditCreds.stringPropertyNames().stream()
.collect(Collectors.toMap(p -> p, property -> redditCreds.getProperty(property)));
return true;
}
private static boolean initActivities() { private static boolean initActivities() {
activitiesPath = verifyExists(resourcePath + "activities.txt", File::isFile); activitiesPath = verifyExists(resourcePath + "activities.txt", File::isFile);
return activitiesPath != null; return activitiesPath != null;
@ -174,7 +192,7 @@ public final class Resources {
patPngPath = verifyExists(resourcePath + "pats/", File::isDirectory); patPngPath = verifyExists(resourcePath + "pats/", File::isDirectory);
return patPngPath != null; return patPngPath != null;
} }
private static boolean initBonkPngPath() { private static boolean initBonkPngPath() {
bonkPngPath = verifyExists(resourcePath + "bonks/", File::isDirectory); bonkPngPath = verifyExists(resourcePath + "bonks/", File::isDirectory);
return bonkPngPath != null; return bonkPngPath != null;
@ -282,7 +300,7 @@ public final class Resources {
private static String verifyExists(String filename, Function<File, Boolean> checkIsValidFile) { private static String verifyExists(String filename, Function<File, Boolean> checkIsValidFile) {
String[] split = filename.split("/"); String[] split = filename.split("/");
Logger.logInfo(String.format("Versuche %s zu finden.", split[split.length - 1]));
Logger.logDebug(String.format("Versuche %s zu finden.", split[split.length - 1]));
if (checkIsValidFile.apply(new File(filename))) { if (checkIsValidFile.apply(new File(filename))) {
return filename; return filename;
} else { } else {


Loading…
Cancel
Save