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.
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 "net.dean.jraw:JRAW:1.1.0"
compileOnly 'org.projectlombok:lombok:1.18.16'
annotationProcessor 'org.projectlombok:lombok:1.18.16'
}
@ -42,11 +44,11 @@ application {
mainClass = "$mainClassName"
}
jar{
manifest{
jar {
manifest {
attributes "Main-Class": "$mainClassName"
}
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.utils.Logger;
import de.yannicpunktdee.yoshibot.utils.Resources;
import lombok.NonNull;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message.Attachment;
import net.dv8tion.jda.api.entities.MessageEmbed;
@ -55,26 +56,29 @@ public abstract class YoshiCommand {
}
return true;
}
protected final void sendMessage(String message){
protected final void sendMessage(String message) {
EmbedBuilder eb = new EmbedBuilder();
eb.setColor(Color.pink);
eb.setDescription(message);
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();
eb.setColor(Color.pink);
if(description != null) eb.setDescription(description);
if (description != null) eb.setDescription(description);
context.getEvent().getTextChannel().sendFile(file).queue();
}
protected final void sendInfoMessage(String message){
protected final void sendInfoMessage(String message) {
EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("INFO");
eb.setColor(Color.blue);
eb.setDescription(message);
context.getEvent().getTextChannel().sendMessage(eb.build()).queue();
}
protected final void sendErrorMessage(String message) {
EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("ERROR");
@ -82,10 +86,11 @@ public abstract class YoshiCommand {
eb.setDescription(message);
context.getEvent().getTextChannel().sendMessage(eb.build()).queue();
}
protected final void sendCustomMessage(MessageEmbed messageEmbed) {
context.getEvent().getTextChannel().sendMessage(messageEmbed).queue();
}
protected File downloadAttachmentToFile(String directoryPath, String name) {
if (directoryPath == null) directoryPath = Resources.getTempPath();
@ -122,23 +127,25 @@ public abstract class YoshiCommand {
return file;
}
protected VoiceChannel getVoiceChannelByParam(){
protected VoiceChannel getVoiceChannelByParam() {
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)) {
sendErrorMessage("Der Kanalname konnte nicht gefunden werden.");
return null;
}
vc = channels.get(0);
}else {
try{
} else {
try {
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;
}
}


+ 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.
*
* @author Yannic Link
*/
public class Main {
/**
* Eintrittspunkt für die Applikation. Erzeugen eines neuen Yoshi-Bots und Starten.
*
* @param args Aufrufargumente. Werden später zum Konfigurieren genutzt.
* @throws URISyntaxException
*
* @throws URISyntaxException
*/
public static void main(String[] args) throws URISyntaxException {
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.");
return;
}
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.DiscordEventListener;
import de.yannicpunktdee.yoshibot.utils.Logger;
import de.yannicpunktdee.yoshibot.utils.RedditProvider;
import de.yannicpunktdee.yoshibot.utils.Resources;
import de.yannicpunktdee.yoshibot.utils.SauceProvider;
import lombok.Getter;
@ -60,7 +61,7 @@ public final class YoshiBot {
* LavaPlayer AudioPlayerManager.
*/
public AudioPlayerManager audioPlayerManager;
@Getter
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.
*
* @throws LoginException Falls das Token ungültig ist.
*/
**/
@SneakyThrows
public void start() throws LoginException {
public void start() {
System.out.println("Starte YoshiBot.");
jdaBuilder = JDABuilder.createDefault(Resources.getJda_builder_string());
@ -120,8 +119,10 @@ public final class YoshiBot {
new SauceProvider(300);
//RedditProvider.init();
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(YoshiBot::setRandomActivity, 0, 10, TimeUnit.HOURS);
joinVoiceChannelWithMostMembers();
}
@ -158,47 +159,47 @@ public final class YoshiBot {
yoshiBot.jda.getPresence().setActivity(Activity.playing(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();
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);
}
public void joinVoiceChannelWithMostMembers(){
public void joinVoiceChannelWithMostMembers() {
VoiceChannel maxVoiceChannel = null;
int maxMembers = 0;
for(VoiceChannel vc : guild.getVoiceChannels()){
for (VoiceChannel vc : guild.getVoiceChannels()) {
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;
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);
}
public boolean playSound(File file, VoiceChannel vc){
public boolean playSound(File file, VoiceChannel vc) {
if (!file.isFile()) return false;
joinVoiceChannel(vc);
audioPlayerManager.loadItem(file.getAbsolutePath(), new AudioLoadResultHandlerImpl());
return true;
}
public boolean sayTTS(String text, VoiceChannel vc) {
String path = Resources.getTempPath() + UUID.randomUUID() + ".opus";
try {
ProcessBuilder pb = new ProcessBuilder(
"python3",
@ -209,7 +210,7 @@ public final class YoshiBot {
"de",
"--out",
path);
Process p = pb.start();
BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuilder builder = new StringBuilder();
@ -224,7 +225,7 @@ public final class YoshiBot {
e.printStackTrace();
return false;
}
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.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public final class Resources {
@ -23,7 +24,7 @@ public final class Resources {
private static String configPath;
@Getter
private static String audioPath;
private static String tempPath;
@Getter
private static String activitiesPath;
@ -45,6 +46,9 @@ public final class Resources {
@Getter
private static String jda_builder_string;
@Getter
private static Map<String, String> redditData;
@Getter
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 Properties propertiesFile;
private static Properties redditCreds;
public synchronized static boolean init(String resourcePathArg) {
@ -80,6 +85,7 @@ public final class Resources {
if (isOk) isOk = initPatPngPath();
if (isOk) isOk = initImages();
if (isOk) isOk = initBonkPngPath();
if (isOk) isOk = initReddit();
if (isOk) Logger.logInfo("Die Konfigurationen wurden erfolgreich geladen.");
else Logger.logError("Die Konfiguration konnte nicht geladen werden");
@ -107,6 +113,9 @@ public final class Resources {
propertiesFile = new Properties();
propertiesFile.load(new FileInputStream(configPath));
redditCreds = new Properties();
redditCreds.load(new FileInputStream(resourcePath + "RedditCredentials.properties"));
return true;
}
@ -137,14 +146,23 @@ public final class Resources {
return false;
}
}
public static String getTempPath(){
public static String getTempPath() {
if (tempPath == null){
initTemp();
}
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;
}
private static boolean initReddit() {
redditData = redditCreds.stringPropertyNames().stream()
.collect(Collectors.toMap(p -> p, property -> redditCreds.getProperty(property)));
return true;
}
private static boolean initActivities() {
activitiesPath = verifyExists(resourcePath + "activities.txt", File::isFile);
return activitiesPath != null;
@ -174,7 +192,7 @@ public final class Resources {
patPngPath = verifyExists(resourcePath + "pats/", File::isDirectory);
return patPngPath != null;
}
private static boolean initBonkPngPath() {
bonkPngPath = verifyExists(resourcePath + "bonks/", File::isDirectory);
return bonkPngPath != null;
@ -282,7 +300,7 @@ public final class Resources {
private static String verifyExists(String filename, Function<File, Boolean> checkIsValidFile) {
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))) {
return filename;
} else {


Loading…
Cancel
Save