Compare commits

..

1 Commits

Author SHA1 Message Date
239d89e42a Almost fix music 2022-05-14 19:26:08 +02:00
161 changed files with 23918 additions and 22225 deletions

View File

@ -17,10 +17,10 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK 17 - name: Set up JDK 1.8
uses: actions/setup-java@v1 uses: actions/setup-java@v1
with: with:
java-version: 17 java-version: 1.8
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew
@ -35,9 +35,8 @@ jobs:
path: build/libs/ path: build/libs/
build-docker: build-docker:
runs-on: ubuntu-latest runs-on: [ ubuntu-latest ]
needs: needs: [ build-gradle ]
- build-gradle
if: github.ref == 'refs/heads/master' if: github.ref == 'refs/heads/master'
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2

View File

@ -1,4 +1,4 @@
FROM openjdk:17.0.2 FROM openjdk:8-jre-buster
WORKDIR /bot_src WORKDIR /bot_src
ARG BUILD_NBR ARG BUILD_NBR
ARG BRANCH_NAME ARG BRANCH_NAME
@ -6,5 +6,7 @@ ARG BRANCH_NAME
ARG GITHUB_RUN_NUMBER ARG GITHUB_RUN_NUMBER
ADD build/libs/ClaptrapBot-*.jar /bot_src/bot.jar ADD build/libs/ClaptrapBot-*.jar /bot_src/bot.jar
RUN java -version RUN java -version
CMD java -jar bot.jar ENV PORT=8080
ENV TOKEN=10
CMD java -jar bot.jar -t ${TOKEN}
LABEL org.opencontainers.image.source=https://github.com/Sebclem/ClaptrapBot/ LABEL org.opencontainers.image.source=https://github.com/Sebclem/ClaptrapBot/

View File

@ -1,7 +1,6 @@
<p align="center"><img alt="discord" src="https://claptrapbot.com/favicon.png" width="150"/></p> <p align="center"><img alt="discord" src="https://claptrapbot.com/favicon.png" width="150"/></p>
# ClaptrapBot: A multifunctional Discord Bot ! # ClaptrapBot: A multifunctional Discord Bot !
[![GitHub Release][releases-shield]][releases] [![GitHub Release][releases-shield]][releases]
![Project Stage][project-stage-shield] ![Project Stage][project-stage-shield]
[![License][license-shield]](LICENSE.md) [![License][license-shield]](LICENSE.md)
@ -10,20 +9,16 @@
![Project Maintenance][maintenance-shield] ![Project Maintenance][maintenance-shield]
[![Buy me a coffee][buymeacoffee-shield]][buymeacoffee] [![Buy me a coffee][buymeacoffee-shield]][buymeacoffee]
## About
## About
ClaptrapBot is a Discord bot. (No way! :open_mouth:) ClaptrapBot is a Discord bot. (No way! :open_mouth:)
### Features: ### Features:
- :notes: Music bot with a cool web control interface ! - :notes: Music bot with a cool web control interface !
- :bar_chart: Rank and Stats ! (Text and voice) - :bar_chart: Rank and Stats ! (Text and voice)
- :heart_eyes: NSFW Commands ! (With a daily surprise :kissing_heart:) - :heart_eyes: NSFW Commands ! (With a daily surprise :kissing_heart:)
- :hammer_and_pick: Moderation commands ! - :hammer_and_pick: Moderation commands !
You can add the bot to your server from the home page: https://claptrapbot.com/ You can add the bot to your server from the home page: https://claptrapbot.com/
## Authors & contributors ## Authors & contributors
The original development is by [SebClem][Sebclem]. The original development is by [SebClem][Sebclem].
@ -60,28 +55,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
[license-shield]: https://img.shields.io/github/license/Sebclem/ClaptrapBot.svg [license-shield]: https://img.shields.io/github/license/Sebclem/ClaptrapBot.svg
[build-badge]: https://img.shields.io/github/workflow/status/Sebclem/ClaptrapBot/Build [build-badge]: https://img.shields.io/github/workflow/status/Sebclem/ClaptrapBot/Build
[maintenance-shield]: https://img.shields.io/maintenance/yes/2020.svg [maintenance-shield]: https://img.shields.io/maintenance/yes/2020.svg
[project-stage-shield]: https://img.shields.io/badge/project%20stage-Beta-red.svg [project-stage-shield]: https://img.shields.io/badge/project%20stage-Beta-red.svg
[buymeacoffee-shield]: https://www.buymeacoffee.com/assets/img/guidelines/download-assets-sm-2.svg [buymeacoffee-shield]: https://www.buymeacoffee.com/assets/img/guidelines/download-assets-sm-2.svg
[buymeacoffee]: https://www.buymeacoffee.com/seb6596 [buymeacoffee]: https://www.buymeacoffee.com/seb6596
[issue]: https://github.com/hassio-addons/addon-log-viewer/issues [issue]: https://github.com/hassio-addons/addon-log-viewer/issues
[releases-shield]: https://img.shields.io/github/release/Sebclem/ClaptrapBot.svg?include_prereleases [releases-shield]: https://img.shields.io/github/release/Sebclem/ClaptrapBot.svg?include_prereleases
[releases]: https://github.com/Sebclem/ClaptrapBot/releases [releases]: https://github.com/Sebclem/ClaptrapBot/releases
[Sebclem]: https://github.com/Sebclem [Sebclem]: https://github.com/Sebclem
[alex]: https://github.com/Alexandre064 [alex]: https://github.com/Alexandre064
[Aeka]: https://twitter.com/Le_aeka [Aeka]: https://twitter.com/Le_aeka
[contributors]: https://github.com/Sebclem/ClaptrapBot/graphs/contributors [contributors]: https://github.com/Sebclem/ClaptrapBot/graphs/contributors

View File

@ -15,31 +15,44 @@ version = "$versionObj"
sourceCompatibility = '17' sourceCompatibility = '17'
jar.doFirst {
delete "${buildDir}/libs/*"
}
jar {
// delete "${buildDir}/libs/*"
// baseName = 'DiscordBot'
}
repositories { repositories {
mavenCentral() mavenCentral()
jcenter()
maven { maven {
url 'https://m2.dv8tion.net/releases' url 'https://m2.dv8tion.net/releases'
} }
} }
jar {
enabled(false)
}
dependencies { dependencies {
implementation("org.springframework.boot:spring-boot-starter-web") { implementation("org.springframework.boot:spring-boot-starter-web"){
exclude group: "org.springframework.boot", module: "spring-boot-starter-logging" exclude group:"org.springframework.boot", module: "spring-boot-starter-logging"
} }
implementation("org.springframework.boot:spring-boot-starter-log4j2") implementation("org.springframework.boot:spring-boot-starter-log4j2")
implementation 'org.codehaus.groovy:groovy-all:3.0.8' implementation 'org.codehaus.groovy:groovy-all:3.0.8'
implementation 'com.sedmelluq:lavaplayer:1.3.77' implementation 'com.sedmelluq:lavaplayer:1.3.77'
implementation 'net.dv8tion:JDA:4.4.0_350' implementation 'net.dv8tion:JDA:4.4.0_350'
implementation group: 'org.json', name: 'json', version: '20210307' implementation group: 'org.json', name: 'json', version: '20210307'
implementation 'org.springframework.security:spring-security-web:5.5.0' implementation 'org.springframework.security:spring-security-web:5.5.0'
// JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...)
implementation("org.springframework.boot:spring-boot-starter-data-jpa") { implementation("org.springframework.boot:spring-boot-starter-data-jpa") {
exclude group: "org.springframework.boot", module: "spring-boot-starter-logging" exclude group:"org.springframework.boot", module: "spring-boot-starter-logging"
} }
implementation(platform("org.apache.logging.log4j:log4j-bom:2.17.1")) implementation(platform("org.apache.logging.log4j:log4j-bom:2.17.1"))
// Use MySQL Connector-J // Use MySQL Connector-J
@ -54,7 +67,7 @@ dependencies {
implementation("org.springframework.boot:spring-boot-starter-thymeleaf") { implementation("org.springframework.boot:spring-boot-starter-thymeleaf") {
exclude group: "org.springframework.boot", module: "spring-boot-starter-logging" exclude group:"org.springframework.boot", module: "spring-boot-starter-logging"
} }
} }
@ -63,7 +76,7 @@ class Version {
static String getBuild() { static String getBuild() {
System.getenv("GITHUB_RUN_NUMBER") ?: System.getProperty("BUILD_NUMBER") ?: System.getenv("GITHUB_RUN_NUMBER") ?: System.getProperty("BUILD_NUMBER") ?:
System.getenv("GIT_COMMIT")?.substring(0, 7) ?: System.getProperty("GIT_COMMIT")?.substring(0, 7) ?: "DEV" System.getenv("GIT_COMMIT")?.substring(0, 7) ?: System.getProperty("GIT_COMMIT")?.substring(0, 7) ?:"DEV"
} }
String toString() { String toString() {

View File

@ -1,17 +1,16 @@
package net.Broken; package net.Broken;
import net.Broken.Commands.Move;
import net.Broken.DB.Entity.GuildPreferenceEntity; import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository; import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.Tools.AutoVoiceChannel; import net.Broken.DB.Repository.UserRepository;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.*;
import net.Broken.Tools.Command.CommandParser;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils; import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.Broken.audio.AudioM; import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent; import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
@ -21,13 +20,16 @@ import net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.managers.GuildManager;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.awt.*; import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -36,59 +38,84 @@ import java.util.List;
* Bot Listener * Bot Listener
*/ */
public class BotListener extends ListenerAdapter { public class BotListener extends ListenerAdapter {
private final GuildPreferenceRepository guildPreferenceRepository; private AntiSpam antispam = new AntiSpam();
private Moderateur modo = new Moderateur();
private final Logger logger = LogManager.getLogger(); private GuildPreferenceRepository guildPreferenceRepository;
private UserRepository userRepository;
private Logger logger = LogManager.getLogger();
public BotListener() { public BotListener() {
ApplicationContext context = SpringContext.getAppContext(); ApplicationContext context = SpringContext.getAppContext();
guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository"); guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository");
userRepository = (UserRepository) context.getBean("userRepository");
} }
@Override @Override
public void onReady(ReadyEvent event) { public void onReady(ReadyEvent event) {
logger.info("Connection success"); logger.info("Connection succees");
} }
@Override @Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) { public void onGuildMemberJoin(GuildMemberJoinEvent event) {
GuildPreferenceEntity guildPref = getPreference(event.getGuild()); GuildPreferenceEntity guildPref = getPreference(event.getGuild());
if (guildPref.isDefaultRole()) { if (guildPref.isDefaultRole()) {
logger.info("[" + event.getGuild().getName() + "] : " + event.getUser().getName() + " join the guild, adding default role !");
Role default_role = event.getGuild().getRoleById(guildPref.getDefaultRoleId()); logger.info(event.getUser().getName() + "join the guild, move it!");
if (default_role != null) {
event.getGuild().addRoleToMember(event.getMember(), default_role).queue(); List<Role> roles = new ArrayList<>();
} else { roles.add(event.getGuild().getRoleById(guildPref.getDefaultRoleId()));
logger.fatal("[" + event.getGuild().getName() + "] : Default role is null !");
}
new Move().exc(event.getMember(), roles, false, event.getGuild(), event.getGuild().getManager());
} }
if (guildPref.isWelcome()) { if (guildPref.isWelcome()) {
TextChannel chanel = event.getGuild().getTextChannelById(guildPref.getWelcomeChanelID()); TextChannel chanel = event.getGuild().getTextChannelById(guildPref.getWelcomeChanelID());
if (chanel != null) { if (chanel != null) {
String message = guildPref.getWelcomeMessage().replaceAll("@name", event.getMember().getAsMention()); String message = guildPref.getWelcomeMessage();
message = message.replaceAll("@name", event.getMember().getAsMention());
logger.debug(message); logger.debug(message);
chanel.sendMessage(message).queue(); chanel.sendMessage(message).complete();
}else {
logger.fatal("[" + event.getGuild().getName() + "] : Welcome chanel is null !");
} }
MainBot.roleFlag = false;
} }
} }
@Override @Override
public void onGuildMemberRoleRemove(GuildMemberRoleRemoveEvent event) { public void onGuildMemberRoleRemove(GuildMemberRoleRemoveEvent event) {
GuildPreferenceEntity guildPref = getPreference(event.getGuild()); GuildPreferenceEntity guildPref = getPreference(event.getGuild());
if (guildPref.isDefaultRole()) { if (guildPref.isDefaultRole()) {
if (event.getMember().getRoles().size() == 0) {
logger.info("[" + event.getGuild().getName() + "] : " + event.getUser().getName() + " have no roles, reset to default !"); if (!MainBot.roleFlag) {
Role default_role = event.getGuild().getRoleById(guildPref.getDefaultRoleId());
if (default_role == null) { if (event.getMember().getRoles().size() == 0) {
logger.fatal("[" + event.getGuild().getName() + "] : Default role is null !");
return; logger.info(event.getUser().getName() + "have no roles, move it!");
List<Role> roles = new ArrayList<>();
roles.add(event.getGuild().getRoleById(guildPref.getDefaultRoleId()));
new Move().exc(event.getMember(), roles, false, event.getGuild(), event.getGuild().getManager());
MainBot.roleFlag = false;
} }
event.getGuild().addRoleToMember(event.getMember(), default_role).queue(); } else {
logger.debug("ignore it");
MainBot.roleFlag = false;
} }
} }
@ -136,16 +163,66 @@ public class BotListener extends ListenerAdapter {
@Override @Override
public void onMessageReceived(MessageReceivedEvent event) { public void onMessageReceived(MessageReceivedEvent event) {
if (!event.getAuthor().isBot()) { if (!event.getAuthor().isBot()) {
UserStatsUtils.getINSTANCE().addMessageCount(event.getMember()); UserStatsUtils.getINSTANCE().addMessageCount(event.getMember());
} }
try {
if (event.getMessage().getContentRaw().startsWith("//") && !event.getMessage().getAuthor().getId().equals(event.getJDA().getSelfUser().getId())) {
//On a detecter que c'etait une commande
//System.out.println(event.getMessage().getContent());
List<UserEntity> users = userRepository.findByJdaId(event.getAuthor().getId());
UserEntity user = users.size() == 0 ? null : users.get(0);
MainBot.handleCommand(new CommandParser().parse(event.getMessage().getContentRaw(), event), user);
} else if (!event.getMessage().getAuthor().getId().equals(event.getJDA().getSelfUser().getId())) {
if (!event.isFromType(ChannelType.PRIVATE)) {
Guild serveur = event.getGuild();
GuildPreferenceEntity guildPref = getPreference(serveur);
if (!guildPref.isAntiSpam())
return;
try {
GuildManager guildManager = serveur.getManager();
Member user = event.getMember();
// appel de la methode d'analyse de message de "Moderateur"
if (event.getMessage().getContentRaw().length() > 0) {
if (modo.analyse(user, serveur, guildManager, event) == 1) {
antispam.extermine(user, serveur, guildManager, true, event);
}
} else if (event.getMessage().getContentRaw().length() == 0)
logger.error("Image detected, ignoring it.");
} catch (InsufficientPermissionException e) {
logger.warn("Insufficient permission for guild " + e.getGuild(MainBot.jda).getName() + " Missing " + e.getPermission() + " permission.");
}
}
}
} catch (Exception e) {
logger.catching(e);
if (event.isFromType(ChannelType.PRIVATE))
PrivateMessage.send(event.getAuthor(), EmbedMessageUtils.getInternalError(), logger);
else
event.getTextChannel().sendMessage(EmbedMessageUtils.getInternalError()).queue();
}
} }
@Override @Override
public void onSlashCommand(@NotNull SlashCommandEvent event) { public void onSlashCommand(@NotNull SlashCommandEvent event) {
HashMap<String, SlashCommand> commands = MainBot.slashCommands; HashMap<String, SlashCommand> commands = MainBot.slashCommands;
super.onSlashCommand(event); super.onSlashCommand(event);
if (commands.containsKey(event.getName())) { if(commands.containsKey(event.getName())){
commands.get(event.getName()).action(event); commands.get(event.getName()).action(event);
} }
} }
@ -160,15 +237,14 @@ public class BotListener extends ListenerAdapter {
.setDescription("Allow me to introduce myself -- I am a CL4P-TP the discord bot, but my friends call me Claptrap ! Or they would, if any of them were real...\n" + .setDescription("Allow me to introduce myself -- I am a CL4P-TP the discord bot, but my friends call me Claptrap ! Or they would, if any of them were real...\n" +
"\nYou can access to my web UI with: " + MainBot.url) "\nYou can access to my web UI with: " + MainBot.url)
.setImage("https://i.imgur.com/Anf1Srg.gif"); .setImage("https://i.imgur.com/Anf1Srg.gif");
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.buildStandar(eb)).build();
TextChannel defaultChan = event.getGuild().getDefaultChannel(); TextChannel defaultChan = event.getGuild().getDefaultChannel();
if (defaultChan != null && defaultChan.canTalk()) { if (defaultChan != null && defaultChan.canTalk())
defaultChan.sendMessage(message).queue(); defaultChan.sendMessage(EmbedMessageUtils.buildStandar(eb)).queue();
} else { else {
for (TextChannel chan : event.getGuild().getTextChannels()) { for(TextChannel chan : event.getGuild().getTextChannels()){
if (chan.canTalk()) { if(chan.canTalk()){
chan.sendMessage(message).queue(); chan.sendMessage(EmbedMessageUtils.buildStandar(eb)).queue();
} }
} }
} }
@ -178,9 +254,9 @@ public class BotListener extends ListenerAdapter {
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId()); List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref; GuildPreferenceEntity guildPref;
if (guildPrefList.isEmpty()) { if (guildPrefList.isEmpty()) {
logger.info("[" + guild.getName() + "] : Generate default pref"); logger.info("Generate default pref");
guildPref = GuildPreferenceEntity.getDefault(guild); guildPref = GuildPreferenceEntity.getDefault(guild);
guildPref = guildPreferenceRepository.save(guildPref); guildPreferenceRepository.save(guildPref);
} else } else
guildPref = guildPrefList.get(0); guildPref = guildPrefList.get(0);
return guildPref; return guildPref;

View File

@ -9,36 +9,31 @@ import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
public interface Commande { public interface Commande {
/** /**
* Main action of command * Main action of command
* * @param args Command args.
* @param args Command args.
* @param event Command MessageReceivedEvent * @param event Command MessageReceivedEvent
*/ */
void action(String[] args, MessageReceivedEvent event); void action(String[] args, MessageReceivedEvent event);
/** /**
* Determines if the command is usable whit private message * Determines if the command is usable whit private message
*
* @return boolean * @return boolean
*/ */
boolean isPrivateUsable(); boolean isPrivateUsable();
/** /**
* Determines if the command is usable only by admin user * Determines if the command is usable only by admin user
*
* @return boolean * @return boolean
*/ */
boolean isAdminCmd(); boolean isAdminCmd();
/** /**
* Determines if the command is usable only by bot level admin user * Determines if the command is usable only by bot level admin user
*
* @return boolean * @return boolean
*/ */
boolean isBotAdminCmd(); boolean isBotAdminCmd();
/** /**
* Determines if the command is only usable on NSFW channels * Determines if the command is only usable on NSFW channels
*
* @return boolean * @return boolean
*/ */
boolean isNSFW(); boolean isNSFW();

View File

@ -0,0 +1,73 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* Command that return a random picture of cat.
*/
public class Cat implements Commande {
@Override
public void action(String[] args, MessageReceivedEvent event) {
if(!event.isFromType(ChannelType.PRIVATE))
{
try {
URL urlC = new URL("http://aws.random.cat/meow");
URLConnection yc = urlC.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
JSONObject json = new JSONObject(a.toString());
event.getTextChannel().sendMessage(json.getString("file")).queue();
} catch (IOException e) {
e.printStackTrace();
}
}
else
event.getPrivateChannel().sendMessage("\n:warning: **__This command cannot be used there !__** :warning:").queue();
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -3,6 +3,7 @@ package net.Broken.Commands;
import net.Broken.Commande; import net.Broken.Commande;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageHistory;
import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -23,19 +24,20 @@ public class ChannelsReview implements Commande {
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
DateFormat format = new SimpleDateFormat("dd.MM.yyyy"); DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
event.getTextChannel().sendMessage("Number of channels found in total : " + event.getGuild().getTextChannels().size()).queue(); event.getTextChannel().sendMessage("Number of channels found in total : " + event.getGuild().getTextChannels().size()).queue();
if (args.length >= 1) { if(args.length>=1){
try { try {
SendBackBefore(format.parse(args[0]), event, format); SendBackBefore(format.parse(args[0]), event, format );
} catch (ParseException e) { } catch (ParseException e) {
logger.warn("Can't parse date : " + e.getMessage()); logger.warn("Can't parse date : " + e.getMessage());
} }
} else { }
else{
SendBack(event); SendBack(event);
} }
} }
private void SendBackBefore(Date beforeDate, MessageReceivedEvent event, DateFormat format) { private void SendBackBefore(Date beforeDate,MessageReceivedEvent event,DateFormat format ){
HashMap<String, String> result = new HashMap<>(); HashMap<String, String> result = new HashMap<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy").withLocale(Locale.ENGLISH); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy").withLocale(Locale.ENGLISH);
int charCtl = 0; int charCtl = 0;
@ -44,7 +46,7 @@ public class ChannelsReview implements Commande {
String lastMessageId = textChannel.getLatestMessageId(); String lastMessageId = textChannel.getLatestMessageId();
try { try {
Message lastMessage = textChannel.retrieveMessageById(lastMessageId).complete(); Message lastMessage = textChannel.retrieveMessageById(lastMessageId).complete();
if (beforeDate.compareTo(format.parse(lastMessage.getTimeCreated().format(formatter))) > 0) { if(beforeDate.compareTo(format.parse(lastMessage.getTimeCreated().format(formatter)))>0){
logger.debug("Last message in channel " + textChannel.toString() + " is " + lastMessageId); logger.debug("Last message in channel " + textChannel.toString() + " is " + lastMessageId);
String date = lastMessage.getTimeCreated().format(formatter); String date = lastMessage.getTimeCreated().format(formatter);
charCtl += textChannel.getName().length() + date.length(); charCtl += textChannel.getName().length() + date.length();
@ -70,7 +72,7 @@ public class ChannelsReview implements Commande {
event.getTextChannel().sendMessage(EmbedMessageUtils.getLastMessageFromTextChannel(result)).queue(); event.getTextChannel().sendMessage(EmbedMessageUtils.getLastMessageFromTextChannel(result)).queue();
} }
private void SendBack(MessageReceivedEvent event) { private void SendBack(MessageReceivedEvent event){
HashMap<String, String> result = new HashMap<>(); HashMap<String, String> result = new HashMap<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy").withLocale(Locale.ENGLISH); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy").withLocale(Locale.ENGLISH);
int charCtl = 0; int charCtl = 0;

View File

@ -0,0 +1,105 @@
package net.Broken.Commands;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import net.Broken.Commande;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.SpringContext;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.PrivateMessage;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import java.awt.*;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
public class Code implements Commande {
private UserRepository userRepository;
private Logger logger = LogManager.getLogger();
public Code (){
ApplicationContext context = SpringContext.getAppContext();
userRepository = (UserRepository) context.getBean("userRepository");
}
@Override
public void action(String[] args, MessageReceivedEvent event) {
StringBuilder stringBuilder = new StringBuilder();
for(String arg : args){
stringBuilder.append(arg);
stringBuilder.append(" ");
}
Binding binding = new Binding();
binding.setVariable("event", event);
GroovyShell shell = new GroovyShell(binding);
EmbedBuilder builder;
try{
Object value = shell.evaluate(stringBuilder.toString());
StringBuilder stringResult = new StringBuilder();
if(value.getClass().isArray()){
Object[] array = (Object[]) value;
for(Object obj : array){
if(stringResult.length() < 1800){
stringResult.append(obj.toString()).append("\n\n");
}
else{
stringResult.append("\n...");
break;
}
}
}else{
stringResult.append(value.toString());
}
builder = new EmbedBuilder().setColor(Color.orange).setTitle(":hammer_pick: Compilation Successful :hammer_pick:").setDescription("```java\n" + stringResult.toString() + "```");
}catch (Exception ex){
builder = new EmbedBuilder().setColor(Color.red).setTitle(":x: Compilation Failed :x:").setDescription("```java\n" + ex.toString() + "```");
}
event.getChannel().sendMessage(builder.build()).queue();
}
@Override
public boolean isPrivateUsable() {
return true;
}
@Override
public boolean isAdminCmd() {
return true;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return true;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -10,12 +10,12 @@ import org.apache.logging.log4j.Logger;
/** /**
* Admin command to manually trigger daily action(s) * Admin command to manually trigger daily action(s)
*/ */
public class DayTrigger implements Commande { public class DayTrigger implements Commande{
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
if (!event.isFromType(ChannelType.PRIVATE)) if(!event.isFromType(ChannelType.PRIVATE))
event.getMessage().delete().queue(); event.getMessage().delete().queue();
DayListener.getInstance().trigger(); DayListener.getInstance().trigger();

View File

@ -0,0 +1,76 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.entities.MessageHistory;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List;
/**
* Command to flush X last message on channel.
*/
public class Flush implements Commande{
Logger logger = LogManager.getLogger();
@Override
public void action(String[] args, MessageReceivedEvent event) {
if(args.length<1){
event.getTextChannel().sendMessage(EmbedMessageUtils.getFlushError("Missing argument!")).queue();
}
else
{
if(event.getMember().hasPermission(Permission.ADMINISTRATOR)){
try {
int limit = Integer.parseInt(args[0]) + 1;
MessageChannel chanel = event.getChannel();
chanel.getIterableHistory().takeAsync(limit).thenAccept(chanel::purgeMessages);
}catch (NumberFormatException e){
event.getTextChannel().sendMessage(EmbedMessageUtils.getFlushError("Argument unknown!")).queue();
}
}
else
{
event.getTextChannel().sendMessage(EmbedMessageUtils.getFlushError("You are not a supreme being, you cannot do that !")).queue();
}
}
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -0,0 +1,195 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.PrivateMessage;
import net.Broken.Tools.TableRenderer;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.*;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Help Command.
*/
public class Help implements Commande {
Logger logger = LogManager.getLogger();
private int cellLenght = 25;
@Override
public void action(String[] args, MessageReceivedEvent event) {
if(args.length>=1)
{
String argsString = args[0];
//System.out.println(argsString);
if (MainBot.commandes.containsKey(argsString))
{
Commande cmdObj = MainBot.commandes.get(argsString);
if(!cmdObj.isAdminCmd() || isAdmin(event))
{
logger.debug("Help for "+argsString+" by "+event.getAuthor().getName());
MessageEmbed messageEmbed;
try {
messageEmbed = EmbedMessageUtils.getHelp(argsString);
} catch (FileNotFoundException e) {
try {
messageEmbed = EmbedMessageUtils.getHelp("Default");
} catch (FileNotFoundException e1) {
messageEmbed = EmbedMessageUtils.getInternalError();
logger.catching(e1);
}
}
if(!event.isFromType(ChannelType.PRIVATE)) {
event.getTextChannel().sendMessage(messageEmbed).queue();
} else{
PrivateMessage.send(event.getAuthor(), messageEmbed,logger);
}
}
else
{
logger.info("Help wanted for admin command, Denied!");
if(!event.isFromType(ChannelType.PRIVATE)) {
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getUnautorized()).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
} else{
PrivateMessage.send(event.getAuthor(), EmbedMessageUtils.getUnautorized(), logger);
}
}
}
else
{
if(!event.isFromType(ChannelType.PRIVATE)) {
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getUnknowCommand()).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
} else{
PrivateMessage.send(event.getAuthor(),EmbedMessageUtils.getUnknowCommand(),logger);
}
logger.debug("Unknown command!");
}
}
else
{
TableRenderer table = new TableRenderer();
table.setHeader("Command","PU");
TableRenderer nsfwTable = new TableRenderer();
nsfwTable.setHeader("NSFW Only\u00A0", "PU");
List<String> noPu = new ArrayList<>();
for (Map.Entry<String, Commande> e : MainBot.commandes.entrySet()) {
if(!e.getValue().isAdminCmd() || isAdmin(event)){
if(e.getValue().isPrivateUsable())
table.addRow(e.getKey(), "XX");
else if(e.getValue().isNSFW())
nsfwTable.addRow(e.getKey(),"");
else
noPu.add(e.getKey());
}
}
for(String key : noPu)
table.addRow(key, "");
String txt = table.build();
txt += "\n\n";
txt += nsfwTable.build();
if(!event.isFromType(ChannelType.PRIVATE)){
Message rest = event.getTextChannel().sendMessage(new EmbedBuilder().setTitle("Commands sent by private message").setColor(Color.green).build()).complete();
new MessageTimeOut(MainBot.messageTimeOut, rest, event.getMessage()).start();
}
String role;
if(isAdmin(event))
role = "Admin";
else
role = "No Admin";
try {
PrivateMessage.send(event.getAuthor(), EmbedMessageUtils.getHelpList(role, txt),logger);
} catch (FileNotFoundException e) {
logger.catching(e);
PrivateMessage.send(event.getAuthor(), EmbedMessageUtils.getInternalError(), logger);
}
}
}
@Override
public boolean isPrivateUsable() {
return true;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
public boolean isAdmin(MessageReceivedEvent event){
if(event.isFromType(ChannelType.PRIVATE)){
List<Guild> guilds = event.getAuthor().getMutualGuilds();
for(Guild iterator : guilds){
if(iterator.getMember(event.getAuthor()).hasPermission(Permission.ADMINISTRATOR)){
return true;
}
}
}
else
return event.getMember().hasPermission(Permission.ADMINISTRATOR);
return false;
}
}

View File

@ -0,0 +1,43 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.Tools.PrivateMessage;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
public class Invite implements Commande{
@Override
public void action(String[] args, MessageReceivedEvent event) {
if(event.getChannelType().isGuild()){
event.getTextChannel().sendMessage("You can invite me whit this link:\nhttps://discordapp.com/oauth2/authorize?client_id=" + event.getJDA().getSelfUser().getId() + "&scope=bot&permissions=8").complete();
}
else {
PrivateMessage.send(event.getAuthor(),"You can invite me whit this link:\nhttps://discordapp.com/oauth2/authorize?client_id=" + event.getJDA().getSelfUser().getId() + "&scope=bot&permissions=8",LogManager.getLogger());
}
}
@Override
public boolean isPrivateUsable() {
return true;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -0,0 +1,48 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import java.awt.*;
import java.util.List;
public class ListRoles implements Commande {
@Override
public void action(String[] args, MessageReceivedEvent event) {
List<Role> roles = event.getGuild().getRoles();
EmbedBuilder messageB = new EmbedBuilder();
for (Role role : roles){
messageB.addField(role.getName(),"```id: " + role.getId() + "```",false);
}
messageB.setColor(Color.green);
event.getTextChannel().sendMessage(messageB.build()).complete();
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return true;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -0,0 +1,203 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.HierarchyException;
import net.dv8tion.jda.api.managers.GuildManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* Move Command
*/
public class Move implements Commande {
Logger logger = LogManager.getLogger();
private String HELP="`//move <@user> <@Role>`\n:arrow_right:\t*Move a user to a specified role.*";
public List<Role> saveRoleUser;
public Member user;
public Guild serveur;
public GuildManager serveurManager;
/** Perform a move (Reset is role and add target(s) role(s)
*
* @param user User to move
* @param cible Complete list of new role
* @param reset
* @param serveur Guild
* @param serveurManager GuildManager
* @return success
*/
public boolean exc(Member user, List<Role> cible , boolean reset, Guild serveur, GuildManager serveurManager) throws HierarchyException
{
MainBot.roleFlag = true;
boolean erreur = false;
List<Role> allRoll = serveur.getRoles();
//On recupere les roles de l'utilisateur
List<Role> roleUserList = user.getRoles();
logger.info("Roles of " + user.getEffectiveName() + ":");
//On les save
saveRoleUser = roleUserList;
//Ajout du role cible
//On transforme la le role a ajouter en une liste pour pouvoir l'utiliser dans modifyMemberRoles
//on fait ensuite les modif
serveur.modifyMemberRoles(user,cible).complete();
logger.info("Give " + cible + " role to " + user.getEffectiveName());
this.user=user;
this.serveur=serveur;
this.serveurManager=serveurManager;
return erreur;
}
/** Command handler
*
* @param args
* @param event
*/
public void action(String[] args, MessageReceivedEvent event)
{
if(!event.isFromType(ChannelType.PRIVATE))
{
if(args.length>=2)
{
serveur=event.getGuild();
List<User> userL = event.getMessage().getMentionedUsers();
List<Role> roleL = event.getMessage().getMentionedRoles();
if(userL.size()<1 ||roleL.size()<1)
{
logger.warn("Wrong mention.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveError("Error, please check if the user and/or the role are existing.")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
else
{
user = serveur.getMember(userL.get(0));
serveur=event.getGuild();
logger.info("Attempting role assignement for "+user.getEffectiveName()+" to "+roleL+" by "+event.getAuthor().getName());
logger.info("Permission granted, role assignement authorized");
logger.debug("User found");
try {
boolean erreur=this.exc(user,roleL,true,serveur,serveur.getManager());
if(erreur)
{
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveError("Check the targeted role. ")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
else
{
StringBuilder roleStr = new StringBuilder("");
boolean first = true;
for( Role role : roleL)
{
if (!first) {
roleStr.append(", ");
}
else
first = false;
roleStr.append("__");
roleStr.append(role.getName());
roleStr.append("__");
}
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveOk("User "+user.getEffectiveName()+" as been successfully moved to "+roleStr.toString())).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
}catch (HierarchyException e){
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveError("You cannot move "+user.getRoles().get(0).getAsMention())).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
logger.error("Hierarchy error, please move bot's role on top!");
}
}
}
else
{
logger.warn("Missing argument.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveError("Missing argument.")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
}
else
event.getPrivateChannel().sendMessage(EmbedMessageUtils.getNoPrivate());
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return true;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -1,14 +1,18 @@
package net.Broken.Commands; package net.Broken.Commands;
import net.Broken.Commande; import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.MessageTimeOut;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
public class Ordre66 implements Commande { public class Ordre66 implements Commande {
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
Message rest = event.getTextChannel().sendMessage("Très bien maître " + event.getAuthor().getAsMention() + ". J'arrive ! ").complete(); Message rest = event.getTextChannel().sendMessage("Très bien maître " + event.getAuthor().getAsMention()+". J'arrive ! ").complete();
Message reste = event.getTextChannel().sendMessage("https://media2.giphy.com/media/UfzTayIyH7g5hk2BA2/giphy.gif\n").complete(); Message reste = event.getTextChannel().sendMessage("https://media2.giphy.com/media/UfzTayIyH7g5hk2BA2/giphy.gif\n").complete();
} }

View File

@ -9,10 +9,10 @@ import org.apache.logging.log4j.LogManager;
*/ */
@NoDev() @NoDev()
public class Ass extends NumberedCommande { public class Ass extends NumberedCommande {
public Ass() { public Ass() {
super(LogManager.getLogger(), "http://les400culs.com/", "-2/", "featured-img", "img"); super(LogManager.getLogger(), "http://les400culs.com/","-2/","featured-img","img");
} }
@Override @Override

View File

@ -11,9 +11,8 @@ import org.apache.logging.log4j.LogManager;
public class Boobs extends NumberedCommande { public class Boobs extends NumberedCommande {
public Boobs() { public Boobs() {
super(LogManager.getLogger(), "http://lesaintdesseins.fr/", "-2/", "featured-img", "img"); super(LogManager.getLogger(), "http://lesaintdesseins.fr/","-2/","featured-img","img");
} }
@Override @Override
public String toString() { public String toString() {
return "Boobs"; return "Boobs";

View File

@ -15,9 +15,9 @@ import java.io.IOException;
*/ */
@NoDev @NoDev
public class Madame extends NumberedCommande { public class Madame extends NumberedCommande {
public String HELP = "Yo really? Just type Madame to see some :cat:";
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
MessageReceivedEvent event; MessageReceivedEvent event;
public String HELP = "Yo really? Just type Madame to see some :cat:";
public Madame() { public Madame() {
super(LogManager.getLogger(), "https://www.bonjourmadame.fr/page/", "/"); super(LogManager.getLogger(), "https://www.bonjourmadame.fr/page/", "/");
@ -73,10 +73,10 @@ public class Madame extends NumberedCommande {
return false; return false;
} }
private String removeParams(String url) { private String removeParams(String url){
int par = url.indexOf('?'); int par = url.indexOf('?');
if (par != -1) { if(par != -1){
url = url.substring(0, par); url = url.substring(0,par);
} }
return url; return url;
} }
@ -86,7 +86,7 @@ public class Madame extends NumberedCommande {
public String poll() throws IOException { public String poll() throws IOException {
boolean success = false; boolean success = false;
String imgUrl = null; String imgUrl = null;
while (!success) { while (!success ) {
checkRandom(); checkRandom();
int randomResult = randomQueue.poll(); int randomResult = randomQueue.poll();

View File

@ -0,0 +1,57 @@
package net.Broken.Commands.Over18;
import net.Broken.Commande;
import net.Broken.Tools.FindContentOnWebPage;
import net.Broken.Tools.Redirection;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
/**
* TODO Remove this
*/
public class SM implements Commande {
Logger logger = LogManager.getLogger();
@Override
public void action(String[] args, MessageReceivedEvent event) {
Redirection redirect= new Redirection();
try {
String redirectUrl = redirect.get("https://bonjourfetish.tumblr.com/random");
logger.debug(redirectUrl);
String img = FindContentOnWebPage.doYourJob(redirectUrl, "article-picture center", "img");
event.getTextChannel().sendMessage(img).queue();
} catch (IOException e) {
logger.warn("Redirection fail.");
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:warning: **__Redirection fail (5 attempt), Try again__**:warning: ").queue();
}
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return true;
}
}

View File

@ -0,0 +1,86 @@
package net.Broken.Commands.Over18;
import net.Broken.Commande;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.FindContentOnWebPage;
import net.Broken.Tools.Redirection;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
public class Suicide implements Commande{
private Logger logger = LogManager.getLogger();
@Override
public void action(String[] args, MessageReceivedEvent event) {
Redirection redirection = new Redirection();
String base = "http://suicidegirls.tumblr.com";
String redirectUrl = null;
try {
Boolean success = false;
int tryCount = 0;
while(!success && tryCount < 10 ){
redirectUrl = redirection.get(base + "/random");
String img;
try{
img = FindContentOnWebPage.doYourJob(redirectUrl, "post photo_nav_caption", "img");
event.getTextChannel().sendMessage(img).queue();
success = true;
}catch (StringIndexOutOfBoundsException | IOException e){
logger.debug("Photo_nav not found try photoset");
try {
String mid = FindContentOnWebPage.doYourJob(redirectUrl, "html_photoset", "iframe");
img = FindContentOnWebPage.doYourJob(base + mid, "photoset_row", "img");
event.getTextChannel().sendMessage(img).queue();
success = true;
} catch (StringIndexOutOfBoundsException | IOException e1) {
logger.debug("Nothing found, assume it's a comment.");
}
}
tryCount ++;
}
} catch (IOException e) {
logger.catching(e);
}
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return true;
}
}

View File

@ -0,0 +1,54 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.MessageTimeOut;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
/**
* Command that return the Bot's ping
*/
public class Ping implements Commande {
@Override
public void action(String[] args, MessageReceivedEvent event) {
long ping = event.getJDA().getGatewayPing();
// long receivedTime = Timestamp.valueOf(LocalDateTime.ofInstant(event.getMessage().getCreationTime().toInstant(), ZoneId.systemDefault())).getTime();
if(event.isFromType(ChannelType.PRIVATE))
event.getPrivateChannel().sendMessage(":arrow_right: Pong! `" + ping+ "ms`").queue();
else {
Message rest = event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n:arrow_right: Pong! `" + ping + "ms`").complete();
new MessageTimeOut(MainBot.messageTimeOut, event.getMessage(), rest).start();
}
LogManager.getLogger().debug("pong");
}
@Override
public boolean isPrivateUsable() {
return true;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -3,8 +3,10 @@ package net.Broken.Commands;
import net.Broken.Commande; import net.Broken.Commande;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.MessageAction;
public class ReportUsers implements Commande { public class ReportUsers implements Commande {
@ -26,7 +28,7 @@ public class ReportUsers implements Commande {
} }
} }
} }
if (restAction != null) if(restAction!=null)
restAction.queue(); restAction.queue();
} else if (args.length == 0) { } else if (args.length == 0) {

View File

@ -1,17 +1,27 @@
package net.Broken.Commands; package net.Broken.Commands;
import net.Broken.Commande; import net.Broken.Commande;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository; import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.SpringContext; import net.Broken.SpringContext;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.SettingsUtils;
import net.Broken.audio.AudioM;
import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.awt.*; import java.awt.*;
import java.io.IOException;
import java.util.List;
public class Settings implements Commande { public class Settings implements Commande {
@ -30,7 +40,7 @@ public class Settings implements Commande {
EmbedBuilder builder = new EmbedBuilder() EmbedBuilder builder = new EmbedBuilder()
.setTitle("Settings") .setTitle("Settings")
.setDescription("You can do all the configuration on the web page in the \"Bot Settings\" menu.\nhttps://" + MainBot.url).setColor(Color.green); .setDescription("You can do all the configuration on the web page in the \"Bot Settings\" menu.\nhttps://"+MainBot.url).setColor(Color.green);
event.getTextChannel().sendMessage(EmbedMessageUtils.buildStandar(builder)).queue(); event.getTextChannel().sendMessage(EmbedMessageUtils.buildStandar(builder)).queue();

View File

@ -0,0 +1,351 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.AntiSpam;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.UserSpamUtils;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.RateLimitedException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Spam admin command
*/
// TODO Rebuild this ...
public class Spam implements Commande {
private Logger logger = LogManager.getLogger();
@Override
public void action(String[] args, MessageReceivedEvent event)
{
/****************************
* Verif argument *
****************************/
if(args.length>=1)
{
String commande = args[0];
/****************************
* on traite la commande *
****************************/
switch (commande) {
case "pardon":
this.pardon(event,args);
break;
case "extermine":
try {
this.extermine(event,args);
} catch (RateLimitedException e) {
e.printStackTrace();
}
break;
case "reset":
try {
this.reset(event,args);
} catch (RateLimitedException e) {
e.printStackTrace();
}
break;
}
}
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return true;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
public void pardon(MessageReceivedEvent event, String[] args){
Guild serveur = event.getGuild();
/****************************
* verif argument *
****************************/
if (args.length >= 1)
{
/****************************
* On recupere l'utilisateur et le role cible
****************************/
List<Member> userL = event.getMessage().getMentionedMembers();
/****************************
* verif utilisteur trouver *
****************************/
if(userL.size()<1)
{
logger.error("User unknown.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError(":arrow_right: User not found. ","pardon")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
else {
Member user = userL.get(0);
logger.info("Attempt to forgive " + user.getEffectiveName() + " by " + event.getMember().getEffectiveName());
/****************************
* virif si en spammer *
****************************/
if (MainBot.spamUtils.containsKey(user)) {
if (MainBot.spamUtils.get(user).isOnSpam()) {
MainBot.spamUtils.get(user).setOnSpam(false);
} else {
logger.warn("User is not in spam.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError(":arrow_right: This user is not in spam.","pardon")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
} else {
logger.warn("User is not in spam.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError(":arrow_right: This user is not in spam.","pardon")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
}
}
else
{
logger.warn("Missing argument.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError("Missing argument!","pardon")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
}
public void extermine(MessageReceivedEvent event, String[] args) throws RateLimitedException {
/****************************
* verif argument *
****************************/
if (args.length >= 3)
{
/****************************
* On recupere l'utilisateur et le role cible
****************************/
List<User> userL = event.getMessage().getMentionedUsers();
/****************************
* verif utilisteur trouver *
****************************/
if(userL.size()<1)
{
logger.warn("Wrong mention (Spam).");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError("Wrong mention. ","extermine")).complete();
}
else{
Guild serveur = event.getGuild();
Member user = serveur.getMember(userL.get(0));
logger.info("Starting protocol 66 on "+user.getEffectiveName()+" by the command of "+event.getAuthor().getName());
String multiStr =args[2];
/****************************
* virif pas deja en spammer *
****************************/
if(MainBot.spamUtils.containsKey(user))
{
if(!MainBot.spamUtils.get(user).isOnSpam())
{
this.goSpam(user,multiStr,serveur,event);
}
else
{
logger.warn("User already in spam.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError("User already in spam.","extermine")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
}
else
{
this.goSpam(user,multiStr,serveur,event);
}
}
}
else
{
logger.warn("Missing argument.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError("Missing argument!","extermine")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
}
public void reset(MessageReceivedEvent event, String[] args) throws RateLimitedException {
if(event!=null)
{
if(args.length>=2)
{
Guild serveur = event.getGuild();
/****************************
* On recupere l'utilisateur et le role cible
****************************/
List<Member> userL = event.getMessage().getMentionedMembers();
/****************************
* verif utilisteur trouver *
****************************/
if(userL.size()<1)
{
logger.warn("User not found.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError("User not found.","reset")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
else {
Member user = userL.get(0);
logger.info("Attempt spam reset of " + user.getEffectiveName() + " by " + event.getMember().getEffectiveName());
/****************************
* verif utilisteur trouver *
****************************/
if (MainBot.spamUtils.containsKey(user)) {
logger.info("Multiplictor reset for " + user.getEffectiveName() + " done.");
Message rest = event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n *The spam multiplicator of " + user.getEffectiveName() + " is now down to zero.*").complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
MainBot.spamUtils.remove(user);
}
}
}
else
{
logger.warn("Missing argument.");
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamError("Missing argument!","reset")).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
}
}
else
{
if (args[0].equals("all"))
{
logger.info("Multiplicator reseted automaticly.");
for (Member unUser: MainBot.spamUtils.keySet())
{
MainBot.message_compteur.remove(unUser); //TODO resolve garbage collector error ????
}
}
}
}
public void goSpam(Member user, String multiStr, Guild serveur, MessageReceivedEvent event)
{
if(Objects.equals(multiStr, "/"))
{
new AntiSpam().extermine(user,serveur,serveur.getManager(),true,event);
}
else
{
int multi = Integer.parseInt(multiStr);
if(MainBot.spamUtils.containsKey(user))
{
MainBot.spamUtils.get(user).setMultip(multi);
}
else
{
MainBot.spamUtils.put(user,new UserSpamUtils(user,new ArrayList<>()));
MainBot.spamUtils.get(user).setMultip(multi);
}
new AntiSpam().extermine(user,serveur,serveur.getManager(),false,event);
}
}
}

View File

@ -0,0 +1,200 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.PrivateMessage;
import net.Broken.Tools.UserSpamUtils;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Spam Info Command
*/
public class SpamInfo implements Commande{
private HashMap<Member,MessageUpdater> threadHashMap = new HashMap<>();
Logger logger = LogManager.getLogger();
@Override
public void action(String[] args, MessageReceivedEvent event) {
Member user;
if(event.getMessage().getMentionedUsers().size() == 0){
user = event.getMember();
}
else {
user = event.getMessage().getMentionedMembers().get(0);
}
Message message = null;
if(!MainBot.spamUtils.containsKey(user)){
if(!event.isFromType(ChannelType.PRIVATE))
message = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamInfo(user.getEffectiveName() + ":\n\t- Multiplicator: `1`\n\t- In spam: `No`")).complete();
else
PrivateMessage.send(event.getAuthor(),EmbedMessageUtils.getSpamInfo(user.getEffectiveName()+":\n\t- Multiplicator: `1`\n\t- In spam: `No`"),logger);
}
else{
UserSpamUtils util = MainBot.spamUtils.get(user);
if(!util.isOnSpam()){
if(!event.isFromType(ChannelType.PRIVATE))
message = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamInfo(user.getEffectiveName()+"\n\t- Multiplicator: `"+util.getMultip()+"`\n\t- In spam: `No`")).complete();
else
PrivateMessage.send(event.getAuthor(),EmbedMessageUtils.getSpamInfo(user.getEffectiveName()+":\n\t- Multiplicator: `"+util.getMultip()+"`\n\t- In spam: `No`"),logger);
}
else{
if(!event.isFromType(ChannelType.PRIVATE))
message = event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamInfo(user.getEffectiveName()+":\n\t- Multiplicator: `"+util.getMultip()+"`\n\t- In spam: `Yes`\n\t- Time remaining: `"+formatSecond(util.getTimeLeft())+"`")).complete();
else
message = PrivateMessage.send(event.getAuthor(),EmbedMessageUtils.getSpamInfo(user.getEffectiveName()+"\n\t- Multiplicator: `"+util.getMultip()+"`\n\t- In spam: `Yes`\n\t- Time remaining: `"+formatSecond(util.getTimeLeft())+"`"),logger);
}
}
if(message != null){
if(threadHashMap.containsKey(user)){
MessageUpdater startedThread = threadHashMap.get(user);
if(!message.getChannelType().equals(startedThread.message.getChannelType())){
MessageUpdater newThread = new MessageUpdater(message,event.getMessage(),MainBot.spamUtils.get(user),user);
threadHashMap.put(user,newThread);
newThread.start();
}
else
{
threadHashMap.get(user).stop = true;
MessageUpdater newThread = new MessageUpdater(message,event.getMessage(),MainBot.spamUtils.get(user),user);
threadHashMap.replace(user, newThread);
newThread.start();
}
}
else
{
MessageUpdater newThread = new MessageUpdater(message,event.getMessage(),MainBot.spamUtils.get(user),user);
threadHashMap.put(user, newThread);
newThread.start();
}
}
}
@Override
public boolean isPrivateUsable() {
return true;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
public String formatSecond(int second){
long days = TimeUnit.SECONDS.toDays(second);
second -= TimeUnit.DAYS.toSeconds(days);
long hours = TimeUnit.SECONDS.toHours(second);
second -= TimeUnit.HOURS.toSeconds(hours);
long minutes = TimeUnit.SECONDS.toMinutes(second);
second -= TimeUnit.MINUTES.toSeconds(minutes);
long seconds = TimeUnit.SECONDS.toSeconds(second);
logger.debug(""+days+":"+hours+":"+minutes+":"+seconds);
String finalText = "";
if(days!=0)
finalText += days+" day(s) ";
if(hours!=0)
finalText += hours+"h ";
if(minutes!=0)
finalText += minutes+"min ";
finalText += seconds+"s";
return finalText;
}
private class MessageUpdater extends Thread{
public Message message;
public Message command;
public UserSpamUtils util;
public boolean stop;
private int oldValue;
private Member user;
public MessageUpdater(Message message,Message command, UserSpamUtils util, Member user) {
this.message = message;
this.util = util;
this.user = user;
this.command = command;
}
@Override
public void run() {
logger.debug("Start "+user.getEffectiveName()+" theard!");
if(util != null){
oldValue = util.getTimeLeft();
while (util.getTimeLeft()!=0 && !stop && util.isOnSpam()){
try {
Thread.sleep(500);
if(util.getTimeLeft()%5 == 0 && oldValue - util.getTimeLeft() >= 5){
message.editMessage(EmbedMessageUtils.getSpamInfo(user.getEffectiveName()+":\n\t- Multiplicator: `"+util.getMultip()+"`\n\t- In spam: `Yes`\n\t- Time remaining: `"+formatSecond(util.getTimeLeft())+"`")).complete();
oldValue = util.getTimeLeft();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
logger.debug("Kill "+user.getEffectiveName()+" theard!");
if(stop)
message.editMessage(new EmbedBuilder().setColor(Color.RED).setTitle("Aborted").build()).complete();
else
message.editMessage(EmbedMessageUtils.getSpamInfo(user.getEffectiveName()+"\n\t- Multiplicator: `"+util.getMultip()+"`\n\t- In spam: `No`")).complete();
}
logger.debug("Timer for message deletion of "+user.getEffectiveName()+" stated...");
threadHashMap.remove(user);
List<Message> messages = new ArrayList<>();
messages.add(command);
messages.add(message);
new MessageTimeOut(messages,15).start();
}
}
}

View File

@ -0,0 +1,79 @@
package net.Broken.Commands;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.audio.Youtube.SearchResult;
import net.Broken.audio.Youtube.YoutubeSearchRework;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class YtSearch implements Commande {
private Logger logger = LogManager.getLogger();
@Override
public void action(String[] args, MessageReceivedEvent event) {
YoutubeSearchRework youtubeSearch = YoutubeSearchRework.getInstance();
if (args.length < 1) {
logger.info("YtSearch: Missing args, user: " + event.getAuthor().getName());
Message message = event.getChannel().sendMessage(EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("Missing search query!"))).complete();
new MessageTimeOut(MainBot.messageTimeOut, message, event.getMessage()).start();
} else {
try {
StringBuilder builder = new StringBuilder();
for (String arg : args) {
builder.append(arg);
}
List<SearchResult> result = youtubeSearch.searchVideo(builder.toString(), 5, false);
for (SearchResult item : result) {
event.getChannel().sendMessage(EmbedMessageUtils.searchResult(item)).queue();
}
} catch (IOException t) {
logger.catching(t);
event.getChannel().sendMessage(EmbedMessageUtils.getInternalError()).queue();
}
}
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -1,11 +1,11 @@
package net.Broken.DB.Entity; package net.Broken.DB.Entity;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.VoiceChannel;
import javax.persistence.Entity; import javax.persistence.*;
import javax.persistence.GeneratedValue; import java.util.ArrayList;
import javax.persistence.GenerationType; import java.util.List;
import javax.persistence.Id;
@Entity @Entity
public class GuildPreferenceEntity { public class GuildPreferenceEntity {

View File

@ -8,7 +8,7 @@ import java.util.Date;
@Entity @Entity
public class PendingPwdResetEntity { public class PendingPwdResetEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy= GenerationType.AUTO)
private Integer id; private Integer id;
@OneToOne @OneToOne
@ -17,7 +17,7 @@ public class PendingPwdResetEntity {
private Date expirationDate; private Date expirationDate;
public PendingPwdResetEntity(UserEntity userEntity, String token) { public PendingPwdResetEntity(UserEntity userEntity,String token) {
this.userEntity = userEntity; this.userEntity = userEntity;
this.securityToken = token; this.securityToken = token;
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
@ -27,8 +27,7 @@ public class PendingPwdResetEntity {
} }
public PendingPwdResetEntity() { public PendingPwdResetEntity() {}
}
public UserEntity getUserEntity() { public UserEntity getUserEntity() {

View File

@ -12,7 +12,7 @@ import javax.persistence.Id;
@Entity @Entity
public class PendingUserEntity { public class PendingUserEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy= GenerationType.AUTO)
private Integer id; private Integer id;
private String name; private String name;
@ -34,6 +34,7 @@ public class PendingUserEntity {
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }

View File

@ -3,7 +3,10 @@ package net.Broken.DB.Entity;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.annotation.Nullable;
import javax.persistence.*; import javax.persistence.*;
import javax.sound.midi.Track;
import java.lang.reflect.Array;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -12,14 +15,14 @@ import java.util.List;
public class PlaylistEntity { public class PlaylistEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy= GenerationType.AUTO)
private Integer id; private Integer id;
private String name; private String name;
@JsonIgnore @JsonIgnore
@ManyToOne @ManyToOne
@JoinColumn(name = "userEntity_id", nullable = false) @JoinColumn(name="userEntity_id", nullable=false)
private UserEntity user; private UserEntity user;
@ -68,8 +71,9 @@ public class PlaylistEntity {
this.tracks = tracks; this.tracks = tracks;
} }
public void addTracks(TrackEntity... tracks) { public void addTracks(TrackEntity... tracks )
if (this.tracks == null) {
if(this.tracks == null)
this.tracks = new ArrayList<>(); this.tracks = new ArrayList<>();
this.tracks.addAll(Arrays.asList(tracks)); this.tracks.addAll(Arrays.asList(tracks));

View File

@ -9,7 +9,7 @@ import javax.persistence.*;
public class TrackEntity { public class TrackEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy= GenerationType.AUTO)
private Integer id; private Integer id;
private String title; private String title;
@ -22,7 +22,7 @@ public class TrackEntity {
@JsonIgnore @JsonIgnore
@ManyToOne @ManyToOne
@JoinColumn(name = "playlistEntity_id", nullable = false) @JoinColumn(name="playlistEntity_id", nullable=false)
private PlaylistEntity playlist; private PlaylistEntity playlist;
public TrackEntity() { public TrackEntity() {
@ -36,9 +36,9 @@ public class TrackEntity {
this.pos = pos; this.pos = pos;
} }
public TrackEntity(TrackEntity trackEntity) { public TrackEntity(TrackEntity trackEntity){
this.title = trackEntity.title; this.title = trackEntity.title;
this.url = trackEntity.url; this.url = trackEntity.url;
this.identifier = trackEntity.identifier; this.identifier = trackEntity.identifier;
this.pos = trackEntity.pos; this.pos = trackEntity.pos;
this.playlist = trackEntity.playlist; this.playlist = trackEntity.playlist;

View File

@ -16,7 +16,7 @@ import java.util.List;
@Entity @Entity
public class UserEntity { public class UserEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy= GenerationType.AUTO)
private Integer id; private Integer id;
private String name; private String name;
@ -49,14 +49,14 @@ public class UserEntity {
this.apiToken = apiToken; this.apiToken = apiToken;
} }
public UserEntity(User user, PasswordEncoder passwordEncoder) { public UserEntity(User user, PasswordEncoder passwordEncoder){
this.name = user.getName(); this.name = user.getName();
this.jdaId = user.getId(); this.jdaId = user.getId();
this.apiToken = UserUtils.getInstance().generateApiToken(); this.apiToken = UserUtils.getInstance().generateApiToken();
this.password = passwordEncoder.encode(UserUtils.getInstance().generateCheckToken()); this.password = passwordEncoder.encode(UserUtils.getInstance().generateCheckToken());
} }
public UserEntity(String name, String id, PasswordEncoder passwordEncoder) { public UserEntity(String name, String id, PasswordEncoder passwordEncoder){
this.name = name; this.name = name;
this.jdaId = id; this.jdaId = id;
this.apiToken = UserUtils.getInstance().generateApiToken(); this.apiToken = UserUtils.getInstance().generateApiToken();
@ -112,8 +112,8 @@ public class UserEntity {
this.playlists = playlists; this.playlists = playlists;
} }
public void addPlaylist(PlaylistEntity... playlists) { public void addPlaylist(PlaylistEntity... playlists){
if (this.playlists == null) if(this.playlists == null)
this.playlists = new ArrayList<>(); this.playlists = new ArrayList<>();
this.playlists.addAll(Arrays.asList(playlists)); this.playlists.addAll(Arrays.asList(playlists));

View File

@ -8,14 +8,14 @@ import javax.persistence.*;
public class UserStats { public class UserStats {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy= GenerationType.AUTO)
private Long id; private Long id;
private String guildId; private String guildId;
@ManyToOne @ManyToOne
@JoinColumn(name = "userEntity_id", nullable = false) @JoinColumn(name="userEntity_id", nullable=false)
private UserEntity user; private UserEntity user;
@ColumnDefault("0") @ColumnDefault("0")
@ -27,10 +27,9 @@ public class UserStats {
@ColumnDefault("0") @ColumnDefault("0")
private Long apiCommandCount = 0L; private Long apiCommandCount = 0L;
public UserStats() { public UserStats(){}
}
public UserStats(String guildId, UserEntity user) { public UserStats(String guildId, UserEntity user){
this.guildId = guildId; this.guildId = guildId;
this.user = user; this.user = user;
} }

View File

@ -6,6 +6,6 @@ import org.springframework.data.repository.CrudRepository;
import java.util.List; import java.util.List;
public interface PendingPwdResetRepository extends CrudRepository<PendingPwdResetEntity, Integer> { public interface PendingPwdResetRepository extends CrudRepository<PendingPwdResetEntity,Integer>{
List<PendingPwdResetEntity> findByUserEntity(UserEntity userEntity); List<PendingPwdResetEntity> findByUserEntity(UserEntity userEntity);
} }

View File

@ -9,10 +9,8 @@ import java.util.List;
* Repository for UserEntity * Repository for UserEntity
*/ */
public interface UserRepository extends CrudRepository<UserEntity, Integer> { public interface UserRepository extends CrudRepository<UserEntity, Integer>{
List<UserEntity> findByName(String name); List<UserEntity> findByName(String name);
List<UserEntity> findByJdaId(String jdaId); List<UserEntity> findByJdaId(String jdaId);
List<UserEntity> findByApiToken(String apiToken); List<UserEntity> findByApiToken(String apiToken);
} }

View File

@ -8,9 +8,7 @@ import java.util.List;
public interface UserStatsRepository extends CrudRepository<UserStats, Long> { public interface UserStatsRepository extends CrudRepository<UserStats, Long> {
List<UserStats> findByUser(UserEntity userEntity); List<UserStats> findByUser(UserEntity userEntity);
List<UserStats> findByGuildId(String guildId); List<UserStats> findByGuildId(String guildId);
List<UserStats> findByUserAndGuildId(UserEntity user, String guildId); List<UserStats> findByUserAndGuildId(UserEntity user, String guildId);
} }

View File

@ -7,7 +7,9 @@ import net.Broken.Tools.Command.CommandLoader;
import net.Broken.Tools.Command.SlashCommandLoader; import net.Broken.Tools.Command.SlashCommandLoader;
import net.Broken.Tools.DayListener.DayListener; import net.Broken.Tools.DayListener.DayListener;
import net.Broken.Tools.DayListener.Listeners.DailyMadame; import net.Broken.Tools.DayListener.Listeners.DailyMadame;
import net.Broken.Tools.DayListener.Listeners.ResetSpam;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils; import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.OnlineStatus;
@ -88,6 +90,7 @@ public class Init {
SlashCommandLoader.registerSlashCommands(jda.updateCommands()); SlashCommandLoader.registerSlashCommands(jda.updateCommands());
ApiCommandLoader.load(); ApiCommandLoader.load();
DayListener dayListener = DayListener.getInstance(); DayListener dayListener = DayListener.getInstance();
dayListener.addListener(new ResetSpam());
dayListener.addListener(new DailyMadame()); dayListener.addListener(new DailyMadame());
dayListener.start(); dayListener.start();
jda.addEventListener(new BotListener()); jda.addEventListener(new BotListener());

View File

@ -1,8 +1,16 @@
package net.Broken; package net.Broken;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.Tools.Command.CommandParser;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.PrivateMessage;
import net.Broken.Tools.UserSpamUtils;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.boot.ExitCodeGenerator; import org.springframework.boot.ExitCodeGenerator;
@ -23,13 +31,18 @@ public class MainBot {
public static HashMap<String, Commande> commandes = new HashMap<>(); public static HashMap<String, Commande> commandes = new HashMap<>();
public static HashMap<String, SlashCommand> slashCommands = new HashMap<>(); public static HashMap<String, SlashCommand> slashCommands = new HashMap<>();
public static HashMap<String, Integer> mutualGuildCount = new HashMap<>(); public static HashMap<Member, ArrayList<Message>> historique =new HashMap<>();
public static HashMap<Member, Integer> message_compteur =new HashMap<>();
public static HashMap<String, Integer> mutualGuildCount =new HashMap<>();
public static boolean roleFlag = false; public static boolean roleFlag = false;
public static HashMap<Member, UserSpamUtils> spamUtils = new HashMap<>();
public static JDA jda; public static JDA jda;
public static boolean ready = false; public static boolean ready = false;
public static boolean dev = false; public static boolean dev = false;
public static String url = "claptrapbot.com"; public static String url= "claptrapbot.com";
public static int messageTimeOut = 10; public static int messageTimeOut = 10;
@ -41,13 +54,13 @@ public class MainBot {
public static void main(String[] args) { public static void main(String[] args) {
if (!Init.checkEnv()) if(!Init.checkEnv())
System.exit(1); System.exit(1);
logger.info("======================================="); logger.info("=======================================");
logger.info("--------------Starting Bot-------------"); logger.info("--------------Starting Bot-------------");
logger.info("======================================="); logger.info("=======================================");
if (System.getenv("DEV") != null) { if(System.getenv("DEV")!= null){
dev = Boolean.parseBoolean(System.getenv("DEV")); dev = Boolean.parseBoolean(System.getenv("DEV"));
} }
@ -58,7 +71,7 @@ public class MainBot {
ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args); ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args);
if (jda == null) { if(jda == null) {
System.exit(SpringApplication.exit(ctx, (ExitCodeGenerator) () -> { System.exit(SpringApplication.exit(ctx, (ExitCodeGenerator) () -> {
logger.fatal("Init error! Close application!"); logger.fatal("Init error! Close application!");
return 1; return 1;
@ -69,4 +82,65 @@ public class MainBot {
ready = true; ready = true;
} }
/**
* Perform test (admin, NSFW and private usable or not) and execute command or not
* @param cmd Container whit all command info
*/
public static void handleCommand(CommandParser.CommandContainer cmd, UserEntity user)
{
if(!ready){
return;
}
if (commandes.containsKey(cmd.commande)){
Commande cmdObj = commandes.get(cmd.commande);
boolean isAdmin;
boolean isBotAdmin = user != null && user.isBotAdmin();
if(cmd.event.isFromType(ChannelType.PRIVATE)){
isAdmin = false;
}
else
isAdmin = cmd.event.getMember().hasPermission(Permission.ADMINISTRATOR);
if((!cmdObj.isAdminCmd() || isAdmin) && (!cmdObj.isBotAdminCmd() || isBotAdmin)){
if(cmd.event.isFromType(ChannelType.PRIVATE) && commandes.get(cmd.commande).isPrivateUsable())
{
commandes.get(cmd.commande).action(cmd.args, cmd.event);
}
else if (!cmd.event.isFromType(ChannelType.PRIVATE))
{
if(!cmdObj.isNSFW() || cmd.event.getTextChannel().isNSFW()){
commandes.get(cmd.commande).action(cmd.args, cmd.event);
}
else{
cmd.event.getMessage().delete().queue();
}
}
else
cmd.event.getPrivateChannel().sendMessage(EmbedMessageUtils.getNoPrivate()).queue();
}
else{
if(cmd.event.isFromType(ChannelType.PRIVATE)){
PrivateMessage.send(cmd.event.getAuthor(),EmbedMessageUtils.getUnautorized(), logger);
}
else{
cmd.event.getTextChannel().sendMessage(EmbedMessageUtils.getUnautorized()).complete();
}
}
}
else{
logger.debug("Unknown command : " + cmd.commande);
}
}
} }

View File

@ -12,8 +12,7 @@ import java.util.Set;
public class ApiCommandLoader { public class ApiCommandLoader {
public static HashMap<String, CommandInterface> apiCommands = new HashMap<>(); public static HashMap<String, CommandInterface> apiCommands = new HashMap<>();
private static Logger logger = LogManager.getLogger(); private static Logger logger = LogManager.getLogger();
public static void load(){
public static void load() {
logger.info("Loading Api Command..."); logger.info("Loading Api Command...");
// Reflections reflections = new Reflections("net.Broken.RestApi.Command"); // Reflections reflections = new Reflections("net.Broken.RestApi.Command");
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage( Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(
@ -28,7 +27,7 @@ public class ApiCommandLoader {
String reference = apiClass.getName(); String reference = apiClass.getName();
String[] splited = reference.split("\\."); String[] splited = reference.split("\\.");
String name = splited[splited.length - 1].toUpperCase(); String name = splited[splited.length-1].toUpperCase();
logger.info("..." + name); logger.info("..." + name);

View File

@ -13,10 +13,9 @@ import org.springframework.http.ResponseEntity;
public interface CommandInterface { public interface CommandInterface {
/** /**
* Main action * Main action
*
* @param musicCommande Current guild music command * @param musicCommande Current guild music command
* @param data Received data * @param data Received data
* @param user User who submit RestApi command * @param user User who submit RestApi command
* @param guild * @param guild
* @return HTTP Response * @return HTTP Response
*/ */

View File

@ -10,13 +10,13 @@ import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
public class AutoFlowOff implements CommandInterface { public class AutoFlowOff implements CommandInterface{
@Override @Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) { public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM audioM = AudioM.getInstance(guild); AudioM audioM = AudioM.getInstance(guild);
TrackScheduler scheduler = audioM.getGuildMusicManager().scheduler; TrackScheduler scheduler = audioM.getGuildMusicManager().scheduler;
scheduler.setAutoFlow(false); scheduler.setAutoFlow(false);
return new ResponseEntity<>(new CommandResponseData(data.command, "ok"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command,"ok"), HttpStatus.OK);
} }
} }

View File

@ -10,14 +10,14 @@ import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
public class AutoFlowOn implements CommandInterface { public class AutoFlowOn implements CommandInterface{
@Override @Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) { public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM audioM = AudioM.getInstance(guild); AudioM audioM = AudioM.getInstance(guild);
TrackScheduler scheduler = audioM.getGuildMusicManager().scheduler; TrackScheduler scheduler = audioM.getGuildMusicManager().scheduler;
scheduler.setAutoFlow(true); scheduler.setAutoFlow(true);
return new ResponseEntity<>(new CommandResponseData(data.command, "ok"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command,"ok"), HttpStatus.OK);
} }
} }

View File

@ -13,25 +13,24 @@ import org.springframework.http.ResponseEntity;
/** /**
* Connect to vocal channel RestApi command * Connect to vocal channel RestApi command
*/ */
public class Connect implements CommandInterface { public class Connect implements CommandInterface{
@Override @Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) { public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM audioM = AudioM.getInstance(guild); AudioM audioM = AudioM.getInstance(guild);
if (data.chanelId == null) if(data.chanelId == null)
return new ResponseEntity<>(new CommandResponseData(data.command, "Missing chanelId"), HttpStatus.BAD_REQUEST); return new ResponseEntity<>(new CommandResponseData(data.command,"Missing chanelId"),HttpStatus.BAD_REQUEST);
VoiceChannel voiceChannel = null; VoiceChannel voiceChannel = null;
try { try{
voiceChannel = guild.getVoiceChannelById(data.chanelId); voiceChannel = guild.getVoiceChannelById(data.chanelId);
} catch (NumberFormatException ignored) { }catch (NumberFormatException ignored){}
}
if (voiceChannel == null) { if(voiceChannel == null){
return new ResponseEntity<>(new CommandResponseData(data.command, "Channel Not found"), HttpStatus.BAD_REQUEST); return new ResponseEntity<>(new CommandResponseData(data.command,"Channel Not found"), HttpStatus.BAD_REQUEST);
} }
audioM.getGuildAudioPlayer(); audioM.getGuildAudioPlayer();
guild.getAudioManager().openAudioConnection(guild.getVoiceChannelById(data.chanelId)); guild.getAudioManager().openAudioConnection(guild.getVoiceChannelById(data.chanelId));
audioM.setPlayedChanel(voiceChannel); audioM.setPlayedChanel(voiceChannel);
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command,"Accepted"),HttpStatus.OK);
} }
} }

View File

@ -15,11 +15,12 @@ import org.springframework.http.ResponseEntity;
public class Dell implements CommandInterface { public class Dell implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) { public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
if (data.url != null) { if(data.url != null) {
if (AudioM.getInstance(guild).getGuildMusicManager().scheduler.remove(data.url)) { if(AudioM.getInstance(guild).getGuildMusicManager().scheduler.remove(data.url)){
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} else }
return new ResponseEntity<>(new CommandResponseData(data.command, "URL not found"), HttpStatus.NOT_FOUND); else
return new ResponseEntity<>(new CommandResponseData(data.command,"URL not found"), HttpStatus.NOT_FOUND);
} }
return new ResponseEntity<>(new CommandResponseData(data.command, "Missing URL"), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new CommandResponseData(data.command, "Missing URL"), HttpStatus.NOT_ACCEPTABLE);

View File

@ -12,11 +12,11 @@ import org.springframework.http.ResponseEntity;
/** /**
* Disconnect from vocal chanel RestApi Command * Disconnect from vocal chanel RestApi Command
*/ */
public class Disconnect implements CommandInterface { public class Disconnect implements CommandInterface{
@Override @Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) { public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM.getInstance(guild).stop(); AudioM.getInstance(guild).stop();
return new ResponseEntity<>(new CommandResponseData(data.command, "Ok"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command,"Ok"), HttpStatus.OK);
} }
} }

View File

@ -15,7 +15,7 @@ import org.springframework.http.ResponseEntity;
public class Pause implements CommandInterface { public class Pause implements CommandInterface {
@Override @Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) { public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM.getInstance(guild).getGuildMusicManager().scheduler.pause(); AudioM.getInstance(guild).getGuildMusicManager().scheduler.pause();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK); return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} }
} }

View File

@ -1,7 +1,6 @@
package net.Broken.RestApi.Data; package net.Broken.RestApi.Data;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
/** /**
* Data for JSON Parsing * Data for JSON Parsing
*/ */

View File

@ -1,7 +1,10 @@
package net.Broken.RestApi.Data; package net.Broken.RestApi.Data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackState;
/** /**
* Data for JSON Parsing * Data for JSON Parsing
*/ */
@ -31,7 +34,7 @@ public class CurrentMusicData {
} }
public String getState() { public String getState() {
if (pause) if(pause)
return "PAUSE"; return "PAUSE";
else else
return state; return state;

View File

@ -2,7 +2,7 @@ package net.Broken.RestApi.Data.Playlist;
import net.Broken.RestApi.Data.CommandPostData; import net.Broken.RestApi.Data.CommandPostData;
public class AddToPlaylistData extends CommandPostData { public class AddToPlaylistData extends CommandPostData{
public int playlistId; public int playlistId;

View File

@ -13,7 +13,6 @@ public class PlaylistResponseData {
this.message = message; this.message = message;
this.playlist = playlist; this.playlist = playlist;
} }
public PlaylistResponseData(String message, String error) { public PlaylistResponseData(String message, String error) {
this.message = message; this.message = message;
this.error = error; this.error = error;

View File

@ -1,7 +1,8 @@
package net.Broken.RestApi.Data; package net.Broken.RestApi.Data;
import java.util.List; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import java.util.List;
/** /**
* Data for JSON Parsing * Data for JSON Parsing
*/ */

View File

@ -25,8 +25,8 @@ public class GetSettingsData {
this.current = current; this.current = current;
} }
public enum TYPE { public enum TYPE{
BOOL, LIST, STRING, SELECT_LIST BOOL,LIST,STRING,SELECT_LIST
} }
} }

View File

@ -12,7 +12,6 @@ public class Value {
this.name = name; this.name = name;
this.id = id; this.id = id;
} }
public Value(String name, String id, boolean selected) { public Value(String name, String id, boolean selected) {
this.name = name; this.name = name;
this.id = id; this.id = id;

View File

@ -2,7 +2,6 @@ package net.Broken.RestApi.Data;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.audio.UserAudioTrack; import net.Broken.audio.UserAudioTrack;
/** /**
* Data for JSON Parsing * Data for JSON Parsing
*/ */
@ -15,7 +14,7 @@ public class UserAudioTrackData {
this.audioTrackInfo = audioTrackInfo; this.audioTrackInfo = audioTrackInfo;
} }
public UserAudioTrackData(UserAudioTrack userAudioTrack) { public UserAudioTrackData(UserAudioTrack userAudioTrack){
this.audioTrackInfo = userAudioTrack.getAudioTrack().getInfo(); this.audioTrackInfo = userAudioTrack.getAudioTrack().getInfo();
this.user = userAudioTrack.getSubmittedUser().getName(); this.user = userAudioTrack.getSubmittedUser().getName();
} }

View File

@ -1,5 +1,8 @@
package net.Broken.RestApi; package net.Broken.RestApi;
import net.Broken.DB.Entity.PlaylistEntity;
import net.Broken.DB.Entity.TrackEntity;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.PlaylistRepository; import net.Broken.DB.Repository.PlaylistRepository;
import net.Broken.DB.Repository.TrackRepository; import net.Broken.DB.Repository.TrackRepository;
import net.Broken.DB.Repository.UserRepository; import net.Broken.DB.Repository.UserRepository;
@ -7,10 +10,14 @@ import net.Broken.MainBot;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController @RestController
@RequestMapping("/api/") @RequestMapping("/api/")
public class GeneralApiController { public class GeneralApiController {
@ -32,10 +39,12 @@ public class GeneralApiController {
} }
@RequestMapping(value = "/isReady", method = RequestMethod.GET) @RequestMapping(value = "/isReady", method = RequestMethod.GET)
public ResponseEntity<String> isReady() { public ResponseEntity<String> isReady(){
if (MainBot.ready) { if(MainBot.ready){
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} else { }
else
{
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} }
} }

View File

@ -44,22 +44,22 @@ public class PlaylistAPIController {
@RequestMapping("/myPlaylist") @RequestMapping("/myPlaylist")
public List<PlaylistEntity> myPlaylist(@CookieValue(value = "token", defaultValue = "") String token) { public List<PlaylistEntity> myPlaylist(@CookieValue(value = "token", defaultValue = "") String token){
if (token.isEmpty()) if(token.isEmpty())
return null; return null;
else { else{
UserEntity user = userRepository.findByApiToken(token).get(0); UserEntity user = userRepository.findByApiToken(token).get(0);
return user.getPlaylists(); return user.getPlaylists();
} }
} }
@RequestMapping("/createPlaylist") @RequestMapping("/createPlaylist")
public ResponseEntity<PlaylistResponseData> createPlaylist(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody CreatePlaylistData data) { public ResponseEntity<PlaylistResponseData> createPlaylist(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody CreatePlaylistData data){
if (token.isEmpty()) if(token.isEmpty())
return new ResponseEntity<>(new PlaylistResponseData("Unknown Token!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(new PlaylistResponseData("Unknown Token!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED);
else { else{
UserEntity user = userRepository.findByApiToken(token).get(0); UserEntity user = userRepository.findByApiToken(token).get(0);
PlaylistEntity playlistEntity = new PlaylistEntity(data.name, user); PlaylistEntity playlistEntity = new PlaylistEntity(data.name, user);
playlistEntity = playlistRepository.save(playlistEntity); playlistEntity = playlistRepository.save(playlistEntity);
@ -72,7 +72,7 @@ public class PlaylistAPIController {
} }
@RequestMapping("/addToPlaylist") @RequestMapping("/addToPlaylist")
public ResponseEntity<PlaylistResponseData> addToPlaylist(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody AddToPlaylistData data) { public ResponseEntity<PlaylistResponseData> addToPlaylist(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody AddToPlaylistData data){
PlaylistManager playlistManager = PlaylistManager.getINSTANCE(); PlaylistManager playlistManager = PlaylistManager.getINSTANCE();
return playlistManager.addToPlaylist(token, data); return playlistManager.addToPlaylist(token, data);
@ -80,7 +80,7 @@ public class PlaylistAPIController {
} }
@RequestMapping("/dellTrack") @RequestMapping("/dellTrack")
public ResponseEntity<PlaylistResponseData> dellTrack(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody DeleteTrackData data) { public ResponseEntity<PlaylistResponseData> dellTrack(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody DeleteTrackData data){
PlaylistManager playlistManager = PlaylistManager.getINSTANCE(); PlaylistManager playlistManager = PlaylistManager.getINSTANCE();
return playlistManager.removeTrack(token, data); return playlistManager.removeTrack(token, data);
@ -88,7 +88,7 @@ public class PlaylistAPIController {
} }
@RequestMapping("/moveTrack") @RequestMapping("/moveTrack")
public ResponseEntity<PlaylistResponseData> moveTrack(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody MoveTrackData data) { public ResponseEntity<PlaylistResponseData> moveTrack(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody MoveTrackData data){
PlaylistManager playlistManager = PlaylistManager.getINSTANCE(); PlaylistManager playlistManager = PlaylistManager.getINSTANCE();
return playlistManager.moveTrack(token, data); return playlistManager.moveTrack(token, data);
@ -96,4 +96,6 @@ public class PlaylistAPIController {
} }
} }

View File

@ -1,14 +1,23 @@
package net.Broken.RestApi; package net.Broken.RestApi;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.DB.Repository.UserRepository; import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.RestApi.Data.Settings.GetSettingsData; import net.Broken.RestApi.Data.Settings.GetSettingsData;
import net.Broken.RestApi.Data.Settings.ListPostSetting; import net.Broken.RestApi.Data.Settings.ListPostSetting;
import net.Broken.RestApi.Data.Settings.PostSetSettings;
import net.Broken.RestApi.Data.Settings.Value;
import net.Broken.Tools.SettingsUtils; import net.Broken.Tools.SettingsUtils;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException; import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
import net.Broken.Tools.UserManager.UserUtils; import net.Broken.Tools.UserManager.UserUtils;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -16,14 +25,16 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.RegEx;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
@RestController @RestController
@RequestMapping("/api") @RequestMapping("/api")
public class SettingAPIController { public class SettingAPIController {
private Logger logger = LogManager.getLogger();
final final
UserRepository userRepository; UserRepository userRepository;
private Logger logger = LogManager.getLogger();
@Autowired @Autowired
public SettingAPIController(UserRepository userRepository) { public SettingAPIController(UserRepository userRepository) {
@ -32,42 +43,45 @@ public class SettingAPIController {
@RequestMapping(value = "/settings", method = RequestMethod.GET) @RequestMapping(value = "/settings", method = RequestMethod.GET)
public ResponseEntity<ArrayList<GetSettingsData>> getSettings(@CookieValue("token") String token, @CookieValue("guild") String guild) { public ResponseEntity<ArrayList<GetSettingsData>> getSettings(@CookieValue("token") String token, @CookieValue("guild") String guild){
SettingsUtils settingUtils = SettingsUtils.getInstance(); SettingsUtils settingUtils = SettingsUtils.getInstance();
if (settingUtils.checkPermission(token, guild)) { if(settingUtils.checkPermission(token, guild)){
Guild jdaGuild = MainBot.jda.getGuildById(guild); Guild jdaGuild = MainBot.jda.getGuildById(guild);
return new ResponseEntity<>(settingUtils.extractSettings(jdaGuild), HttpStatus.OK); return new ResponseEntity<>( settingUtils.extractSettings(jdaGuild), HttpStatus.OK);
} else { }
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); else{
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
} }
} }
@RequestMapping(value = "/settings", method = RequestMethod.POST) @RequestMapping(value = "/settings", method = RequestMethod.POST)
public ResponseEntity<String> setSetting(@CookieValue("token") String token, @CookieValue("guild") String guild, @RequestBody ListPostSetting settings) { public ResponseEntity<String> setSetting(@CookieValue("token") String token, @CookieValue("guild") String guild, @RequestBody ListPostSetting settings){
SettingsUtils settingUtils = SettingsUtils.getInstance(); SettingsUtils settingUtils = SettingsUtils.getInstance();
if (settingUtils.checkPermission(token, guild)) { if(settingUtils.checkPermission(token, guild)){
Guild jdaGuild = MainBot.jda.getGuildById(guild); Guild jdaGuild = MainBot.jda.getGuildById(guild);
try { try {
UserEntity user = UserUtils.getInstance().getUserWithApiToken(userRepository, token); UserEntity user = UserUtils.getInstance().getUserWithApiToken(userRepository,token);
logger.info(user.getName() + " change config of " + jdaGuild.getName()); logger.info(user.getName() + " change config of " + jdaGuild.getName());
} catch (UnknownTokenException e) { } catch (UnknownTokenException e) {
e.printStackTrace(); e.printStackTrace();
} }
if (settingUtils.setSettings(jdaGuild, settings.settings)) { if(settingUtils.setSettings(jdaGuild, settings.settings)){
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} else { }else{
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} }
} else { }
else{
logger.warn("Try to change setting, UNAUTHORIZED. TOKEN: " + token + " GUILD: " + guild); logger.warn("Try to change setting, UNAUTHORIZED. TOKEN: " + token + " GUILD: " + guild);
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
} }
} }
} }

View File

@ -1,15 +1,13 @@
package net.Broken.RestApi; package net.Broken.RestApi;
import net.Broken.DB.Entity.PendingUserEntity;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.PendingUserRepository; import net.Broken.DB.Repository.PendingUserRepository;
import net.Broken.DB.Repository.UserRepository; import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.RestApi.Data.UserManager.GuildInfo; import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.RestApi.Data.UserManager.UserConnectionData; import net.Broken.RestApi.Data.UserManager.*;
import net.Broken.RestApi.Data.UserManager.UserInfoData; import net.Broken.Tools.UserManager.Exceptions.*;
import net.Broken.Tools.UserManager.Exceptions.PasswordNotMatchException;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
import net.Broken.Tools.UserManager.Exceptions.UserNotFoundException;
import net.Broken.Tools.UserManager.Oauth; import net.Broken.Tools.UserManager.Oauth;
import net.Broken.Tools.UserManager.Stats.GuildStatsPack; import net.Broken.Tools.UserManager.Stats.GuildStatsPack;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils; import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
@ -17,6 +15,7 @@ import net.Broken.Tools.UserManager.UserUtils;
import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import org.apache.http.HttpResponse;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -35,12 +34,15 @@ import java.util.List;
@RestController @RestController
@RequestMapping("/api/userManagement") @RequestMapping("/api/userManagement")
public class UserManagerAPIController { public class UserManagerAPIController {
Logger logger = LogManager.getLogger();
final final
PendingUserRepository pendingUserRepository; PendingUserRepository pendingUserRepository;
final final
UserRepository userRepository; UserRepository userRepository;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
Logger logger = LogManager.getLogger();
UserUtils userUtils = UserUtils.getInstance(); UserUtils userUtils = UserUtils.getInstance();
@Autowired @Autowired
@ -51,65 +53,66 @@ public class UserManagerAPIController {
} }
// @RequestMapping(value = "/preRegister", method = RequestMethod.POST) @RequestMapping(value = "/preRegister", method = RequestMethod.POST)
// public ResponseEntity<CheckResposeData> command(@RequestBody UserInfoData data) { public ResponseEntity<CheckResposeData> command(@RequestBody UserInfoData data){
// if (data != null && data.name != null) { if(data != null && data.name != null) {
// try { try {
// String id = userUtils.sendCheckToken(pendingUserRepository, userRepository, passwordEncoder, data); String id = userUtils.sendCheckToken(pendingUserRepository, userRepository, passwordEncoder, data);
// return new ResponseEntity<>(new CheckResposeData(true, data.name, "Message sent", id), HttpStatus.OK); return new ResponseEntity<>(new CheckResposeData(true, data.name, "Message sent", id), HttpStatus.OK);
// } catch (UserNotFoundException e) { } catch (UserNotFoundException e) {
// logger.warn("User \"" + data.name + "\" not found!"); logger.warn("User \"" + data.name + "\" not found!");
// return new ResponseEntity<>(new CheckResposeData(false, data.name, "User not found on server!", ""), HttpStatus.NOT_FOUND); return new ResponseEntity<>(new CheckResposeData(false, data.name, "User not found on server!",""), HttpStatus.NOT_FOUND);
// } catch (PasswordNotMatchException userAlreadyRegistered) { } catch (PasswordNotMatchException userAlreadyRegistered) {
// return new ResponseEntity<>(new CheckResposeData(false, data.name, "User already registered in pending database and password not match!", ""), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new CheckResposeData(false, data.name, "User already registered in pending database and password not match!",""), HttpStatus.NOT_ACCEPTABLE);
//
// } catch (UserAlreadyRegistered userAlreadyRegistered) {
// return new ResponseEntity<>(new CheckResposeData(false, data.name, "User already registered in database!", ""), HttpStatus.NOT_ACCEPTABLE);
// }
// } else {
// return new ResponseEntity<>(new CheckResposeData(false, "", "Missing parameter(s)", ""), HttpStatus.BAD_REQUEST);
// }
// }
// @RequestMapping(value = "/confirmAccount", method = RequestMethod.POST) } catch (UserAlreadyRegistered userAlreadyRegistered) {
// public ResponseEntity<UserConnectionData> confirAccount(@RequestBody ConfirmData data) { return new ResponseEntity<>(new CheckResposeData(false, data.name, "User already registered in database!",""), HttpStatus.NOT_ACCEPTABLE);
// try { }
// PendingUserEntity pUser = userUtils.confirmCheckToken(pendingUserRepository, Integer.parseInt(data.id), data.checkToken); }
// UserEntity user = new UserEntity(pUser, userUtils.generateApiToken()); else{
// userRepository.save(user); return new ResponseEntity<>(new CheckResposeData(false, "", "Missing parameter(s)",""), HttpStatus.BAD_REQUEST);
// pendingUserRepository.delete(pUser); }
// }
// return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK);
// } catch (TokenNotMatch tokenNotMatch) { @RequestMapping(value = "/confirmAccount", method = RequestMethod.POST)
// logger.warn("Pre token not match for " + data.id + "!"); public ResponseEntity<UserConnectionData> confirAccount(@RequestBody ConfirmData data){
// return new ResponseEntity<>(new UserConnectionData(false, "Token not match!", "token"), HttpStatus.NOT_ACCEPTABLE); try {
// } catch (UserNotFoundException e) { PendingUserEntity pUser = userUtils.confirmCheckToken(pendingUserRepository, Integer.parseInt(data.id), data.checkToken);
// logger.warn("Id not found in DB (" + data.id + ")"); UserEntity user = new UserEntity(pUser, userUtils.generateApiToken());
// return new ResponseEntity<>(new UserConnectionData(false, "User not found on DB!", "user"), HttpStatus.NOT_ACCEPTABLE); userRepository.save(user);
// } pendingUserRepository.delete(pUser);
// }
return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(),""),HttpStatus.OK);
} catch (TokenNotMatch tokenNotMatch) {
logger.warn("Pre token not match for "+data.id+"!");
return new ResponseEntity<>(new UserConnectionData(false,"Token not match!","token"),HttpStatus.NOT_ACCEPTABLE);
} catch (UserNotFoundException e) {
logger.warn("Id not found in DB ("+data.id+")");
return new ResponseEntity<>(new UserConnectionData(false,"User not found on DB!", "user"),HttpStatus.NOT_ACCEPTABLE);
}
}
@RequestMapping(value = "/requestToken", method = RequestMethod.POST) @RequestMapping(value = "/requestToken", method = RequestMethod.POST)
public ResponseEntity<UserConnectionData> requestToken(@RequestBody UserInfoData data) { public ResponseEntity<UserConnectionData> requestToken(@RequestBody UserInfoData data){
try { try {
UserEntity user = userUtils.getUser(userRepository, passwordEncoder, data); UserEntity user = userUtils.getUser(userRepository, passwordEncoder, data);
return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK); return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK);
} catch (UserNotFoundException e) { } catch (UserNotFoundException e) {
return new ResponseEntity<>(new UserConnectionData(false, "User not registered!", "user"), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new UserConnectionData(false,"User not registered!", "user"),HttpStatus.NOT_ACCEPTABLE);
} catch (PasswordNotMatchException e) { } catch (PasswordNotMatchException e) {
return new ResponseEntity<>(new UserConnectionData(false, "Wrong user name or password!", "password"), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(new UserConnectionData(false,"Wrong user name or password!", "password"),HttpStatus.NOT_ACCEPTABLE);
} }
} }
@RequestMapping(value = "/getGuilds", method = RequestMethod.GET) @RequestMapping(value = "/getGuilds", method = RequestMethod.GET)
public ResponseEntity<List<GuildInfo>> getGuilds(@CookieValue("token") String token) { public ResponseEntity<List<GuildInfo>> getGuilds(@CookieValue("token") String token){
try { try {
UserEntity userE = userUtils.getUserWithApiToken(userRepository, token); UserEntity userE = userUtils.getUserWithApiToken(userRepository, token);
User user = MainBot.jda.getUserById(userE.getJdaId()); User user = MainBot.jda.getUserById(userE.getJdaId());
List<GuildInfo> temp = new ArrayList<>(); List<GuildInfo> temp = new ArrayList<>();
if (user != null) { if(user != null){
for (Guild guild : user.getMutualGuilds()) { for (Guild guild : user.getMutualGuilds()){
temp.add(new GuildInfo(guild.getName(), guild.getId(), guild.getMember(user).hasPermission(Permission.ADMINISTRATOR), guild.getIconUrl())); temp.add(new GuildInfo(guild.getName(), guild.getId(), guild.getMember(user).hasPermission(Permission.ADMINISTRATOR), guild.getIconUrl()));
} }
@ -126,21 +129,24 @@ public class UserManagerAPIController {
} }
@RequestMapping(value = "/oauthLogin", method = RequestMethod.POST) @RequestMapping(value = "/oauthLogin", method = RequestMethod.POST)
public ResponseEntity<UserConnectionData> oauthLogin(@RequestParam(value = "token") String discordToken) { public ResponseEntity<UserConnectionData> oauthLogin(@RequestParam(value = "token") String discordToken){
logger.debug(discordToken); logger.debug(discordToken);
UserEntity user = Oauth.getInstance().getUserEntity(discordToken, userRepository, passwordEncoder); UserEntity user = Oauth.getInstance().getUserEntity(discordToken, userRepository, passwordEncoder);
logger.info("OAuth login for " + user.getName()); logger.info("OAuth login for " + user.getName());
return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK); return new ResponseEntity<>(new UserConnectionData(true, user.getName(), user.getApiToken(), ""), HttpStatus.OK);
} }
@RequestMapping(value = "/checkToken", method = RequestMethod.GET) @RequestMapping(value = "/checkToken", method = RequestMethod.GET)
public ResponseEntity checkToken(@CookieValue(value = "token") String token) { public ResponseEntity checkToken(@CookieValue(value = "token") String token){
try { try{
userUtils.getUserWithApiToken(userRepository, token); userUtils.getUserWithApiToken(userRepository,token);
return new ResponseEntity(HttpStatus.OK); return new ResponseEntity(HttpStatus.OK);
} catch (UnknownTokenException e) { } catch (UnknownTokenException e) {
logger.info("Token check fail"); logger.info("Token check fail");
@ -149,11 +155,11 @@ public class UserManagerAPIController {
} }
@RequestMapping(value = "/getStatsPack", method = RequestMethod.GET) @RequestMapping(value = "/getStatsPack", method = RequestMethod.GET)
public ResponseEntity<GuildStatsPack> getStatsPack(@CookieValue(value = "token") String token, @RequestParam(value = "guild") String guildID) { public ResponseEntity<GuildStatsPack> getStatsPack(@CookieValue(value = "token") String token, @RequestParam(value = "guild") String guildID){
try { try{
UserEntity user = userUtils.getUserWithApiToken(userRepository, token); UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
Guild guild = MainBot.jda.getGuildById(guildID); Guild guild = MainBot.jda.getGuildById(guildID);
if (guild == null) { if(guild == null ){
logger.warn("Request whit no guild!"); logger.warn("Request whit no guild!");
return new ResponseEntity(HttpStatus.BAD_REQUEST); return new ResponseEntity(HttpStatus.BAD_REQUEST);
} }
@ -161,6 +167,7 @@ public class UserManagerAPIController {
return new ResponseEntity<>(UserStatsUtils.getINSTANCE().getStatPack(user, guildID), HttpStatus.OK); return new ResponseEntity<>(UserStatsUtils.getINSTANCE().getStatPack(user, guildID), HttpStatus.OK);
} catch (UnknownTokenException e) { } catch (UnknownTokenException e) {
logger.info("Token check fail"); logger.info("Token check fail");
return new ResponseEntity(HttpStatus.UNAUTHORIZED); return new ResponseEntity(HttpStatus.UNAUTHORIZED);
@ -168,4 +175,7 @@ public class UserManagerAPIController {
} }
} }

View File

@ -12,8 +12,7 @@ import java.util.List;
public interface SlashCommand { public interface SlashCommand {
/** /**
* Main action of command * Main action of command
* * @param args Command args.
* @param args Command args.
* @param event Command MessageReceivedEvent * @param event Command MessageReceivedEvent
*/ */
void action(SlashCommandEvent event); void action(SlashCommandEvent event);
@ -26,14 +25,12 @@ public interface SlashCommand {
/** /**
* Determines if the command is usable only by bot level admin user * Determines if the command is usable only by bot level admin user
*
* @return boolean * @return boolean
*/ */
boolean isBotAdminCmd(); boolean isBotAdminCmd();
/** /**
* Determines if the command is only usable on NSFW channels * Determines if the command is only usable on NSFW channels
*
* @return boolean * @return boolean
*/ */
boolean isNSFW(); boolean isNSFW();

View File

@ -1,10 +1,15 @@
package net.Broken.SlashCommands; package net.Broken.SlashCommands;
import net.Broken.Commande;
import net.Broken.SlashCommand; import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -23,9 +28,7 @@ import java.util.List;
* Command that return a random picture of cat. * Command that return a random picture of cat.
*/ */
public class Cat implements SlashCommand { public class Cat implements SlashCommand {
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();;
;
@Override @Override
public void action(SlashCommandEvent event) { public void action(SlashCommandEvent event) {
try { try {
@ -45,7 +48,7 @@ public class Cat implements SlashCommand {
} catch (IOException e) { } catch (IOException e) {
logger.catching(e); logger.catching(e);
event.reply(new MessageBuilder().setEmbeds(EmbedMessageUtils.getInternalError()).build()).setEphemeral(true).queue(); event.reply(new MessageBuilder().setEmbeds(EmbedMessageUtils.getInternalError()).build()).queue();
} }
@ -58,7 +61,7 @@ public class Cat implements SlashCommand {
@Override @Override
public List<OptionData> getOptions() { public List<OptionData> getOptions() {
return null; return new ArrayList<>();
} }
@Override @Override

View File

@ -1,58 +0,0 @@
package net.Broken.SlashCommands;
import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import java.util.ArrayList;
import java.util.List;
public class Clear implements SlashCommand {
@Override
public void action(SlashCommandEvent event) {
if (event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
event.reply(":white_check_mark: Done").setEphemeral(true).queue();
long n = event.getOption("n").getAsLong();
MessageChannel chanel = event.getChannel();
chanel.getIterableHistory().takeAsync((int) n).thenAccept(chanel::purgeMessages);
} else {
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getFlushError("You are not a supreme being, you cannot do that !")).build();
event.reply(message).setEphemeral(true).queue();
}
}
@Override
public String getDescription() {
return "Clear the last [n] message(s)";
}
@Override
public List<OptionData> getOptions() {
ArrayList<OptionData> options = new ArrayList<>();
options.add(new OptionData(OptionType.INTEGER, "n", "The number of message(s) to clear", true));
return options;
}
@Override
public List<SubcommandData> getSubcommands() {
return null;
}
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -1,41 +0,0 @@
package net.Broken.SlashCommands;
import net.Broken.SlashCommand;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import java.util.List;
public class Invite implements SlashCommand {
@Override
public void action(SlashCommandEvent event) {
event.reply(event.getJDA().setRequiredScopes("bot", "applications.commands").getInviteUrl(Permission.ADMINISTRATOR)).setEphemeral(true).queue();
}
@Override
public String getDescription() {
return "Get the link to invite this bot to your server";
}
@Override
public List<OptionData> getOptions() {
return null;
}
@Override
public List<SubcommandData> getSubcommands() {
return null;
}
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -1,8 +1,10 @@
package net.Broken.SlashCommands; package net.Broken.SlashCommands;
import net.Broken.MainBot;
import net.Broken.SlashCommand; import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.audio.AudioM; import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message;
@ -14,7 +16,13 @@ import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -44,22 +52,45 @@ public class Music implements SlashCommand {
} }
} else { } else {
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("You are not in a voice channel !")).build(); Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("You are not in a voice channel !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue(); event.getHook().sendMessage(message).queue();
}
break;
case "add":
OptionMapping url = event.getOption("url");
boolean next = false;
if (event.getOption("next") != null) {
next = event.getOption("next").getAsBoolean();
}
if (event.getOption("playlist-limit") == null) {
audio.add(event, url.getAsString(), 30, next);
} else {
long limit = event.getOption("playlist-limit").getAsLong();
audio.add(event, url.getAsString(), (int) limit, next);
} }
break; break;
// case "add":
// event.getTextChannel().sendTyping().queue();
// if(args.length ==2){
// audio.add(event,args[1],30,false);
// }
// else if(args.length == 3){
// try{
// int limit = Integer.parseInt(args[2]);
// audio.add(event,args[1],limit,false);
// }catch (NumberFormatException e){
// audio.add(event,args[1],30,false);
// }
// }
// else{
// Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicError("Missing argument!")).complete();
// List<Message> messages = new ArrayList<Message>(){{
// add(message);
// add(event.getMessage());
// }};
// new MessageTimeOut(messages, MainBot.messageTimeOut).start();
// }
// break;
// case "addNext":
// event.getTextChannel().sendTyping().queue();
// if(args.length >=2){
// audio.add(event,args[1],1,true);
// }
// else{
// Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getMusicError("Missing argument!")).complete();
// List<Message> messages = new ArrayList<Message>(){{
// add(message);
// add(event.getMessage());
// }};
// new MessageTimeOut(messages, MainBot.messageTimeOut).start();
// }
// break;
case "pause": case "pause":
audio.pause(event); audio.pause(event);
break; break;
@ -83,6 +114,8 @@ public class Music implements SlashCommand {
audio.list(event); audio.list(event);
break; break;
} }
} }
@Override @Override
@ -98,13 +131,11 @@ public class Music implements SlashCommand {
@Override @Override
public List<SubcommandData> getSubcommands() { public List<SubcommandData> getSubcommands() {
ArrayList<SubcommandData> subCommandList = new ArrayList<>(); ArrayList<SubcommandData> subCommandList = new ArrayList<>();
subCommandList.add(new SubcommandData("play", "Play music") subCommandList.add(new SubcommandData("play", "Play somme music")
.addOption(OptionType.STRING, "url", "The URL of the video to play", true) .addOption(OptionType.STRING, "url", "The URL of the video to play", true)
.addOption(OptionType.INTEGER, "playlist-limit", "If a playlist is loaded, enter the max number of loaded tracks (default to 30)")); .addOption(OptionType.INTEGER, "playlist-limit", "If a playlist is loaded, enter the max number of loaded tracks"));
subCommandList.add(new SubcommandData("add", "Add track to queue") subCommandList.add(new SubcommandData("add", "Add music to queue")
.addOption(OptionType.STRING, "url", " The URL of the video to play", true) .addOption(OptionType.STRING, "url", " The URL of the video to play", true));
.addOption(OptionType.BOOLEAN, "next", "If true, track will be added on top of the playlist and will be the next to play")
.addOption(OptionType.INTEGER, "playlist-limit", "If a playlist is loaded, enter the max number of loaded tracks (default to 30)"));
subCommandList.add(new SubcommandData("pause", "Pause playback")); subCommandList.add(new SubcommandData("pause", "Pause playback"));
subCommandList.add(new SubcommandData("resume", "Resume playback")); subCommandList.add(new SubcommandData("resume", "Resume playback"));
subCommandList.add(new SubcommandData("stop", "Stop playback")); subCommandList.add(new SubcommandData("stop", "Stop playback"));

View File

@ -7,17 +7,18 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class SpringContext implements ApplicationContextAware { public class SpringContext implements ApplicationContextAware{
@Autowired @Autowired
static ApplicationContext context; static ApplicationContext context;
public static ApplicationContext getAppContext() {
return context;
}
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext; context = applicationContext;
} }
public static ApplicationContext getAppContext(){
return context;
}
} }

View File

@ -0,0 +1,173 @@
package net.Broken.Tools;
import net.Broken.MainBot;
import net.Broken.Commands.Move;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.HierarchyException;
import net.dv8tion.jda.api.managers.GuildManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Thread.sleep;
/**
* AntiSpam punishment system
*/
public class AntiSpam {
Logger logger = LogManager.getLogger();
public Move move = new Move();
public AntiSpam() {
}
/**
* Send user to Spam role
* @param user User to punish
* @param guild Guild
* @param guildManager GuildManager
* @param incrMulti True for increment punishment time
* @param event Message Received Event
*/
public void extermine(Member user, Guild guild, GuildManager guildManager, Boolean incrMulti, MessageReceivedEvent event){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// On créer un nouvelle case dans le tableau des statuts si il n'y est pas
if(!MainBot.spamUtils.containsKey(user))
{
List<Message> messages = new ArrayList<>();
messages.addAll(MainBot.historique.get(user));
MainBot.spamUtils.put(user,new UserSpamUtils(user,messages));
}
// On verrifie que l'uttilisateur n'est pas deja en spam
if(!MainBot.spamUtils.get(user).isOnSpam())
{
//l'utilisateur n'est pas deja en spam
if(MainBot.spamUtils.get(user).getMultip() != 0)
{
if(MainBot.spamUtils.get(user).getMultip()<45 && incrMulti)
{
MainBot.spamUtils.get(user).setMultip(MainBot.spamUtils.get(user).getMultip()*2);
}
}
else
MainBot.spamUtils.get(user).setMultip(1);
logger.info("Starting protocol 66 on "+user.getEffectiveName()+" with a multiplicator of "+MainBot.spamUtils.get(user));
if(!MainBot.spamUtils.get(user).isOnSpam())
{
MainBot.spamUtils.get(user).setOnSpam(true);
List<Role> spm = guild.getRolesByName("Spammer", false);
if(spm.size() != 0){
try{
move.exc(user, spm, true, guild, guildManager);
MainBot.spamUtils.get(user).addMessage(event.getTextChannel().sendMessage(EmbedMessageUtils.getSpamExtermine(user,MainBot.spamUtils.get(user.getUser()).getMultip())).complete());
MainBot.spamUtils.get(user).setMinuteur(new Minuteur(MainBot.spamUtils.get(user).getMultip(), move.user, move.saveRoleUser, move.serveur, move.serveurManager,event));
MainBot.spamUtils.get(user).launchMinuteur();
}catch (HierarchyException e){
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveError("You cannot move a "+user.getRoles().get(0).getAsMention())).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
MainBot.spamUtils.get(user).setOnSpam(false);
}
}
else {
MessageEmbed msg = EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("\nSpam role not found, you need to create it!"));
event.getTextChannel().sendMessage(msg).complete();
}
}
}
}
/**
* Timer to auto remove user from Spam role
*/
public class Minuteur extends Thread{
public TextChannel chanel;
public List<Role> saveRoleUser;
public Member user;
public Guild serveur;
public GuildManager serveurManager;
public int multip;
public MessageReceivedEvent event;
public int timeLeft;
public Minuteur(int multip, Member user, List<Role> saveRoleUser, Guild serveur, GuildManager serveurManager, MessageReceivedEvent event )
{
this.multip=multip;
this.user=user;
this.saveRoleUser=saveRoleUser;
this.serveur=serveur;
this.serveurManager=serveurManager;
this.event=event;
this.chanel=event.getTextChannel();
this.timeLeft = 60*multip;
}
@Override
public void run() {
logger.info("["+user.getEffectiveName()+"] Start for "+multip+"min");
while (MainBot.spamUtils.get(user).isOnSpam())
{
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(timeLeft<=0)
{
MainBot.spamUtils.get(user.getUser()).setOnSpam(false);
}
timeLeft--;
}
logger.info("["+user.getEffectiveName()+"] End of spam for "+user.getEffectiveName()+" after "+multip+"min.");
try {
move.exc(user, saveRoleUser, true, serveur, serveurManager); //aSaveroleUser=saveRoleUser.get(i)
}catch (HierarchyException e){
Message rest = event.getTextChannel().sendMessage(EmbedMessageUtils.getMoveError("You cannot move "+user.getRoles().get(0).getAsMention())).complete();
List<Message> messages = new ArrayList<Message>(){{
add(rest);
add(event.getMessage());
}};
new MessageTimeOut(messages,MainBot.messageTimeOut).start();
logger.error("Hierarchy error");
}
logger.info("["+user.getEffectiveName()+"] End for "+multip+"min");
new MessageTimeOut(new ArrayList<>(MainBot.spamUtils.get(user).getMessages()),0).start();
MainBot.spamUtils.get(user).clearAndAdd(chanel.sendMessage(EmbedMessageUtils.getSpamPardon(user)).complete());
new MessageTimeOut(MainBot.spamUtils.get(user).getMessages(),60).start();
// #-----------------------------------------------#
}
}
}

View File

@ -9,10 +9,7 @@ import net.dv8tion.jda.api.requests.RestAction;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static net.Broken.MainBot.jda; import static net.Broken.MainBot.jda;
@ -23,10 +20,6 @@ public class AutoVoiceChannel {
private final String guildID; private final String guildID;
private final HashMap<Integer, String> createdChannels = new HashMap<>(); private final HashMap<Integer, String> createdChannels = new HashMap<>();
public AutoVoiceChannel(Guild guild) {
this.guildID = guild.getId();
}
public static AutoVoiceChannel getInstance(Guild guild) { public static AutoVoiceChannel getInstance(Guild guild) {
if (INSTANCE_MAP.get(guild.getId()) == null) { if (INSTANCE_MAP.get(guild.getId()) == null) {
INSTANCE_MAP.put(guild.getId(), new AutoVoiceChannel(guild)); INSTANCE_MAP.put(guild.getId(), new AutoVoiceChannel(guild));
@ -34,6 +27,10 @@ public class AutoVoiceChannel {
return INSTANCE_MAP.get(guild.getId()); return INSTANCE_MAP.get(guild.getId());
} }
public AutoVoiceChannel(Guild guild) {
this.guildID = guild.getId();
}
public void join(VoiceChannel voiceChannel) { public void join(VoiceChannel voiceChannel) {
Guild guild = jda.getGuildById(guildID); Guild guild = jda.getGuildById(guildID);
if (guild == null) if (guild == null)
@ -44,7 +41,7 @@ public class AutoVoiceChannel {
VoiceChannel newChannel = voiceChannel.createCopy().complete(); VoiceChannel newChannel = voiceChannel.createCopy().complete();
int next = getNextNumber(); int next = getNextNumber();
String title = pref.getAutoVoiceChannelTitle(); String title = pref.getAutoVoiceChannelTitle();
if (title.isEmpty()) { if (title.isEmpty()){
title = "Voice @count"; title = "Voice @count";
} }
title = title.replace("@count", Integer.toString(next)); title = title.replace("@count", Integer.toString(next));

View File

@ -40,13 +40,13 @@ public class CommandLoader {
if (command.isAnnotationPresent(NoDev.class) && MainBot.dev) { if (command.isAnnotationPresent(NoDev.class) && MainBot.dev) {
logger.warn("Command disabled in dev mode"); logger.warn("Command disabled in dev mode");
} else { }else{
try { try {
MainBot.commandes.put(name, command.newInstance()); MainBot.commandes.put(name, command.newInstance());
} catch (InstantiationException | IllegalAccessException e) { } catch (InstantiationException | IllegalAccessException e) {
logger.error("Failed to load " + name + "!"); logger.error("Failed to load " + name + "!");
} }
} }
} else { } else {

View File

@ -16,31 +16,32 @@ public class CommandParser {
/** /**
* Parse raw received string. * Parse raw received string.
*
* @param brt Raw command string. * @param brt Raw command string.
* @param e Event * @param e Event
* @return Readable container that contain all useful data * @return Readable container that contain all useful data
*/ */
public CommandContainer parse(String brt, MessageReceivedEvent e) { public CommandContainer parse(String brt, MessageReceivedEvent e)
ArrayList<String> split = new ArrayList<String>(); {
String brut = brt; ArrayList<String> split =new ArrayList<String>();
String sansTete = brut.replaceFirst("//", ""); String brut =brt;
String sansTete = brut.replaceFirst("//","");
String[] splitSansTete = sansTete.split(" "); String[] splitSansTete = sansTete.split(" ");
for (String s : splitSansTete) { for(String s : splitSansTete){
if (s.length() > 0) if(s.length()>0)
split.add(s); split.add(s);
} }
String commande = split.get(0); String commande = split.get(0);
String[] args = new String[split.size() - 1]; String[] args = new String[split.size()-1];
split.subList(1, split.size()).toArray(args); split.subList(1,split.size()).toArray(args);
for (int i = 0; i < args.length; i++) for(int i=0;i<args.length;i++)
args[i] = args[i].replace('$', ' '); args[i]=args[i].replace('$',' ');
logger.info("Author: " + e.getAuthor().getName() + ", Command: " + commande + ", args: " + Arrays.toString(args));
logger.info("Author: "+e.getAuthor().getName()+", Command: "+commande+", args: "+ Arrays.toString(args));
return new CommandContainer(brut, sansTete, splitSansTete, commande, args, e); return new CommandContainer(brut, sansTete, splitSansTete, commande, args, e);
@ -49,7 +50,7 @@ public class CommandParser {
/** /**
* Container * Container
*/ */
public class CommandContainer { public class CommandContainer{
public final String brut; public final String brut;
public final String sansTete; public final String sansTete;
public final String[] splitSansTete; public final String[] splitSansTete;
@ -57,13 +58,14 @@ public class CommandParser {
public final String[] args; public final String[] args;
public final MessageReceivedEvent event; public final MessageReceivedEvent event;
public CommandContainer(String brut, String sansTete, String[] splitSansTete, String commande, String[] args, MessageReceivedEvent e) { public CommandContainer(String brut, String sansTete, String[] splitSansTete, String commande, String[] args, MessageReceivedEvent e)
this.brut = brut; {
this.sansTete = sansTete; this.brut=brut;
this.splitSansTete = splitSansTete; this.sansTete=sansTete;
this.commande = commande; this.splitSansTete=splitSansTete;
this.args = args; this.commande=commande;
this.event = e; this.args=args;
this.event= e;
} }
} }
} }

View File

@ -1,5 +1,4 @@
package net.Broken.Tools.Command; package net.Broken.Tools.Command;
import net.Broken.Commande; import net.Broken.Commande;
import net.Broken.Tools.FindContentOnWebPage; import net.Broken.Tools.FindContentOnWebPage;
import net.Broken.Tools.LimitChecker; import net.Broken.Tools.LimitChecker;
@ -12,13 +11,15 @@ import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
/** /**
* Abstact class used for all command that need to find the max number of page on a web site. * Abstact class used for all command that need to find the max number of page on a web site.
*/ */
@Ignore @Ignore
public abstract class NumberedCommande implements Commande { public abstract class NumberedCommande implements Commande{
private Logger logger = LogManager.getLogger();
protected int minNumber = 1; protected int minNumber = 1;
protected int maxNumber = -1; protected int maxNumber = -1;
protected String baseURL; protected String baseURL;
@ -26,13 +27,11 @@ public abstract class NumberedCommande implements Commande {
protected String htmlType; protected String htmlType;
protected String urlSuffix; protected String urlSuffix;
protected LinkedBlockingQueue<Integer> randomQueue = new LinkedBlockingQueue<>(); protected LinkedBlockingQueue<Integer> randomQueue = new LinkedBlockingQueue<>();
private Logger logger = LogManager.getLogger();
/** /**
* Default constructor * Default constructor
* * @param logger Logger used for logs
* @param logger Logger used for logs * @param baseURL WebSite base url
* @param baseURL WebSite base url
* @param divClass DivClass to search to extract image * @param divClass DivClass to search to extract image
* @param htmlType HTML tag to extract image (img) * @param htmlType HTML tag to extract image (img)
*/ */
@ -45,25 +44,29 @@ public abstract class NumberedCommande implements Commande {
try { try {
logger.debug("Checking max..."); logger.debug("Checking max...");
maxNumber = LimitChecker.doYourJob(baseURL, 2, urlSuffix); maxNumber = LimitChecker.doYourJob(baseURL, 2, urlSuffix);
logger.info("Limit is " + maxNumber); logger.info("Limit is "+maxNumber);
} catch (IOException e) { } catch (IOException e) {
logger.catching(e); logger.catching(e);
} }
} }
public NumberedCommande(Logger logger, String baseURL, String urlSuffix) { public NumberedCommande(Logger logger, String baseURL, String urlSuffix){
this(logger, baseURL, urlSuffix, null, null); this(logger, baseURL, urlSuffix, null, null);
} }
@Override @Override
public void action(String[] args, MessageReceivedEvent event) { public void action(String[] args, MessageReceivedEvent event) {
try { try
if (args.length == 0) { {
String result = poll(); if(args.length == 0)
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n" + result).queue(); {
String result = poll();
event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n"+result).queue();
} else { }
else
{
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "update": case "update":
logger.info("update commande from " + event.getMessage().getAuthor().getName()); logger.info("update commande from " + event.getMessage().getAuthor().getName());
@ -136,7 +139,7 @@ public abstract class NumberedCommande implements Commande {
protected void checkRandom() throws IOException { protected void checkRandom() throws IOException {
logger.trace("Queue size: " + randomQueue.size()); logger.trace("Queue size: " + randomQueue.size());
if (randomQueue.isEmpty()) { if(randomQueue.isEmpty()){
logger.debug("Queue empty, update it."); logger.debug("Queue empty, update it.");
completeRandom(); completeRandom();
} }

View File

@ -1,11 +1,13 @@
package net.Broken.Tools.Command; package net.Broken.Tools.Command;
import net.Broken.Commande;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.SlashCommand; import net.Broken.SlashCommand;
import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction; import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.jboss.jandex.Main;
import org.reflections.Reflections; import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper; import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder; import org.reflections.util.ConfigurationBuilder;
@ -43,11 +45,10 @@ public class SlashCommandLoader {
if (command.isAnnotationPresent(NoDev.class) && MainBot.dev) { if (command.isAnnotationPresent(NoDev.class) && MainBot.dev) {
logger.warn("Command disabled in dev mode"); logger.warn("Command disabled in dev mode");
} else { }else{
try { try {
MainBot.slashCommands.put(name, command.getDeclaredConstructor().newInstance()); MainBot.slashCommands.put(name, command.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
NoSuchMethodException e) {
logger.error("Failed to load " + name + "!"); logger.error("Failed to load " + name + "!");
} }
@ -60,12 +61,12 @@ public class SlashCommandLoader {
} }
} }
public static void registerSlashCommands(CommandListUpdateAction commandListUpdateAction) { public static void registerSlashCommands(CommandListUpdateAction commandListUpdateAction){
MainBot.slashCommands.forEach((k, v) -> { MainBot.slashCommands.forEach((k,v)->{
CommandData command = new CommandData(k, v.getDescription()); CommandData command = new CommandData(k, v.getDescription());
if (v.getOptions() != null) if(v.getOptions() != null)
command.addOptions(v.getOptions()); command.addOptions(v.getOptions());
if (v.getSubcommands() != null) { if(v.getSubcommands() != null){
command.addSubcommands(v.getSubcommands()); command.addSubcommands(v.getSubcommands());
} }
commandListUpdateAction.addCommands(command); commandListUpdateAction.addCommands(command);

View File

@ -1,5 +1,6 @@
package net.Broken.Tools.DayListener; package net.Broken.Tools.DayListener;
import net.Broken.Commands.Spam;
import net.dv8tion.jda.api.exceptions.RateLimitedException;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -11,14 +12,15 @@ import java.util.GregorianCalendar;
* Day change listener * Day change listener
*/ */
public class DayListener extends Thread { public class DayListener extends Thread {
private static DayListener INSTANCE = new DayListener();
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
private Calendar calendar; private Calendar calendar;
private int previousDay; private int previousDay;
/** /**
* List of listeners to need to be triggered * List of listeners to need to be triggered
*/ */
private ArrayList<NewDayListener> listeners = new ArrayList<>(); private ArrayList<NewDayListener> listeners = new ArrayList<>();
private static DayListener INSTANCE = new DayListener();
/** /**
@ -32,30 +34,29 @@ public class DayListener extends Thread {
/** /**
* Singleton * Singleton
*
* @return Unique DayListener instance. * @return Unique DayListener instance.
*/ */
public static DayListener getInstance() { public static DayListener getInstance()
{
return INSTANCE; return INSTANCE;
} }
/** /**
* Add Listener who will be triggered * Add Listener who will be triggered
*
* @param listener * @param listener
*/ */
public void addListener(NewDayListener listener) { public void addListener(NewDayListener listener){
listeners.add(listener); listeners.add(listener);
} }
/** /**
* Trigger all listeners * Trigger all listeners
*/ */
public void trigger() { public void trigger(){
for (NewDayListener listener : listeners) { for(NewDayListener listener : listeners){
try { try{
listener.onNewDay(); listener.onNewDay();
} catch (Exception ex) { }catch (Exception ex){
logger.error("Fail to execute day change !"); logger.error("Fail to execute day change !");
logger.catching(ex); logger.catching(ex);
} }
@ -68,9 +69,11 @@ public class DayListener extends Thread {
*/ */
@Override @Override
public void run() { public void run() {
while (true) { while(true)
{
calendar = Calendar.getInstance(); calendar = Calendar.getInstance();
if (calendar.get(GregorianCalendar.DAY_OF_MONTH) != previousDay) { if(calendar.get(GregorianCalendar.DAY_OF_MONTH) != previousDay)
{
LogManager.getLogger().info("New day triggered!"); LogManager.getLogger().info("New day triggered!");
trigger(); trigger();
previousDay = calendar.get(GregorianCalendar.DAY_OF_MONTH); previousDay = calendar.get(GregorianCalendar.DAY_OF_MONTH);

View File

@ -7,6 +7,7 @@ import net.Broken.MainBot;
import net.Broken.SpringContext; import net.Broken.SpringContext;
import net.Broken.Tools.DayListener.NewDayListener; import net.Broken.Tools.DayListener.NewDayListener;
import net.Broken.Tools.FindContentOnWebPage; import net.Broken.Tools.FindContentOnWebPage;
import net.Broken.Tools.Redirection;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.TextChannel;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -14,24 +15,26 @@ import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.io.IOException; import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.List; import java.util.List;
/** /**
* Daily Listener for DailyMadame * Daily Listener for DailyMadame
*/ */
public class DailyMadame implements NewDayListener { public class DailyMadame implements NewDayListener{
private GuildPreferenceRepository guildPreferenceRepository; private GuildPreferenceRepository guildPreferenceRepository;
private Logger logger = LogManager.getLogger();
public DailyMadame() { public DailyMadame() {
ApplicationContext context = SpringContext.getAppContext(); ApplicationContext context = SpringContext.getAppContext();
guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository"); guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository");
} }
private Logger logger = LogManager.getLogger();
@Override @Override
public void onNewDay() { public void onNewDay() {
@ -40,7 +43,7 @@ public class DailyMadame implements NewDayListener {
String imgUrl; String imgUrl;
try { try {
int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
if (day != Calendar.MONDAY && day != Calendar.SUNDAY) { if(day != Calendar.MONDAY && day != Calendar.SUNDAY){
LocalDate now = LocalDate.now().minusDays(1); LocalDate now = LocalDate.now().minusDays(1);
String date = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(now); String date = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(now);
@ -49,37 +52,41 @@ public class DailyMadame implements NewDayListener {
imgUrl = FindContentOnWebPage.doYourJob(url, "post-content", "img"); imgUrl = FindContentOnWebPage.doYourJob(url, "post-content", "img");
} else { }else {
Madame command = (Madame) MainBot.commandes.get("madame"); Madame command = (Madame) MainBot.commandes.get("madame");
imgUrl = command.poll(); imgUrl = command.poll();
} }
for (Guild guild : guilds) {
for(Guild guild : guilds){
TextChannel chanel = null; TextChannel chanel = null;
logger.debug(guild.getName()); logger.debug(guild.getName());
List<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId()); List<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId());
if (guildPref.size() > 0 && guildPref.get(0).isDailyMadame()) { if( guildPref.size() > 0 && guildPref.get(0).isDailyMadame()){
for (TextChannel iterator : guild.getTextChannels()) { for(TextChannel iterator : guild.getTextChannels())
if (iterator.isNSFW() && iterator.canTalk()) { {
if(iterator.isNSFW() && iterator.canTalk()){
chanel = iterator; chanel = iterator;
logger.debug("break: " + chanel.getName()); logger.debug("break: " + chanel.getName());
break; break;
} }
} }
if (chanel != null) { if(chanel != null){
chanel.sendMessage("Madame of the day :kissing_heart: \n" + imgUrl).queue(); chanel.sendMessage("Madame of the day :kissing_heart: \n" + imgUrl).queue();
} else { }
else {
logger.info("No NSFW chanel found for " + guild.getName() + ", ignoring it!"); logger.info("No NSFW chanel found for " + guild.getName() + ", ignoring it!");
} }
} }
} }
} catch (IOException e) { }catch (IOException e) {
logger.catching(e); logger.catching(e);
} }
} }

View File

@ -0,0 +1,24 @@
package net.Broken.Tools.DayListener.Listeners;
import net.Broken.Commands.Spam;
import net.Broken.Tools.DayListener.NewDayListener;
import net.dv8tion.jda.api.exceptions.RateLimitedException;
import java.util.GregorianCalendar;
/**
* Daily spam reset
*/
public class ResetSpam implements NewDayListener {
@Override
public void onNewDay() {
Spam spam = new Spam();
String str[] = {"all"};
try {
spam.reset(null,str);
} catch (RateLimitedException e) {
e.printStackTrace();
}
}
}

View File

@ -1,13 +1,18 @@
package net.Broken.Tools; package net.Broken.Tools;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.audio.Youtube.SearchResult; import net.Broken.audio.Youtube.SearchResult;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.MessageEmbed;
import java.awt.*; import java.awt.*;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -15,15 +20,26 @@ import java.util.Map;
* Pre build Message Embed * Pre build Message Embed
*/ */
public class EmbedMessageUtils { public class EmbedMessageUtils {
public static MessageEmbed getUnknowCommand() {
return new EmbedBuilder().setTitle(":warning: Unknown command! :warning:").setDescription(":arrow_right: Use `//help` to see the available commands.").setColor(Color.orange).setFooter(MainBot.url, MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build();
}
public static EmbedBuilder getError(String message) { public static EmbedBuilder getError(String message) {
EmbedBuilder temp = new EmbedBuilder().setTitle(":warning: Error! :warning:").setColor(Color.red).setDescription(message); EmbedBuilder temp = new EmbedBuilder().setTitle(":warning: Error! :warning:").setColor(Color.red).setDescription(message);
return temp; return temp;
} }
public static MessageEmbed getNoPrivate(){
EmbedBuilder temp = new EmbedBuilder().setTitle(":warning: Command not available in private :warning:").setDescription(":arrow_right: Use `//help` to see the available commands.").setColor(Color.red);
return buildStandar(temp);
}
public static MessageEmbed getMusicError(String message){
return new EmbedBuilder().setTitle(":warning: Musique Error :warning:").setDescription(":arrow_right: "+message).setFooter("'//help music' for more info.",MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).setColor(Color.red).setFooter(MainBot.url, MainBot.jda.getSelfUser().getAvatarUrl()).build();
public static MessageEmbed getMusicError(String message) {
return new EmbedBuilder().setTitle(":warning: Musique Error :warning:").setDescription(":arrow_right: " + message).setFooter("'//help music' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).setColor(Color.red).setFooter(MainBot.url, MainBot.jda.getSelfUser().getAvatarUrl()).build();
} }
public static MessageEmbed getMusicOk(String message) { public static MessageEmbed getMusicOk(String message) {
@ -31,34 +47,94 @@ public class EmbedMessageUtils {
return buildStandar(temp); return buildStandar(temp);
} }
public static MessageEmbed getFlushError(String message) { public static MessageEmbed getSpamExtermine(Member autor, int multi) {
return buildStandar(new EmbedBuilder().setTitle(":warning: Flush Error :warning: ").setDescription(message).setColor(Color.red)); return new EmbedBuilder().setTitle(":mute: Spam Hunter :mute:").setDescription(autor.getAsMention() + " detected as spam !\n\nSee you in __**" + multi + "**__ minutes!").setImage("https://media.giphy.com/media/WVudyGEaizNeg/giphy.gif").setFooter("Spam info available with '//spaminfo' in private.", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).setTimestamp(Instant.now()).setColor(Color.orange).setColor(Color.orange).build();
} }
public static MessageEmbed getSpamPardon(Member autor) {
return new EmbedBuilder().setTitle(":mute: Spam Hunter :mute:").setDescription(autor.getAsMention() + " is back , watch out!\nI'm watching you!").setImage("https://media.giphy.com/media/3o7TKwBctlv08kY08M/giphy.gif").setFooter("Spam info available with '//spaminfo' in private.", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).setColor(Color.orange).build();
}
public static MessageEmbed getInternalError() { public static MessageEmbed getHelp(String command) throws FileNotFoundException {
String name = command.substring(0, 1).toUpperCase() + command.substring(1).toLowerCase();
String message = new ResourceLoader().getFile("Help/"+name+"/en/main.md");
EmbedBuilder temp = new EmbedBuilder().setTitle(":question: " + command.substring(0, 1).toUpperCase() + command.substring(1).toLowerCase() + " :question: ").setDescription(message).setColor(Color.green);
return buildStandar(temp);
}
public static MessageEmbed getMoveError(String message) {
return new EmbedBuilder().setTitle(":warning: Move Error :warning: ").setDescription(message).setColor(Color.red).setFooter("'//help move' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build();
}
public static MessageEmbed getMoveOk(String message) {
EmbedBuilder temp = new EmbedBuilder().setTitle(":arrow_left: Move :arrow_right: ").setDescription(message).setColor(Color.green);
return buildStandar(temp);
}
public static MessageEmbed getSpamError(String message) {
return new EmbedBuilder().setTitle(":warning: Spam Error :warning: ").setDescription(message).setColor(Color.red).setFooter("'//help spam' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()).build();
}
public static MessageEmbed getSpamError(String message, String sub) {
return new EmbedBuilder().setTitle(":warning: Spam Error :warning: ").setDescription(message).setColor(Color.red).setFooter("'//help spam "+sub+"' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()).setThumbnail(MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build();
}
public static MessageEmbed getSpamInfo(String message) {
EmbedBuilder temp = new EmbedBuilder().setTitle(":hourglass: Spam Info :hourglass:").setDescription(message).setColor(Color.green);
return buildStandar(temp);
}
public static MessageEmbed getFlushError(String message) {
return new EmbedBuilder().setTitle(":warning: Flush Error :warning: ").setDescription(message).setColor(Color.red).setFooter("'//help flush' for more info. ", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build();
}
public static MessageEmbed getRegister(String message) {
return buildStandar(new EmbedBuilder().setTitle(":pencil: Web Registration :pencil:").setDescription(message).setColor(Color.green));
}
public static MessageEmbed getInternalError(){
return buildStandar(getError("I... I... I don't feel so good ~~mr stark~~... :thermometer_face: \nPlease contact my developer!").setImage("https://i.imgur.com/anKv8U5.gif")); return buildStandar(getError("I... I... I don't feel so good ~~mr stark~~... :thermometer_face: \nPlease contact my developer!").setImage("https://i.imgur.com/anKv8U5.gif"));
} }
public static MessageEmbed buildStandar(EmbedBuilder embedBuilder) { public static MessageEmbed buildStandar(EmbedBuilder embedBuilder){
return embedBuilder.setFooter(MainBot.url, MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build(); return embedBuilder.setFooter(MainBot.url, MainBot.jda.getSelfUser().getAvatarUrl()).setThumbnail(MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build();
} }
public static MessageEmbed getUnautorized() { public static MessageEmbed getUnautorized(){
return buildStandar(getError("You're not powerful enough to do that slave !").setImage("https://i.imgur.com/0OSsdvW.gif")); return buildStandar(getError("You're not powerful enough to do that slave !").setImage("https://i.imgur.com/0OSsdvW.gif"));
} }
public static MessageEmbed getHelpList(String role, String list) throws FileNotFoundException {
String message = new ResourceLoader().getFile("Help/main.md");
message = message.replace("@list", list);
return new EmbedBuilder().setTitle("Bot Command ("+role+")").setDescription(message).setFooter("Use '//help <command>' for more info",MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).setColor(Color.green).setThumbnail(MainBot.jda.getSelfUser().getAvatarUrl()).build();
}
public static MessageEmbed getLastMessageFromTextChannel(HashMap<String, String> message) { public static MessageEmbed getLastMessageFromTextChannel(HashMap<String, String> message) {
EmbedBuilder temp = new EmbedBuilder().setTitle("Channel uses checker").setDescription("Last message date for channels:").setColor(Color.green); EmbedBuilder temp = new EmbedBuilder().setTitle("Channel uses checker").setDescription("Last message date for channels:").setColor(Color.green);
for (Map.Entry<String, String> entry : message.entrySet()) { for(Map.Entry<String, String> entry : message.entrySet()) {
temp.addField(entry.getKey(), entry.getValue(), false); temp.addField(entry.getKey(),entry.getValue(), false);
} }
return buildStandar(temp); return buildStandar(temp);
} }
public static MessageEmbed getReportUsersError() { public static MessageEmbed getReportUsersError(){
return new EmbedBuilder().setTitle(":warning: Command error :warning: ").setDescription("").setColor(Color.red).setFooter("'//help move' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build(); return new EmbedBuilder().setTitle(":warning: Command error :warning: ").setDescription("").setColor(Color.red).setFooter("'//help move' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build();
} }
public static MessageEmbed searchResult(SearchResult result){
EmbedBuilder builder = new EmbedBuilder()
.setColor(Color.CYAN)
.setTitle(result.title)
.setImage(result.imageUrl)
.addField("Duration: ", result.duration, false)
.addField("URL:","https://www.youtube.com/watch?v="+result.id,false)
.addField("Chanel:", result.channelTittle, false);
return buildStandar(builder);
}
} }

View File

@ -6,11 +6,10 @@ import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
public class FindContentOnWebPage { public class FindContentOnWebPage {
/** /**
* Find picture URL on webPage * Find picture URL on webPage
* * @param url Web Page URL
* @param url Web Page URL
* @param divClass Div class where the picture is * @param divClass Div class where the picture is
* @param htmlType HTML tag of image (img) * @param htmlType HTML tag of image (img)
* @return Picture URL * @return Picture URL
@ -19,13 +18,13 @@ public class FindContentOnWebPage {
public static String doYourJob(String url, String divClass, String htmlType) throws IOException { public static String doYourJob(String url, String divClass, String htmlType) throws IOException {
// System.out.println(url); // System.out.println(url);
String source = getSourceUrl(url); String source = getSourceUrl(url);
int divIndex = source.indexOf("class=\"" + divClass); int divIndex = source.indexOf("class=\""+divClass);
String sub = source.substring(divIndex); String sub = source.substring(divIndex);
// System.out.println(sub); // System.out.println(sub);
sub = sub.replace(divClass, ""); sub = sub.replace(divClass,"");
sub = sub.substring(sub.indexOf(htmlType)); sub = sub.substring(sub.indexOf(htmlType));
sub = sub.substring(sub.indexOf("src")); sub = sub.substring(sub.indexOf("src"));
sub = sub.replace("src=\"", ""); sub = sub.replace("src=\"","");
String[] split = sub.split("\""); String[] split = sub.split("\"");
// System.out.println(split[0]); // System.out.println(split[0]);
return split[0]; return split[0];
@ -33,7 +32,6 @@ public class FindContentOnWebPage {
/** /**
* Get source code of web page * Get source code of web page
*
* @param url Web page URL * @param url Web page URL
* @return Web page source as String * @return Web page source as String
* @throws IOException * @throws IOException
@ -41,7 +39,7 @@ public class FindContentOnWebPage {
public static String getSourceUrl(String url) throws IOException { public static String getSourceUrl(String url) throws IOException {
URL urlC = new URL(url); URL urlC = new URL(url);
URLConnection yc = urlC.openConnection(); URLConnection yc = urlC.openConnection();
yc.setRequestProperty("User-Agent", "Googlebot/2.1 (+http://www.googlebot.com/bot.html)"); yc.setRequestProperty("User-Agent","Googlebot/2.1 (+http://www.googlebot.com/bot.html)");
BufferedReader in = new BufferedReader(new InputStreamReader( BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8")); yc.getInputStream(), "UTF-8"));
String inputLine; String inputLine;

View File

@ -3,7 +3,9 @@ package net.Broken.Tools;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
/** /**
@ -15,8 +17,7 @@ public class LimitChecker {
/** /**
* Check max page url for web site like baseURL.com/number-2/ * Check max page url for web site like baseURL.com/number-2/
* * @param baseURL Base url without numbers
* @param baseURL Base url without numbers
* @param minNumber Start number * @param minNumber Start number
* @return max Number * @return max Number
* @throws IOException * @throws IOException
@ -27,53 +28,57 @@ public class LimitChecker {
boolean redirected = false; boolean redirected = false;
Redirection redirection = new Redirection(); Redirection redirection = new Redirection();
while (!redirected) { while(!redirected )
String origin = baseURL + number + suffix; {
String origin = baseURL+number+suffix;
String newUrl = redirection.get(origin); String newUrl = redirection.get(origin);
logger.trace("Origin URL: " + origin + " Result: " + newUrl); logger.trace("Origin URL: "+origin+" Result: "+newUrl);
if (newUrl.equals(origin)) if(newUrl.equals(origin))
number += 500; number += 500;
else else
redirected = true; redirected = true;
} }
number -= 400; number-=400;
redirected = false; redirected = false;
logger.debug("First pass: " + number); logger.debug("First pass: "+number);
while (!redirected) { while(!redirected )
String origin = baseURL + number + suffix; {
String origin = baseURL+number+suffix;
String newUrl = redirection.get(origin); String newUrl = redirection.get(origin);
logger.trace("Origin URL: " + origin + " Result: " + newUrl); logger.trace("Origin URL: "+origin+" Result: "+newUrl);
if (newUrl.equals(origin)) if(newUrl.equals(origin))
number += 100; number += 100;
else else
redirected = true; redirected = true;
} }
number -= 90; number-=90;
redirected = false; redirected = false;
logger.debug("Second pass: " + number); logger.debug("Second pass: "+number);
while (!redirected) { while(!redirected )
String origin = baseURL + number + suffix; {
String origin = baseURL+number+suffix;
String newUrl = redirection.get(origin); String newUrl = redirection.get(origin);
logger.trace("Origin URL: " + origin + " Result: " + newUrl); logger.trace("Origin URL: "+origin+" Result: "+newUrl);
if (newUrl.equals(origin)) if(newUrl.equals(origin))
number += 10; number += 10;
else else
redirected = true; redirected = true;
} }
number -= 9; number-=9;
redirected = false; redirected = false;
logger.debug("Third pass: " + number); logger.debug("Third pass: "+number);
while (!redirected) { while(!redirected )
String origin = baseURL + number + suffix; {
String origin = baseURL+number+suffix;
String newUrl = redirection.get(origin); String newUrl = redirection.get(origin);
logger.trace("Origin URL: " + origin + " Result: " + newUrl); logger.trace("Origin URL: "+origin+" Result: "+newUrl);
if (newUrl.equals(origin)) if(newUrl.equals(origin))
number += 1; number += 1;
else else
redirected = true; redirected = true;
} }
number -= 1; number-=1;
logger.debug("Final pass: " + number); logger.debug("Final pass: "+number);
return number; return number;

View File

@ -0,0 +1,52 @@
package net.Broken.Tools;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Auto dell message util
*/
public class MessageTimeOut extends Thread{
List<Message> messages;
int second;
Logger logger = LogManager.getLogger();
public MessageTimeOut(List<Message> messages, int second) {
this.messages = messages;
this.second = second;
}
public MessageTimeOut(int second, Message... messages) {
this.messages = Arrays.asList(messages);
this.second = second;
}
@Override
public void run() {
logger.debug("Timer for message deletion stated...");
for(int i=0; i<second; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
logger.debug("Time out! Deleting message!");
for(Message aMessage: messages)
{
try {
aMessage.delete().queue();
}catch (ErrorResponseException e){
logger.warn("Unknown Message");
}
}
}
}

View File

@ -0,0 +1,129 @@
package net.Broken.Tools;
import net.Broken.MainBot;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.managers.GuildManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
/**
* Auto spam utils TODO Rebuild all this shit!
*/
public class Moderateur {
Logger logger = LogManager.getLogger();
public Moderateur() {}
// Cette méthode récupère le dernier message est le rajoute à "historique"
// SI (spam) retourne 1 (si l'user spam)
// SINON retourne 0
/**
* Get last message and add it on history. After analyse for spam detection
* @param user User
* @param guild Guild
* @param guildManager Guild manager
* @param event Message received event
* @return 1 if detected as spam, else 0
*/
public int analyse(Member user, Guild guild, GuildManager guildManager, MessageReceivedEvent event){
ArrayList<Message> thisUserHistory = new ArrayList<>();//Creer tableau pour la copie
int i = 0; // variable de parcours de "historique"
int nbMessage = 3;
int spam = 0;
if(MainBot.spamUtils.containsKey(user) && MainBot.spamUtils.get(user).isOnSpam()){
MainBot.spamUtils.get(user).addMessage(event.getMessage());
}
/********************************************
* si l'USER a deja envoyé un message *
********************************************/
if(MainBot.historique.containsKey(user))// Si le user a deja posté un message
{
/********************************************
* COPIE des infos d"historique" vers TOI[] *
********************************************/
thisUserHistory = (ArrayList<Message>) MainBot.historique.get(user).clone();
/********************************************
* Ajout dernier message recu + dans histo' *
********************************************/
thisUserHistory.add(0,event.getMessage());
if(thisUserHistory.size()>nbMessage+1)
thisUserHistory.remove(4);
MainBot.historique.put(user, thisUserHistory);// On ajoute dans l'historique TOI
/*****************************
* ANALYSE des messages *
*****************************/
int equalCont = 0;
String oldMessage = "";
for(Message aMessage : thisUserHistory){
if(aMessage.getContentRaw().equals(oldMessage))
equalCont++;
oldMessage = aMessage.getContentRaw();
}
if(equalCont >= nbMessage){
spam = 1;
logger.info("Spam detected for "+user.getEffectiveName()+"with 3 identical messages : ");
for(Message aMessage : thisUserHistory)
{
logger.info("\t - "+aMessage.getContentRaw());
}
MainBot.historique.put(user, new ArrayList<Message>());
}
} else {
/********************************************
* SI c'est le 1er message de l'USER *
********************************************/
// si le user n'a pas encore posté de message
// on ajoute le dernier message dans "historique"
thisUserHistory.add(0,event.getMessage());
MainBot.historique.put(user, thisUserHistory);
}
/**********************************
* AFFICHAGE DE HISTORIQUE *
**********************************/
/********************************************
* Comptage du nombre de message *
********************************************/
if(MainBot.message_compteur.containsKey(user))// Si le user a deja posté un message
{
int cpt = MainBot.message_compteur.get(user);
cpt++;
//System.out.println("compteur : "+cpt);
MainBot.message_compteur.put(user, cpt);
if(cpt > 5){
MainBot.message_compteur.put(user,0);
spam = 1;
logger.info("Spam detected for "+user.getEffectiveName()+"with 5 messages in 5 secondes: ");
ArrayList<Message> histo = MainBot.historique.get(user);
for (Message aMessage:histo )
{
// logger.debug("\t*"+aMessage.getContent());
}
}
}else{
MainBot.message_compteur.put(user, 1);
}
return spam;
}
}

View File

@ -0,0 +1,36 @@
package net.Broken.Tools;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User;
import org.apache.logging.log4j.Logger;
/**
* Private message utils
*/
public class PrivateMessage {
/**
* Auto open private channel and send message
* @param user User to send message
* @param message Message to send
* @param logger Logger
*/
public static void send(User user, String message, Logger logger){
user.openPrivateChannel().complete().sendMessage(message).queue();
}
/**
* Auto open private channel and send message
* @param user User to send message
* @param message Message to send
* @param logger Logger
* @return Sended Message
*/
public static Message send(User user, MessageEmbed message, Logger logger){
return user.openPrivateChannel().complete().sendMessage(message).complete();
}
}

View File

@ -4,34 +4,34 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.net.URLConnection;
/** /**
* Redirection URL Util * Redirection URL Util
*/ */
public class Redirection { public class Redirection {
public Redirection() { public Redirection(){
} }
/** /**
* Return Redirected URL * Return Redirected URL
*
* @param urlString Source URL * @param urlString Source URL
* @return Redirected URL * @return Redirected URL
* @throws IOException * @throws IOException
*/ */
public String get(String urlString) throws IOException { public String get(String urlString) throws IOException {
System.setProperty("http.agent", "Googlebot"); System.setProperty("http.agent","Googlebot");
HttpURLConnection con = (HttpURLConnection) new URL(urlString).openConnection(); HttpURLConnection con = (HttpURLConnection) new URL(urlString).openConnection();
con.setRequestProperty("User-Agent", "Googlebot/2.1 (+http://www.googlebot.com/bot.html)"); con.setRequestProperty("User-Agent","Googlebot/2.1 (+http://www.googlebot.com/bot.html)");
//System.out.println( "orignal url: " + con.getURL() ); //System.out.println( "orignal url: " + con.getURL() );
con.connect(); con.connect();
//System.out.println( "connected url: " + con.getURL() ); //System.out.println( "connected url: " + con.getURL() );
InputStream is = null; InputStream is = null;
if (con.getResponseCode() != 200) if(con.getResponseCode() != 200)
return ""; return "";
is = con.getInputStream(); is = con.getInputStream();
String urlReturn = con.getURL().toString(); String urlReturn=con.getURL().toString();
//System.out.println( "redirected url: " + con.getURL() ); //System.out.println( "redirected url: " + con.getURL() );
is.close(); is.close();
@ -39,4 +39,5 @@ public class Redirection {
} }
} }

View File

@ -3,18 +3,20 @@ package net.Broken.Tools;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Scanner; import java.util.Scanner;
public class ResourceLoader { public class ResourceLoader {
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
/** /**
* Get file contents as string for resource folder * Get file contents as string for resource folder
*
* @param fileName Requested file * @param fileName Requested file
* @return File contents as string * @return File contents as string
* @throws FileNotFoundException * @throws FileNotFoundException
@ -26,7 +28,7 @@ public class ResourceLoader {
//Get file from resources folder //Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader(); ClassLoader classLoader = getClass().getClassLoader();
InputStream file = classLoader.getResourceAsStream(fileName); InputStream file = classLoader.getResourceAsStream(fileName);
if (file == null) if(file == null)
throw new FileNotFoundException(); throw new FileNotFoundException();
try (Scanner scanner = new Scanner(file, "UTF-8")) { try (Scanner scanner = new Scanner(file, "UTF-8")) {

View File

@ -17,14 +17,22 @@ import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
public class SettingsUtils { public class SettingsUtils {
private static SettingsUtils INSTANCE; private static SettingsUtils INSTANCE;
private final Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
public static SettingsUtils getInstance() {
return (INSTANCE == null) ? new SettingsUtils() : INSTANCE;
}
private final GuildPreferenceRepository guildPreferenceRepository; private final GuildPreferenceRepository guildPreferenceRepository;
private final UserRepository userRepository; private final UserRepository userRepository;
private SettingsUtils() { private SettingsUtils() {
ApplicationContext context = SpringContext.getAppContext(); ApplicationContext context = SpringContext.getAppContext();
guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository"); guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository");
@ -33,10 +41,6 @@ public class SettingsUtils {
} }
public static SettingsUtils getInstance() {
return (INSTANCE == null) ? new SettingsUtils() : INSTANCE;
}
/** /**
* Extract all settings for displaying on webpage * Extract all settings for displaying on webpage
* *

View File

@ -1,13 +1,13 @@
package net.Broken.Tools; package net.Broken.Tools;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import org.apache.commons.lang3.StringUtils;
/** /**
* Utils to render table in block code * Utils to render table in block code
*/ */
@ -25,7 +25,6 @@ public class TableRenderer {
/** /**
* Set Table header(s) * Set Table header(s)
*
* @param header Header(s) as String * @param header Header(s) as String
*/ */
public void setHeader(Object... header) { public void setHeader(Object... header) {
@ -36,7 +35,6 @@ public class TableRenderer {
/** /**
* Add row to table * Add row to table
*
* @param content Content(s) as string * @param content Content(s) as string
*/ */
public void addRow(Object... content) { public void addRow(Object... content) {
@ -48,7 +46,6 @@ public class TableRenderer {
/** /**
* Change default empty string * Change default empty string
*
* @param str * @param str
*/ */
public void setEmptyString(String str) { public void setEmptyString(String str) {
@ -75,7 +72,7 @@ public class TableRenderer {
if (obj.size() > hIndex) if (obj.size() > hIndex)
normalized[vIndex][hIndex] = obj.get(hIndex).toString(); normalized[vIndex][hIndex] = obj.get(hIndex).toString();
else else
normalized[vIndex][hIndex] = this.empty + "s"; normalized[vIndex][hIndex] = this.empty+"s";
} }
vIndex++; vIndex++;
} }
@ -89,7 +86,7 @@ public class TableRenderer {
for (int hIndex = 0; hIndex < width; hIndex++) for (int hIndex = 0; hIndex < width; hIndex++)
if (table[vIndex][hIndex].length() + padding > collums[hIndex]) if (table[vIndex][hIndex].length() + padding > collums[hIndex])
collums[hIndex] = table[vIndex][hIndex].length() + padding; collums[hIndex] = table[vIndex][hIndex].length() + padding;
collums[collums.length - 1] -= padding; collums[collums.length-1] -= padding;
return collums; return collums;
} }
@ -105,7 +102,7 @@ public class TableRenderer {
String line = IntStream.range(0, strings.length) String line = IntStream.range(0, strings.length)
.mapToObj((i) -> buildElement(strings[i], widths[i], " ")) .mapToObj((i) -> buildElement(strings[i], widths[i], " "))
.collect(Collectors.joining("")); .collect(Collectors.joining(""));
line = "" + line + ""; line = ""+ line + "";
if (header) { if (header) {
String seperator = IntStream.range(0, strings.length) String seperator = IntStream.range(0, strings.length)
.mapToObj((i) -> buildElement("", widths[i], "")) .mapToObj((i) -> buildElement("", widths[i], ""))
@ -120,7 +117,7 @@ public class TableRenderer {
String[][] table = normalizeTable(); String[][] table = normalizeTable();
int[] widths = getCollumnWidths(table, 1); int[] widths = getCollumnWidths(table, 1);
return IntStream.range(0, table.length) return IntStream.range(0, table.length)
.mapToObj(i -> buildLine(table[i], widths, header != null && i == 0)) .mapToObj(i -> buildLine(table[i], widths, header != null && i==0))
.collect(Collectors.joining("\n")); .collect(Collectors.joining("\n"));
} }
} }

View File

@ -3,12 +3,15 @@ package net.Broken.Tools;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class TimeConvertor { public class TimeConvertor {
static Logger logger = LogManager.getLogger(); static Logger logger = LogManager.getLogger();
public static ArrayList<String> sToTime(long sec){
public static ArrayList<String> sToTime(long sec) {
final int MINUTES_IN_AN_HOUR = 60; final int MINUTES_IN_AN_HOUR = 60;
final int SECONDS_IN_A_MINUTE = 60; final int SECONDS_IN_A_MINUTE = 60;

View File

@ -9,6 +9,7 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.IOException; import java.io.IOException;
@ -19,16 +20,19 @@ import java.util.List;
public class TrueRandom { public class TrueRandom {
private static TrueRandom INSTANCE = new TrueRandom(); private static TrueRandom INSTANCE = new TrueRandom();
private Logger logger = LogManager.getLogger();
private String url = "https://api.random.org/json-rpc/2/invoke";
private String apiKey = System.getenv("RANDOM_API_KEY");
private TrueRandom() {
}
public static TrueRandom getINSTANCE() { public static TrueRandom getINSTANCE() {
return INSTANCE; return INSTANCE;
} }
private Logger logger = LogManager.getLogger();
private String url = "https://api.random.org/json-rpc/2/invoke";
private String apiKey = System.getenv("RANDOM_API_KEY");
private TrueRandom() {
}
public ArrayList<Integer> getNumbers(int min, int max) throws IOException { public ArrayList<Integer> getNumbers(int min, int max) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build(); HttpClient httpClient = HttpClientBuilder.create().build();
@ -42,18 +46,19 @@ public class TrueRandom {
int status = response.getStatusLine().getStatusCode(); int status = response.getStatusLine().getStatusCode();
logger.debug("Status: " + status); logger.debug("Status: " + status);
if (status != 200) { if(status != 200){
logger.error("Request fail! Status: " + status); logger.error("Request fail! Status: " + status);
throw new IOException(); throw new IOException();
} }
InputStream responseIS = response.getEntity().getContent(); InputStream responseIS = response.getEntity().getContent();
String content = IOUtils.toString(responseIS, "UTF-8"); String content = IOUtils.toString(responseIS, "UTF-8");
logger.trace(content); logger.trace(content);
JSONObject json = new JSONObject(content); JSONObject json = new JSONObject(content);
if (json.keySet().contains("error")) { if(json.keySet().contains("error")){
logger.error("Request fail!"); logger.error("Request fail!");
logger.error("Request : " + postVal); logger.error("Request : " + postVal);
logger.error("Response : " + content); logger.error("Response : " + content);

View File

@ -1,4 +1,4 @@
package net.Broken.Tools.UserManager.Exceptions; package net.Broken.Tools.UserManager.Exceptions;
public class PasswordNotMatchException extends Exception { public class PasswordNotMatchException extends Exception{
} }

View File

@ -1,4 +1,4 @@
package net.Broken.Tools.UserManager.Exceptions; package net.Broken.Tools.UserManager.Exceptions;
public class UnknownTokenException extends Exception { public class UnknownTokenException extends Exception{
} }

View File

@ -1,4 +1,4 @@
package net.Broken.Tools.UserManager.Exceptions; package net.Broken.Tools.UserManager.Exceptions;
public class UserNotFoundException extends Exception { public class UserNotFoundException extends Exception{
} }

View File

@ -18,21 +18,21 @@ import java.util.List;
public class Oauth { public class Oauth {
private static Oauth INSTANCE = new Oauth(); private static Oauth INSTANCE = new Oauth();
public static Oauth getInstance(){ return INSTANCE; }
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
private String baseUrl = "https://discordapp.com/api"; private String baseUrl = "https://discordapp.com/api";
private String mePath = "/users/@me"; private String mePath = "/users/@me";
public static Oauth getInstance() {
return INSTANCE;
}
private JSONObject getUserId(String token) {
private JSONObject getUserId(String token){
StringBuffer content = new StringBuffer(); StringBuffer content = new StringBuffer();
try { try {
String httpsURL = baseUrl + mePath; String httpsURL = baseUrl+mePath;
URL myUrl = new URL(httpsURL); URL myUrl = new URL(httpsURL);
HttpURLConnection con = (HttpURLConnection) myUrl.openConnection(); HttpURLConnection con = (HttpURLConnection)myUrl.openConnection();
con.setRequestProperty("Authorization", "Bearer " + token); con.setRequestProperty("Authorization", "Bearer "+token);
con.setRequestProperty("User-Agent", "DiscordBot (claptrapbot.com, 0.1)"); con.setRequestProperty("User-Agent", "DiscordBot (claptrapbot.com, 0.1)");
con.setRequestMethod("GET"); con.setRequestMethod("GET");
logger.debug("Response code: " + con.getResponseCode()); logger.debug("Response code: " + con.getResponseCode());
@ -56,15 +56,15 @@ public class Oauth {
} }
public UserEntity getUserEntity(String token, UserRepository userRepository, PasswordEncoder passwordEncoder) { public UserEntity getUserEntity(String token, UserRepository userRepository, PasswordEncoder passwordEncoder){
JSONObject discorResponse = getUserId(token); JSONObject discorResponse = getUserId(token);
List<UserEntity> userEntitys = userRepository.findByJdaId(discorResponse.getString("id")); List<UserEntity> userEntitys = userRepository.findByJdaId(discorResponse.getString("id"));
if (userEntitys.size() != 0) { if(userEntitys.size() != 0){
return userEntitys.get(0); return userEntitys.get(0);
} else { }else{
User jdaUser = MainBot.jda.getUserById(discorResponse.getString("id")); User jdaUser = MainBot.jda.getUserById(discorResponse.getString("id"));
UserEntity user; UserEntity user;
if (jdaUser == null) if( jdaUser == null)
user = new UserEntity(discorResponse.getString("username"), discorResponse.getString("id"), passwordEncoder); user = new UserEntity(discorResponse.getString("username"), discorResponse.getString("id"), passwordEncoder);
else else
user = new UserEntity(MainBot.jda.getUserById(discorResponse.getString("id")), passwordEncoder); user = new UserEntity(MainBot.jda.getUserById(discorResponse.getString("id")), passwordEncoder);

View File

@ -15,16 +15,17 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.List; import java.util.List;
public class PasswordResetUtils { public class PasswordResetUtils {
private static PasswordResetUtils INSTANCE = new PasswordResetUtils();
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
private PasswordEncoder passwordEncoder; private PasswordEncoder passwordEncoder;
private PendingPwdResetRepository pendingPwdResetRepository; private PendingPwdResetRepository pendingPwdResetRepository;
private UserRepository userRepository; private UserRepository userRepository;
private static PasswordResetUtils INSTANCE = new PasswordResetUtils();
/** /**
* Private default constructor * Private default constructor
*/ */
private PasswordResetUtils() { private PasswordResetUtils(){
ApplicationContext context = SpringContext.getAppContext(); ApplicationContext context = SpringContext.getAppContext();
passwordEncoder = (PasswordEncoder) context.getBean("passwordEncoder"); passwordEncoder = (PasswordEncoder) context.getBean("passwordEncoder");
pendingPwdResetRepository = (PendingPwdResetRepository) context.getBean("pendingPwdResetRepository"); pendingPwdResetRepository = (PendingPwdResetRepository) context.getBean("pendingPwdResetRepository");
@ -34,14 +35,13 @@ public class PasswordResetUtils {
/** /**
* Singleton * Singleton
*
* @return Unique PasswordResetUtils instance * @return Unique PasswordResetUtils instance
*/ */
public static PasswordResetUtils getInstance() { public static PasswordResetUtils getInstance(){
return INSTANCE; return INSTANCE;
} }
public String resetRequest(UserEntity userEntity) { public String resetRequest(UserEntity userEntity){
String token = UserUtils.getInstance().generateCheckToken(); String token = UserUtils.getInstance().generateCheckToken();
String encodedToken = passwordEncoder.encode(token); String encodedToken = passwordEncoder.encode(token);
PendingPwdResetEntity entity = new PendingPwdResetEntity(userEntity, encodedToken); PendingPwdResetEntity entity = new PendingPwdResetEntity(userEntity, encodedToken);
@ -51,10 +51,10 @@ public class PasswordResetUtils {
public void changePass(UserEntity userEntity, String token, String newPassword) throws UserNotFoundException, TokenNotMatch { public void changePass(UserEntity userEntity, String token, String newPassword) throws UserNotFoundException, TokenNotMatch {
List<PendingPwdResetEntity> dbResults = pendingPwdResetRepository.findByUserEntity(userEntity); List<PendingPwdResetEntity> dbResults = pendingPwdResetRepository.findByUserEntity(userEntity);
if (dbResults.size() == 0) if(dbResults.size() == 0)
throw new UserNotFoundException(); throw new UserNotFoundException();
PendingPwdResetEntity pendingPwdReset = dbResults.get(0); PendingPwdResetEntity pendingPwdReset = dbResults.get(0);
if (!passwordEncoder.matches(token, pendingPwdReset.getSecurityToken())) if(!passwordEncoder.matches(token, pendingPwdReset.getSecurityToken()))
throw new TokenNotMatch(); throw new TokenNotMatch();
userEntity.setPassword(passwordEncoder.encode(newPassword)); userEntity.setPassword(passwordEncoder.encode(newPassword));

View File

@ -1,6 +1,6 @@
package net.Broken.Tools.UserManager.Stats; package net.Broken.Tools.UserManager.Stats;
public class GuildStats { public class GuildStats{
public String userName; public String userName;
public int rank; public int rank;
public String avatarUrl; public String avatarUrl;

View File

@ -7,6 +7,7 @@ import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.RestApi.Data.UserManager.UserInfoData; import net.Broken.RestApi.Data.UserManager.UserInfoData;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.PrivateMessage;
import net.Broken.Tools.ResourceLoader; import net.Broken.Tools.ResourceLoader;
import net.Broken.Tools.UserManager.Exceptions.*; import net.Broken.Tools.UserManager.Exceptions.*;
import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.MessageEmbed;
@ -22,44 +23,149 @@ import java.util.UUID;
public class UserUtils { public class UserUtils {
private static UserUtils INSTANCE = new UserUtils();
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
private static UserUtils INSTANCE = new UserUtils();
/** /**
* Private default constructor * Private default constructor
*/ */
private UserUtils() { private UserUtils(){}
}
/** /**
* Singleton * Singleton
*
* @return Unique UserUtils instance * @return Unique UserUtils instance
*/ */
public static UserUtils getInstance() { public static UserUtils getInstance(){
return INSTANCE; return INSTANCE;
} }
/**
* Check if user exist on Guild, if exist, generate and send checkTocken, create entry on PendingUser DB
* @param pendingUserRepository Pending user DB interface
* @param userRepository User DB interface
* @param passwordEncoder Password encoder
* @param userInfo Received data
* @return PendingUserEntity PK
* @throws UserNotFoundException User not found in guild
* @throws PasswordNotMatchException User already registered in PendingUser DB but password not match
* @throws UserAlreadyRegistered User already registered in User DB
*/
public String sendCheckToken(PendingUserRepository pendingUserRepository, UserRepository userRepository, PasswordEncoder passwordEncoder, UserInfoData userInfo) throws UserNotFoundException, PasswordNotMatchException, UserAlreadyRegistered {
logger.info("New registration for " + userInfo.name);
List<User> users = MainBot.jda.getUsersByName(userInfo.name,true);
if(users.size() < 1)
throw new UserNotFoundException();
User user = users.get(0);
logger.info("User found!");
PendingUserEntity pendingUserEntity = null;
String token = "";
//Preference if exist on register user
if(userRepository.findByJdaId(user.getId()).size() > 0){
logger.warn("User already registered!");
throw new UserAlreadyRegistered();
}
//Check if exist in pading user Table
List<PendingUserEntity> pendingUsers = pendingUserRepository.findByJdaId(user.getId());
if(pendingUsers.size() != 0){
PendingUserEntity thisUser = pendingUsers.get(0);
if(passwordEncoder.matches(userInfo.password, thisUser.getPassword())){
logger.info("Password matches");
pendingUserEntity = thisUser;
token = thisUser.getCheckToken();
}else{
logger.warn("Password don't match!");
throw new PasswordNotMatchException();
}
}
logger.info("Generating check Token...");
if(token.equals("")){
token = generateCheckToken();
}
logger.info("Token generated: " + token);
if(pendingUserEntity == null) {
pendingUserEntity = new PendingUserEntity(user.getName(), user.getId(), token, passwordEncoder.encode(userInfo.password));
pendingUserEntity = pendingUserRepository.save(pendingUserEntity);
}
String message = null;
try {
message = new ResourceLoader().getFile("MessagesTemplates/RegisterMessage.md");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
message = message.replace("%code",token);
MessageEmbed ebM = EmbedMessageUtils.getRegister(message);
PrivateMessage.send(user,ebM,logger);
return pendingUserEntity.getId().toString();
}
/**
* Confirm user account
* @param pendingUserRepository Pending user DB interface
* @param id UserPendingEntity PK to cofirm
* @param checkToken received token
* @return PendingUserEntity
* @throws TokenNotMatch Given token not match
* @throws UserNotFoundException User not found in Pending user DB
*/
public PendingUserEntity confirmCheckToken(PendingUserRepository pendingUserRepository, int id, String checkToken ) throws TokenNotMatch, UserNotFoundException {
PendingUserEntity pendingUser = pendingUserRepository.findById(id);
if(pendingUser != null) {
if(pendingUser.getCheckToken().equals(checkToken)){
logger.info("Check Token match!");
}
else{
logger.warn("Check token not match!");
throw new TokenNotMatch();
}
}
else{
logger.warn("Id not Found!");
throw new UserNotFoundException();
}
return pendingUser;
}
/** /**
* Get user Entity * Get user Entity
* * @param userRepository User DB interface
* @param userRepository User DB interface
* @param passwordEncoder Password encoder * @param passwordEncoder Password encoder
* @param userInfoData Received data * @param userInfoData Received data
* @return User Entity * @return User Entity
* @throws UserNotFoundException User not found in User DB * @throws UserNotFoundException User not found in User DB
* @throws PasswordNotMatchException Given password not match * @throws PasswordNotMatchException Given password not match
*/ */
public UserEntity getUser(UserRepository userRepository, PasswordEncoder passwordEncoder, UserInfoData userInfoData) throws UserNotFoundException, PasswordNotMatchException { public UserEntity getUser(UserRepository userRepository, PasswordEncoder passwordEncoder, UserInfoData userInfoData) throws UserNotFoundException, PasswordNotMatchException {
List<UserEntity> users = userRepository.findByName(userInfoData.name); List<UserEntity> users = userRepository.findByName(userInfoData.name);
if (users.size() < 1) { if(users.size()<1){
logger.warn("Login with unknown username: " + userInfoData.name); logger.warn("Login with unknown username: " + userInfoData.name);
throw new UserNotFoundException(); throw new UserNotFoundException();
} else { }
else{
UserEntity user = users.get(0); UserEntity user = users.get(0);
if (passwordEncoder.matches(userInfoData.password, user.getPassword())) { if(passwordEncoder.matches(userInfoData.password,user.getPassword())){
logger.info("Login successful for " + user.getName()); logger.info("Login successful for " + user.getName());
return user; return user;
} else { }
else
{
logger.warn("Login fail for " + user.getName() + ", wrong password!"); logger.warn("Login fail for " + user.getName() + ", wrong password!");
throw new PasswordNotMatchException(); throw new PasswordNotMatchException();
} }
@ -68,40 +174,38 @@ public class UserUtils {
/** /**
* return token's UserEntity * return token's UserEntity
*
* @param userRepository User DB interface * @param userRepository User DB interface
* @param token Received token * @param token Received token
* @return User Entity * @return User Entity
* @throws UnknownTokenException Can't find token on User DB * @throws UnknownTokenException Can't find token on User DB
*/ */
public UserEntity getUserWithApiToken(UserRepository userRepository, String token) throws UnknownTokenException { public UserEntity getUserWithApiToken(UserRepository userRepository, String token) throws UnknownTokenException {
List<UserEntity> users = userRepository.findByApiToken(token); List<UserEntity> users = userRepository.findByApiToken(token);
if (users.size() > 0) { if(users.size() > 0){
return users.get(0); return users.get(0);
} else }
else
throw new UnknownTokenException(); throw new UnknownTokenException();
} }
/** /**
* Generate API Token * Generate API Token
*
* @return UUID String TODO Find something more secure * @return UUID String TODO Find something more secure
*/ */
public String generateApiToken() { public String generateApiToken(){
return UUID.randomUUID().toString(); return UUID.randomUUID().toString();
} }
/** /**
* Generate short check token * Generate short check token
*
* @return check token as string * @return check token as string
*/ */
public String generateCheckToken() { public String generateCheckToken(){
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
long longToken = Math.abs(random.nextLong()); long longToken = Math.abs( random.nextLong() );
String randomStr = Long.toString(longToken, 16); String randomStr = Long.toString( longToken, 16 );
randomStr = randomStr.substring(0, 4); randomStr = randomStr.substring(0,4);
randomStr = randomStr.toUpperCase(); randomStr = randomStr.toUpperCase();
return randomStr; return randomStr;
} }

View File

@ -0,0 +1,69 @@
package net.Broken.Tools;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import java.util.List;
/**
* Spam info for one user
*/
public class UserSpamUtils {
private AntiSpam.Minuteur minuteur;
private Member user;
private int multip = 0;
private boolean onSpam = false;
private List<Message> messages;
public int getTimeLeft(){
return minuteur.timeLeft;
}
public int getMultip()
{
return multip;
}
public UserSpamUtils(Member user, List<Message> messages) {
this.user = user;
this.messages = messages;
}
public void setMinuteur(AntiSpam.Minuteur minuteur) {
this.minuteur = minuteur;
}
public void launchMinuteur(){
minuteur.start();
}
public void setMultip(int multip) {
this.multip = multip;
}
public boolean isOnSpam() {
return onSpam;
}
public void setOnSpam(boolean onSpam) {
this.onSpam = onSpam;
}
public Member getUser() {
return user;
}
public void addMessage(Message message){
messages.add(message);
}
public List<Message> getMessages() {
return messages;
}
public void clearAndAdd(Message message){
messages.clear();
messages.add(message);
}
}

View File

@ -17,6 +17,7 @@ import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -26,7 +27,6 @@ import java.util.List;
public class AudioM { public class AudioM {
private static HashMap<Guild, AudioM> INSTANCES = new HashMap<>();
/** /**
* Music manager for this guild * Music manager for this guild
*/ */
@ -53,12 +53,7 @@ public class AudioM {
private Guild guild; private Guild guild;
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
private AudioM(Guild guild) { private static HashMap<Guild, AudioM> INSTANCES = new HashMap<>();
this.playerManager = new DefaultAudioPlayerManager();
AudioSourceManagers.registerRemoteSources(playerManager);
AudioSourceManagers.registerLocalSource(playerManager);
this.guild = guild;
}
public static AudioM getInstance(Guild guild) { public static AudioM getInstance(Guild guild) {
if (!INSTANCES.containsKey(guild)) { if (!INSTANCES.containsKey(guild)) {
@ -68,6 +63,14 @@ public class AudioM {
return INSTANCES.get(guild); return INSTANCES.get(guild);
} }
private AudioM(Guild guild) {
this.playerManager = new DefaultAudioPlayerManager();
AudioSourceManagers.registerRemoteSources(playerManager);
AudioSourceManagers.registerLocalSource(playerManager);
this.guild = guild;
}
/** /**
* Load audio track from url, connect to chanel if not connected * Load audio track from url, connect to chanel if not connected
* *
@ -104,7 +107,7 @@ public class AudioM {
public void noMatches() { public void noMatches() {
logger.warn("[" + guild + "] Cant find media!"); logger.warn("[" + guild + "] Cant find media!");
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Video not found !")).build(); Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Video not found !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue(); event.getHook().sendMessage(message).queue();
} }
@Override @Override
@ -112,7 +115,7 @@ public class AudioM {
logger.error("[" + guild + "] Can't load media!"); logger.error("[" + guild + "] Can't load media!");
logger.error(exception.getMessage()); logger.error(exception.getMessage());
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Playback error !")).build(); Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Playback error !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue(); event.getHook().sendMessage(message).queue();
} }
}); });
} }
@ -293,7 +296,7 @@ public class AudioM {
loadAndPlay(event, playedChanel, url, playListLimit, onHead); loadAndPlay(event, playedChanel, url, playListLimit, onHead);
} else { } else {
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Not connected to vocal chanel !")).build(); Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Not connected to vocal chanel !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue(); event.getHook().sendMessage(message).queue();
} }
} }

View File

@ -1,6 +1,7 @@
package net.Broken.audio; package net.Broken.audio;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import com.sedmelluq.discord.lavaplayer.track.playback.MutableAudioFrame; import com.sedmelluq.discord.lavaplayer.track.playback.MutableAudioFrame;
import net.dv8tion.jda.api.audio.AudioSendHandler; import net.dv8tion.jda.api.audio.AudioSendHandler;

View File

@ -21,7 +21,6 @@ public class GuildMusicManager {
/** /**
* Creates a player and a track scheduler. * Creates a player and a track scheduler.
*
* @param manager Audio player manager to use for creating the player. * @param manager Audio player manager to use for creating the player.
*/ */
public GuildMusicManager(AudioPlayerManager manager, Guild guild) { public GuildMusicManager(AudioPlayerManager manager, Guild guild) {

View File

@ -27,15 +27,24 @@ import java.util.List;
public class PlaylistManager { public class PlaylistManager {
private static PlaylistManager INSTANCE = new PlaylistManager();
private final ResponseEntity<PlaylistResponseData> TOKEN_ERROR = new ResponseEntity<>(new PlaylistResponseData("Unknown Token!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED); private final ResponseEntity<PlaylistResponseData> TOKEN_ERROR = new ResponseEntity<>(new PlaylistResponseData("Unknown Token!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED);
private final ResponseEntity<PlaylistResponseData> PLAYLIST_NOT_FOUND = new ResponseEntity<>(new PlaylistResponseData("Playlist not found", "playlist"), HttpStatus.NOT_FOUND); private final ResponseEntity<PlaylistResponseData> PLAYLIST_NOT_FOUND = new ResponseEntity<>(new PlaylistResponseData("Playlist not found", "playlist"), HttpStatus.NOT_FOUND);
private final ResponseEntity<PlaylistResponseData> TRACK_NOT_FOUND = new ResponseEntity<>(new PlaylistResponseData("Can't find media!", "track"), HttpStatus.NOT_FOUND); private final ResponseEntity<PlaylistResponseData> TRACK_NOT_FOUND = new ResponseEntity<>(new PlaylistResponseData("Can't find media!", "track"), HttpStatus.NOT_FOUND);
Logger logger = LogManager.getLogger();
private PlaylistRepository playlistRepository; private PlaylistRepository playlistRepository;
private TrackRepository trackRepository; private TrackRepository trackRepository;
private UserRepository userRepository; private UserRepository userRepository;
Logger logger = LogManager.getLogger();
private static PlaylistManager INSTANCE = new PlaylistManager();
private PlaylistManager() { private PlaylistManager() {
ApplicationContext context = SpringContext.getAppContext(); ApplicationContext context = SpringContext.getAppContext();
@ -57,52 +66,57 @@ public class PlaylistManager {
User jdaUser = MainBot.jda.getUserById(user.getJdaId()); User jdaUser = MainBot.jda.getUserById(user.getJdaId());
WebLoadUtils webLoadUtils = new WebLoadUtils(data, jdaUser, MainBot.jda.getGuilds().get(0), false); WebLoadUtils webLoadUtils = new WebLoadUtils(data, jdaUser, MainBot.jda.getGuilds().get(0) , false);
webLoadUtils.getResponse(); webLoadUtils.getResponse();
if (webLoadUtils.userAudioTrack == null) { if(webLoadUtils.userAudioTrack == null){
return TRACK_NOT_FOUND; return TRACK_NOT_FOUND;
} else { }
else
{
TrackEntity trackEntity = new TrackEntity(webLoadUtils.userAudioTrack.getAudioTrack().getInfo(), data.pos, playlist); TrackEntity trackEntity = new TrackEntity(webLoadUtils.userAudioTrack.getAudioTrack().getInfo(), data.pos, playlist);
playlist = insert(playlist, trackEntity); playlist = insert(playlist, trackEntity);
return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist), HttpStatus.OK); return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist),HttpStatus.OK);
} }
} catch (UnknownTokenException e) { } catch (UnknownTokenException e) {
logger.warn("Unknown token: " + token); logger.warn("Unknown token: "+ token);
return TOKEN_ERROR; return TOKEN_ERROR;
} catch (PlaylistNotFoundException e) { } catch (PlaylistNotFoundException e) {
logger.debug("Playlist not found: " + data.playlistId); logger.debug("Playlist not found: "+ data.playlistId);
return PLAYLIST_NOT_FOUND; return PLAYLIST_NOT_FOUND;
} }
} }
public ResponseEntity<PlaylistResponseData> removeTrack(String token, DeleteTrackData data) { public ResponseEntity<PlaylistResponseData> removeTrack(String token, DeleteTrackData data){
UserUtils userUtils = UserUtils.getInstance(); UserUtils userUtils = UserUtils.getInstance();
try { try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token); UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
PlaylistEntity playlist = getPlaylist(data.playlistId); PlaylistEntity playlist = getPlaylist(data.playlistId);
TrackEntity toDelete = trackRepository.findById(data.id); TrackEntity toDelete = trackRepository.findById(data.id);
playlist = remove(playlist, toDelete); playlist = remove(playlist, toDelete);
if (playlist == null) { if(playlist == null)
{
logger.warn("Playlist: " + data.playlistId + " Track: " + data.id); logger.warn("Playlist: " + data.playlistId + " Track: " + data.id);
return TRACK_NOT_FOUND; return TRACK_NOT_FOUND;
} }
return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist), HttpStatus.OK); return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist),HttpStatus.OK);
} catch (UnknownTokenException e) { } catch (UnknownTokenException e) {
logger.warn("Unknown token: " + token); logger.warn("Unknown token: "+ token);
return TOKEN_ERROR; return TOKEN_ERROR;
} catch (PlaylistNotFoundException e) { } catch (PlaylistNotFoundException e) {
logger.debug("Playlist not found: " + data.playlistId); logger.debug("Playlist not found: "+ data.playlistId);
return PLAYLIST_NOT_FOUND; return PLAYLIST_NOT_FOUND;
} }
} }
@ -114,13 +128,15 @@ public class PlaylistManager {
PlaylistEntity playlist = getPlaylist(data.playlistId); PlaylistEntity playlist = getPlaylist(data.playlistId);
TrackEntity toMove = trackRepository.findById(data.id); TrackEntity toMove = trackRepository.findById(data.id);
TrackEntity save = new TrackEntity(toMove); TrackEntity save = new TrackEntity(toMove);
playlist = remove(playlist, toMove); playlist = remove(playlist, toMove);
if (playlist == null) { if(playlist == null)
{
logger.warn("Playlist: " + data.playlistId + " Track: " + data.id); logger.warn("Playlist: " + data.playlistId + " Track: " + data.id);
return TRACK_NOT_FOUND; return TRACK_NOT_FOUND;
} }
@ -130,20 +146,21 @@ public class PlaylistManager {
playlist = insert(playlist, save); playlist = insert(playlist, save);
return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist), HttpStatus.OK);
return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist),HttpStatus.OK);
} catch (UnknownTokenException e) { } catch (UnknownTokenException e) {
logger.warn("Unknown token: " + token); logger.warn("Unknown token: "+ token);
return TOKEN_ERROR; return TOKEN_ERROR;
} catch (PlaylistNotFoundException e) { } catch (PlaylistNotFoundException e) {
logger.debug("Playlist not found: " + data.playlistId); logger.debug("Playlist not found: "+ data.playlistId);
return PLAYLIST_NOT_FOUND; return PLAYLIST_NOT_FOUND;
} }
} }
private PlaylistEntity getPlaylist(int id) throws PlaylistNotFoundException { private PlaylistEntity getPlaylist(int id) throws PlaylistNotFoundException{
PlaylistEntity playlist = playlistRepository.findById(id); PlaylistEntity playlist = playlistRepository.findById(id);
if (playlist == null) if(playlist == null)
throw new PlaylistNotFoundException(); throw new PlaylistNotFoundException();
else else
return playlist; return playlist;
@ -151,25 +168,26 @@ public class PlaylistManager {
} }
private PlaylistEntity insert(PlaylistEntity playlistEntity, TrackEntity trackEntity) { private PlaylistEntity insert(PlaylistEntity playlistEntity, TrackEntity trackEntity){
List<TrackEntity> tracks = trackRepository.findDistinctByPlaylistOrderByPos(playlistEntity); List<TrackEntity> tracks = trackRepository.findDistinctByPlaylistOrderByPos(playlistEntity);
boolean increase = false; boolean increase = false;
for (TrackEntity track : tracks) { for(TrackEntity track : tracks){
if (track.getPos().equals(trackEntity.getPos())) { if(track.getPos().equals(trackEntity.getPos())){
logger.debug("Need re-organisation"); logger.debug("Need re-organisation");
increase = true; increase = true;
} }
if (increase) { if(increase){
track.setPos(track.getPos() + 1); track.setPos(track.getPos() + 1);
trackRepository.save(track); trackRepository.save(track);
} }
} }
if (!increase) { if(!increase)
{
trackEntity.setPos(tracks.size()); trackEntity.setPos(tracks.size());
} }
@ -182,9 +200,9 @@ public class PlaylistManager {
} }
private PlaylistEntity remove(PlaylistEntity playlistEntity, TrackEntity trackEntity) { private PlaylistEntity remove(PlaylistEntity playlistEntity, TrackEntity trackEntity){
if (trackEntity == null) { if(trackEntity == null){
logger.warn("Track not found in DB!"); logger.warn("Track not found in DB!");
return null; return null;
} }
@ -192,14 +210,14 @@ public class PlaylistManager {
List<TrackEntity> tracks = trackRepository.findDistinctByPlaylistOrderByPos(playlistEntity); List<TrackEntity> tracks = trackRepository.findDistinctByPlaylistOrderByPos(playlistEntity);
int toDeleteIndex = tracks.indexOf(trackEntity); int toDeleteIndex = tracks.indexOf(trackEntity);
logger.debug("To delete index: " + toDeleteIndex); logger.debug("To delete index: " + toDeleteIndex);
if (toDeleteIndex == -1) { if(toDeleteIndex == -1){
logger.warn("Track not found in playlist"); logger.warn("Track not found in playlist");
return null; return null;
} }
for (int i = toDeleteIndex + 1; i < tracks.size(); i++) { for(int i = toDeleteIndex + 1; i< tracks.size(); i++){
tracks.get(i).setPos(tracks.get(i).getPos() - 1); tracks.get(i).setPos(tracks.get(i).getPos() - 1);
trackRepository.save(tracks.get(i)); trackRepository.save(tracks.get(i));
} }

View File

@ -205,12 +205,12 @@ public class TrackScheduler extends AudioEventAdapter {
} }
} }
public boolean isAutoFlow() {
return autoFlow;
}
public void setAutoFlow(boolean autoFlow) { public void setAutoFlow(boolean autoFlow) {
this.autoFlow = autoFlow; this.autoFlow = autoFlow;
needAutoPlay(); needAutoPlay();
} }
public boolean isAutoFlow() {
return autoFlow;
}
} }

View File

@ -6,7 +6,7 @@ import net.dv8tion.jda.api.entities.User;
/** /**
* Container that link AudioTrack to who submit it (User) * Container that link AudioTrack to who submit it (User)
*/ */
public class UserAudioTrack { public class UserAudioTrack{
private User user; private User user;
private AudioTrack audioTrack; private AudioTrack audioTrack;

Some files were not shown because too many files have changed in this diff Show More