use of sx.blah.discord.util.DiscordException in project Discord4J by Discord4J.
the class RoleBot method handle.
/**
* Client is ready to interact with Discord.
* @see ReadyBot
*/
@Override
public void handle(ReadyEvent event) {
try {
// Gets the first guild the bot is a member of. (NOTE: This is only for demonstration. Getting guilds in this way is NOT recommended. Use IDs or events instead.)
IGuild guild = event.getClient().getGuilds().get(0);
// Instantiate a RoleBuilder which will aide in the creation of the role.
RoleBuilder roleBuilder = new RoleBuilder(guild);
// Set the new role's name
roleBuilder.withName("Awesome Role");
// Set the new role's color
roleBuilder.withColor(Color.GREEN);
// Make the new role display separately from others in Discord.
roleBuilder.setHoist(true);
// Allow this role to be mentionable in chat.
roleBuilder.setMentionable(true);
// Assign the Administrator permission to this role.
roleBuilder.withPermissions(EnumSet.of(Permissions.ADMINISTRATOR));
// Add the role to the guild in Discord.
IRole role = roleBuilder.build();
// Gets the user of the bot
IUser ourUser = event.getClient().getOurUser();
// Assigns our new role to the bot. NOTE: This will make the bot's ONLY role our role.
guild.editUserRoles(ourUser, new IRole[] { role });
} catch (MissingPermissionsException | RateLimitException | DiscordException e) {
// Error occurred
e.printStackTrace();
}
}
use of sx.blah.discord.util.DiscordException in project Discord4J by Discord4J.
the class Discord4J method main.
/**
* Runs Discord4J using modules only.
*
* @param args The args should only include the bot token.
*/
public static void main(String[] args) {
// This functionality is dependent on these options being true
if (!Configuration.AUTOMATICALLY_ENABLE_MODULES || !Configuration.LOAD_EXTERNAL_MODULES)
throw new RuntimeException("Invalid configuration! Must have auto-enabling of modules + loading of external modules enabled.");
if (args.length == 0)
throw new RuntimeException("Invalid configuration! No arguments passed in.");
try {
ClientBuilder builder = new ClientBuilder();
IDiscordClient client = builder.withToken(args[0]).login();
client.getDispatcher().registerListener((IListener<ReadyEvent>) (ReadyEvent e) -> {
LOGGER.info(LogMarkers.MAIN, "Logged in as {}", e.getClient().getOurUser().getName());
});
// The modules should handle the rest
} catch (DiscordException e) {
LOGGER.error(LogMarkers.MAIN, "There was an error initializing the client", e);
}
}
use of sx.blah.discord.util.DiscordException in project Discord4J by Discord4J.
the class ClientBuilder method build.
/**
* Creates a {@link IDiscordClient} with the configuration specified by this builder.
*
* @return The new client with the configuration specified by this builder.
*/
public IDiscordClient build() {
if (botToken == null)
throw new DiscordException("No login info present!");
if (withRecommendedShardCount && shard != null)
throw new DiscordException("Cannot use recommend shard count options with a specific shard!");
if (withRecommendedShardCount) {
GatewayBotResponse response = Requests.GENERAL_REQUESTS.GET.makeRequest(DiscordEndpoints.GATEWAY + "/bot", GatewayBotResponse.class, new BasicNameValuePair("Authorization", "Bot " + botToken), new BasicNameValuePair("Content-Type", "application/json"));
shardCount = response.shards;
}
final IDiscordClient client = new DiscordClientImpl(botToken, shard != null ? -1 : shardCount, isDaemon, maxMissedPings, maxReconnectAttempts, retryCount, maxCacheCount, provider, shard, backpressureHandler, minimumPoolSize, maximumPoolSize, overflowCapacity, eventThreadTimeout, eventThreadTimeoutUnit, new PresenceUpdateRequest(status, activity, text, streamUrl));
// Registers events as soon as client is initialized
final EventDispatcher dispatcher = client.getDispatcher();
iListeners.forEach(dispatcher::registerListener);
listeners.forEach(dispatcher::registerListener);
listenerClasses.forEach(dispatcher::registerListener);
return client;
}
use of sx.blah.discord.util.DiscordException in project Ublisk by Derkades.
the class DiscordBot method onEnable.
@Override
public void onEnable() {
if (!DataFile.MYSQL.getConfig().getBoolean("discord.enabled")) {
super.log(this, LogLevel.WARNING, "Discord bot is not enabled in the config!");
return;
}
if (Var.DEBUG) {
super.log(this, LogLevel.WARNING, "Debug mode is enabled. Bot startup has been cancelled");
return;
}
String token = DataFile.MYSQL.getConfig().getString("discord.token");
try {
client = new ClientBuilder().withToken(token).login();
} catch (DiscordException e) {
super.log(this, LogLevel.SEVERE, "An error occured while trying to connect with Discord. Shutting down..");
e.printStackTrace();
this.terminate();
}
super.log(this, LogLevel.INFO, "Discord module has been initialized successfully!");
enabled = true;
}
use of sx.blah.discord.util.DiscordException in project Shadbot by Shadorc.
the class BotUtils method sendMessage.
public static RequestFuture<IMessage> sendMessage(MessageBuilder message, int retry) {
IGuild guild = message.getChannel().isPrivate() ? null : message.getChannel().getGuild();
long guildID = guild == null ? -1 : guild.getLongID();
if (retry == 0) {
LogUtils.infof("{Guild ID: %d} Abort attempt to send message (3 failed requests).", guildID);
return null;
}
if (!message.getChannel().getShard().isReady()) {
if (guild != null) {
LogUtils.infof("{Guild ID: %d} A message couldn't be sent because shard isn't ready, adding it to queue.", guildID);
ShardManager.getShadbotShard(guild.getShard()).queue(message);
}
return null;
}
return RequestBuffer.request(() -> {
try {
return message.send();
} catch (MissingPermissionsException err) {
BotUtils.sendMessage(TextUtils.missingPerm(err.getMissingPermissions()), message.getChannel());
LogUtils.infof("{Guild ID: %d} %s", guildID, err.getMessage());
} catch (DiscordException err) {
if (err.getMessage().contains("Message was unable to be sent (Discord didn't return a response)")) {
LogUtils.infof("{Guild ID: %d} A message could not be send because Discord didn't return a response, retrying.", guildID);
RequestFuture<IMessage> msgRequest = BotUtils.sendMessage(message, retry - 1);
if (msgRequest != null) {
return msgRequest.get();
}
} else if (err.getMessage().contains("Failed to make a 400 failed request after 5 tries!")) {
LogUtils.infof("{Guild ID: %d} %s", guildID, err.getMessage());
} else {
LogUtils.error(err, "An error occurred while sending message.");
}
}
return null;
});
}
Aggregations