Search in sources :

Example 16 with DiscordException

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();
    }
}
Also used : IRole(sx.blah.discord.handle.obj.IRole) RateLimitException(sx.blah.discord.util.RateLimitException) DiscordException(sx.blah.discord.util.DiscordException) IUser(sx.blah.discord.handle.obj.IUser) MissingPermissionsException(sx.blah.discord.util.MissingPermissionsException) IGuild(sx.blah.discord.handle.obj.IGuild) RoleBuilder(sx.blah.discord.util.RoleBuilder)

Example 17 with DiscordException

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);
    }
}
Also used : ReadyEvent(sx.blah.discord.handle.impl.events.ReadyEvent) DiscordException(sx.blah.discord.util.DiscordException) IDiscordClient(sx.blah.discord.api.IDiscordClient) ClientBuilder(sx.blah.discord.api.ClientBuilder)

Example 18 with DiscordException

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;
}
Also used : EventDispatcher(sx.blah.discord.api.events.EventDispatcher) PresenceUpdateRequest(sx.blah.discord.api.internal.json.requests.PresenceUpdateRequest) GatewayBotResponse(sx.blah.discord.api.internal.json.responses.GatewayBotResponse) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) DiscordException(sx.blah.discord.util.DiscordException) DiscordClientImpl(sx.blah.discord.api.internal.DiscordClientImpl)

Example 19 with DiscordException

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;
}
Also used : DiscordException(sx.blah.discord.util.DiscordException) ClientBuilder(sx.blah.discord.api.ClientBuilder)

Example 20 with DiscordException

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;
    });
}
Also used : RequestFuture(sx.blah.discord.util.RequestBuffer.RequestFuture) DiscordException(sx.blah.discord.util.DiscordException) MissingPermissionsException(sx.blah.discord.util.MissingPermissionsException) IGuild(sx.blah.discord.handle.obj.IGuild)

Aggregations

DiscordException (sx.blah.discord.util.DiscordException)20 ClientBuilder (sx.blah.discord.api.ClientBuilder)7 IChannel (sx.blah.discord.handle.obj.IChannel)4 MissingPermissionsException (sx.blah.discord.util.MissingPermissionsException)4 RateLimitException (sx.blah.discord.util.RateLimitException)4 Language (enums.Language)3 IDiscordClient (sx.blah.discord.api.IDiscordClient)3 IGuild (sx.blah.discord.handle.obj.IGuild)3 IMessage (sx.blah.discord.handle.obj.IMessage)3 IUser (sx.blah.discord.handle.obj.IUser)3 ProfileObject (com.github.vaerys.objects.ProfileObject)2 TrackLikes (com.github.vaerys.objects.TrackLikes)2 Matcher (java.util.regex.Matcher)2 EventDispatcher (sx.blah.discord.api.events.EventDispatcher)2 DiscordClientImpl (sx.blah.discord.api.internal.DiscordClientImpl)2 IReaction (sx.blah.discord.handle.obj.IReaction)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 CommandObject (com.github.vaerys.commands.CommandObject)1 ChannelSetting (com.github.vaerys.enums.ChannelSetting)1 UserSetting (com.github.vaerys.enums.UserSetting)1