use of tk.ardentbot.core.misc.logging.BotException in project Ardent by adamint.
the class CommandFactory method pass.
/**
* Handles generic message events, parses message content
* and creates a new AsyncCommandExecutor that will execute the command
*
* @param event the MessageReceivedEvent to be handled
*/
public void pass(MessageReceivedEvent event, String prefix) {
try {
Guild guild = event.getGuild();
User ardent = guild.getSelfMember().getUser();
User user = event.getAuthor();
if (user.isBot())
return;
Message message = event.getMessage();
MessageChannel channel = event.getChannel();
String[] args = message.getContent().split(" ");
String rawContent = message.getRawContent();
if (rawContent.startsWith(guild.getSelfMember().getUser().getAsMention())) {
rawContent = rawContent.replaceFirst(ardent.getAsMention(), "");
if (rawContent.length() == 0)
channel.sendMessage("Type @Ardent [msg] to talk to me or /help to see a list of commands").queue();
else {
if (!Ardent.disabledCommands.contains("cleverbot")) {
channel.sendMessage(Unirest.post("https://cleverbot.io/1.0/ask").field("user", Ardent.cleverbotUser).field("key", Ardent.cleverbotKey).field("nick", "ardent").field("text", rawContent).asJson().getBody().getObject().getString("response")).queue();
} else
channel.sendMessage("Cleverbot is currently disabled, sorry.").queue();
}
return;
}
if (!args[0].startsWith(prefix))
return;
String cmd = args[0].replaceFirst(prefix, "");
final boolean[] ranCommand = { false };
String pre = StringEscapeUtils.escapeJava(prefix);
if (args[0].startsWith(pre)) {
args[0] = args[0].replaceFirst(pre, "");
baseCommands.forEach(command -> {
if (command.getBotCommand().containsAlias(args[0])) {
command.botCommand.usages++;
if (!Ardent.disabledCommands.contains(command.getName())) {
EntityGuild entityGuild = EntityGuild.get(guild);
for (RestrictedUser u : entityGuild.getRestrictedUsers()) {
if (u.getUserId().equalsIgnoreCase(user.getId())) {
command.sendRestricted(user);
return;
}
}
GuildModel guildModel = BaseCommand.asPojo(r.table("guilds").get(guild.getId()).run(connection), GuildModel.class);
if (guildModel == null) {
guildModel = new GuildModel(guild.getId(), "english", "/");
r.table("guilds").insert(r.json(shard.gson.toJson(guildModel))).runNoReply(connection);
}
if (guildModel.role_permissions != null) {
for (RolePermission rolePermission : guildModel.role_permissions) {
Member member = guild.getMember(user);
Role r = guild.getRoleById(rolePermission.getId());
if (r != null && member.getRoles().contains(r) && !member.hasPermission(Permission.MANAGE_SERVER)) {
if (!rolePermission.getCanUseArdentCommands()) {
user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of " + "your roles, **" + r.getName() + "**, cannot send Ardent commands!").queue());
return;
}
if (!message.getRawContent().toLowerCase().contains("discord.gg") && !rolePermission.getCanSendDiscordInvites()) {
message.delete().queue();
user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of " + "your roles, **" + r.getName() + "**, cannot send Discord server invite " + "links!").queue());
return;
}
if (!rolePermission.getCanSendLinks()) {
if (message.getContent().toLowerCase().contains("http://") || message.getContent().toLowerCase().contains("https://")) {
message.delete().queue();
user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One" + " of " + "your roles, **" + r.getName() + "**, cannot send websiet links!").queue());
return;
}
}
}
}
}
new AsyncCommandExecutor(command.botCommand, guild, channel, event.getAuthor(), message, args, user).run();
commandsReceived++;
ranCommand[0] = true;
UserUtils.addMoney(user, 1);
} else {
command.sendTranslatedMessage("Sorry, this command is currently disabled and will be re-enabled soon.", channel, user);
ranCommand[0] = true;
}
}
});
}
if (!ranCommand[0]) {
if (!prefix.equalsIgnoreCase("/")) {
pass(event, "/");
}
}
} catch (Throwable ex) {
if (ex instanceof PermissionException) {
event.getAuthor().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("I don't have permission to " + "send a message in this channel, please tell a server administrator").queue());
} else {
new BotException(ex);
}
}
}
use of tk.ardentbot.core.misc.logging.BotException in project Ardent by adamint.
the class Ardent method main.
public static void main(String[] args) throws Exception {
new DefaultAudioPlayerManager();
Logger root1 = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root1.setLevel(Level.OFF);
for (String s : args) {
if (s.contains("premium"))
premiumBot = true;
}
if (!testingBot) {
spotifyApi = Api.builder().clientId("471f277107704e3b89d489284b65c6c6").clientSecret(IOUtils.toString(new FileInputStream(new File("/root/Ardent/spotifysecret.key")))).redirectURI("https://ardentbot.tk").build();
SpotifyTokenRefresh spotifyTokenRefresh = new SpotifyTokenRefresh();
spotifyTokenRefresh.run();
globalExecutorService.scheduleAtFixedRate(spotifyTokenRefresh, 10, 10, TimeUnit.MINUTES);
} else
spotifyApi = Api.DEFAULT_API;
if (!testingBot) {
dbPassword = IOUtils.toString(new FileReader(new File("/root/Ardent/v2password.key")));
botsDiscordPwToken = IOUtils.toString(new FileReader(new File("/root/Ardent/botsdiscordpw.key")));
discordBotsOrgToken = IOUtils.toString(new FileReader(new File("/root/Ardent/discordbotsorg.key")));
} else {
try {
dbPassword = IOUtils.toString(new FileReader(new File("C:\\Users\\AMR\\Desktop\\Ardent\\v2password.key")));
discordBotsOrgToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjE2OTkwNDMyNDk4MDI0NDQ4MCIsImlhdCI6MTQ5MzMyNDM1OX0.LQ97UtslzaM5Qo__gkihOX5afaZA5z3TjMjSovMzDTI";
} catch (Exception ex) {
dbPassword = IOUtils.toString(new FileReader(new File("/root/Ardent/.key")));
}
}
Database.setup();
Cursor<HashMap> apiKeys = r.db("data").table("api_keys").run(connection);
apiKeys.forEach((outside) -> {
outside.forEach((uId, uValue) -> {
String id = (String) uId;
String value = (String) uValue;
if (id.equalsIgnoreCase("mashape"))
mashapeKey = value;
else if (id.equalsIgnoreCase("google"))
GOOGLE_API_KEY = value;
else if (id.equalsIgnoreCase("node0"))
node0Url = value;
else if (id.equalsIgnoreCase("node1"))
node1Url = value;
else if (id.equalsIgnoreCase("cleverbotuser"))
cleverbotUser = value;
else if (id.equalsIgnoreCase("cleverbotkey"))
cleverbotKey = value;
else if (id.equalsIgnoreCase("premiumbottoken"))
premiumBotToken = value;
else if (id.equalsIgnoreCase("testbottoken"))
testBotToken = value;
else if (id.equalsIgnoreCase("googlesecret"))
clientSecret = value;
else if (id.equalsIgnoreCase("twitch"))
twitch = value;
});
});
ShardManager.register(shardCount);
BotlistUpdater updater = new BotlistUpdater();
globalExecutorService.scheduleAtFixedRate(updater, 0, 1, TimeUnit.HOURS);
StuckVoiceConnection playerStuckDaemon = new StuckVoiceConnection();
globalExecutorService.scheduleAtFixedRate(playerStuckDaemon, 10, 10, TimeUnit.SECONDS);
UpdatePremiumMembers updatePremiumMembers = new UpdatePremiumMembers();
globalExecutorService.scheduleAtFixedRate(updatePremiumMembers, 0, 1, TimeUnit.MINUTES);
ProfileUpdater profileUpdater = new ProfileUpdater();
globalExecutorService.scheduleWithFixedDelay(profileUpdater, 1, 5, TimeUnit.MINUTES);
if (!premiumBot) {
SparkServer.setup();
/*Class currentClass = new Object() {
}.getClass().getEnclosingClass();
premiumProcess = Runtime.getRuntime().exec("java -jar " + currentClass.getProtectionDomain().getCodeSource().getLocation()
.getPath() + " -premium");*/
} else {
CheckIfPremiumGuild checkIfPremiumGuild = new CheckIfPremiumGuild();
globalExecutorService.scheduleAtFixedRate(checkIfPremiumGuild, 1, 5, TimeUnit.MINUTES);
}
GoogleSearch.setup(GOOGLE_API_KEY);
int status = Unirest.post("https://cleverbot.io/1.0/create").field("user", cleverbotUser).field("key", cleverbotKey).field("nick", "ardent").asString().getStatus();
if (status != 200)
new BotException("Unable to connect to cleverbot!");
WebsiteDaemon websiteDaemon = new WebsiteDaemon();
globalExecutorService.scheduleAtFixedRate(websiteDaemon, 5, 15, TimeUnit.SECONDS);
PermissionsDaemon permissionsDaemon = new PermissionsDaemon();
globalExecutorService.scheduleAtFixedRate(permissionsDaemon, 0, 60, TimeUnit.SECONDS);
GuildDaemon guildDaemon = new GuildDaemon();
globalExecutorService.scheduleAtFixedRate(guildDaemon, 0, 10, TimeUnit.SECONDS);
MuteDaemon muteDaemon = new MuteDaemon();
globalExecutorService.scheduleAtFixedRate(muteDaemon, 1, 5, TimeUnit.SECONDS);
RankableDaemon rankableDaemon = new RankableDaemon();
globalExecutorService.scheduleAtFixedRate(rankableDaemon, 0, 1, TimeUnit.MINUTES);
Music.checkMusicConnections();
globalExecutorService.scheduleAtFixedRate(() -> {
Shard[] shards = ShardManager.getShards();
for (int i = 0; i < shards.length; i++) {
Shard shard = shards[i];
if ((System.currentTimeMillis() - shard.getLAST_EVENT()) > 20000) {
shard.jda.getRegisteredListeners().forEach(shard.jda::removeEventListener);
int finalI = i;
globalExecutorService.schedule(() -> {
shard.jda.shutdown(false);
try {
shards[finalI] = new Shard(testingBot, finalI, shardCount);
} catch (Exception e) {
new BotException(e);
}
}, 3, TimeUnit.SECONDS);
}
}
}, 60, 15, TimeUnit.SECONDS);
if (!testingBot) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey("Fi9IjqqsGmOXqjR5uYK8YM2Pr").setOAuthConsumerSecret(IOUtils.toString(new FileReader(new File("/root/Ardent/twitterconsumersecret.key")))).setOAuthAccessToken("818984879018954752-aCzxyML6Xp0QcRpq5sjoe8wfp0sjVDt").setOAuthAccessTokenSecret(IOUtils.toString(new FileReader(new File("/root/Ardent/twitteroauthsecret.key"))));
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
}
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF);
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.OFF);
try {
transport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
jsonFactory = JacksonFactory.getDefaultInstance();
sheetsApi = getSheetsService();
globalExecutorService.schedule(() -> {
try {
triviaSheet = sheetsApi.spreadsheets().values().get("1qm27kGVQ4BdYjvPSlF0zM64j7nkW4HXzALFNcan4fbs", "A2:C").execute();
} catch (IOException e) {
new BotException(e);
}
List<List<Object>> values = triviaSheet.getValues();
values.forEach(row -> {
String category = (String) row.get(0);
String q = (String) row.get(1);
String answerUnparsed = (String) row.get(2);
TriviaQuestion triviaQuestion = new TriviaQuestion();
triviaQuestion.setQuestion(q);
triviaQuestion.setCategory(category);
for (String answer : answerUnparsed.split("~")) {
triviaQuestion.withAnswer(answer);
}
Trivia.triviaQuestions.add(triviaQuestion);
});
}, 30, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
started = true;
}
use of tk.ardentbot.core.misc.logging.BotException in project Ardent by adamint.
the class TrackScheduler method onException.
private void onException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
manager.setCurrentlyPlaying(null);
manager.nextTrack();
try {
manager.getChannel().sendMessage("I wasn't able to play that track, skipping... **Reason: **" + exception.getLocalizedMessage()).queue();
} catch (Exception ex) {
new BotException(ex);
}
}
use of tk.ardentbot.core.misc.logging.BotException in project Ardent by adamint.
the class Music method checkMusicConnections.
public static void checkMusicConnections() {
for (Shard shard : ShardManager.getShards()) {
shard.executorService.scheduleAtFixedRate(() -> {
try {
for (Guild guild : shard.jda.getGuilds()) {
GuildMusicManager manager = getGuildAudioPlayer(guild, null, shard);
if (manager != null) {
GuildVoiceState voiceState = guild.getSelfMember().getVoiceState();
if (voiceState.inVoiceChannel()) {
TextChannel channel = manager.scheduler.manager.getChannel();
if (channel == null)
channel = guild.getPublicChannel();
if (channel != null) {
if (channel.canTalk()) {
VoiceChannel voiceChannel = voiceState.getChannel();
AudioPlayer player = manager.player;
if (voiceState.isGuildMuted()) {
shard.help.sendTranslatedMessage("Pausing player now because I'm muted", channel, null);
player.setPaused(true);
}
if (voiceChannel.getMembers().size() == 1 && !EntityGuild.get(guild).isPremium()) {
shard.help.sendTranslatedMessage("Left {0} because no one was in the channel!".replace("{0}", voiceChannel.getName()), channel, null);
guild.getAudioManager().closeAudioConnection();
}
}
}
}
}
}
} catch (Exception ex) {
new BotException(ex);
}
}, 5, 5, TimeUnit.MINUTES);
}
}
use of tk.ardentbot.core.misc.logging.BotException in project Ardent by adamint.
the class Roles method setupSubcommands.
@Override
public void setupSubcommands() throws Exception {
subcommands.add(new Subcommand("Adds the specified role to a user", "add @User [Role name]", "add") {
@Override
public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
if (args.length > 2) {
Member userMember = guild.getMember(user);
if (userMember.hasPermission(Permission.MANAGE_SERVER)) {
List<User> mentionedUsers = message.getMentionedUsers();
if (mentionedUsers.size() > 0) {
User mentioned = mentionedUsers.get(0);
Member mentionedMember = guild.getMember(mentioned);
if (!mentionedMember.hasPermission(userMember.getPermissions())) {
String[] split = message.getRawContent().split(" ");
StringBuilder role = new StringBuilder();
for (int i = 3; i < split.length; i++) {
role.append(split[i]);
if (i < (split.length - 1))
role.append(" ");
}
List<Role> roles = guild.getRolesByName(role.toString(), true);
if (roles.size() > 0) {
try {
Role r = roles.get(0);
guild.getController().addRolesToMember(mentionedMember, r).queue(aVoid -> {
try {
String reply = "Added **{0}** to {1}".replace("{0}", r.getName()).replace("{1}", mentioned.getAsMention());
sendTranslatedMessage(reply, channel, user);
} catch (Exception e) {
new BotException(e);
}
});
} catch (PermissionException ex) {
sendTranslatedMessage("I don't have permission to do this", channel, user);
}
} else
sendTranslatedMessage("No roles with that name were found", channel, user);
} else
sendTranslatedMessage("You cannot modify this user!", channel, user);
} else
sendTranslatedMessage("You need to mention a user", channel, user);
} else
sendTranslatedMessage("You need the Manage Roles permission", channel, user);
} else
sendTranslatedMessage("Please mention a user and type a role name", channel, user);
}
});
subcommands.add(new Subcommand("Removes the specified role from a user", "remove @user [Role name]", "remove") {
@Override
public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
if (args.length > 2) {
Member userMember = guild.getMember(user);
if (userMember.hasPermission(Permission.MANAGE_SERVER)) {
List<User> mentionedUsers = message.getMentionedUsers();
if (mentionedUsers.size() > 0) {
User mentioned = mentionedUsers.get(0);
Member mentionedMember = guild.getMember(mentioned);
if (!mentionedMember.hasPermission(userMember.getPermissions())) {
String[] split = message.getRawContent().split(" ");
StringBuilder role = new StringBuilder();
for (int i = 3; i < split.length; i++) {
role.append(split[i]);
if (i < (split.length - 1))
role.append(" ");
}
List<Role> roles = guild.getRolesByName(role.toString(), true);
if (roles.size() > 0) {
try {
Role r = roles.get(0);
guild.getController().removeRolesFromMember(mentionedMember, r).queue(aVoid -> {
try {
String reply = "Successfully removed role {0} from {1}".replace("{0}", r.getName()).replace("{1}", mentioned.getAsMention());
sendTranslatedMessage(reply, channel, user);
} catch (Exception e) {
new BotException(e);
}
});
} catch (PermissionException ex) {
sendTranslatedMessage("I don't have permission to do this", channel, user);
}
} else
sendTranslatedMessage("No roles with that name were found", channel, user);
} else
sendTranslatedMessage("You cannot modify this user!", channel, user);
} else
sendTranslatedMessage("You need to mention a user", channel, user);
} else
sendTranslatedMessage("You need the Manage Roles permission", channel, user);
} else
sendTranslatedMessage("Please mention a user and type a role name", channel, user);
}
});
}
Aggregations