discord4j.core.DiscordClient Java Examples

The following examples show how to use discord4j.core.DiscordClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GuildUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static List<WebGuild> getGuilds(JSONArray ids, String userId, DiscordClient client) {
	List<WebGuild> guilds = new ArrayList<>();

	for (int i = 0; i < ids.length(); i++) {
		Guild g = client.getGuildById(Snowflake.of(ids.getLong(i))).onErrorResume(e -> Mono.empty()).block();
		if (g != null) {
			Member m = g.getMemberById(Snowflake.of(userId)).block();

			WebGuild wg = new WebGuild().fromGuild(g);
			wg.setManageServer(PermissionChecker.hasManageServerRole(m));
			wg.setDiscalRole(PermissionChecker.hasSufficientRole(g, m));
			guilds.add(wg);
		}
	}
	return guilds;
}
 
Example #2
Source File: GuildUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static List<WebGuild> getGuilds(JSONArray ids, String userId, DiscordClient client) {
	List<WebGuild> guilds = new ArrayList<>();

	for (int i = 0; i < ids.length(); i++) {
		Guild g = client.getGuildById(Snowflake.of(ids.getLong(i))).onErrorResume(e -> Mono.empty()).block();
		if (g != null) {
			Member m = g.getMemberById(Snowflake.of(userId)).block();

			WebGuild wg = new WebGuild().fromGuild(g);
			wg.setManageServer(PermissionChecker.hasManageServerRole(m));
			wg.setDiscalRole(PermissionChecker.hasSufficientRole(g, m));
			guilds.add(wg);
		}
	}
	return guilds;
}
 
Example #3
Source File: DisCalClient.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates the DisCal bot client.
 *
 * @return The client if successful, otherwise <code>null</code>.
 */
private static DiscordClient createClient() {
	DiscordClientBuilder clientBuilder = new DiscordClientBuilder(BotSettings.TOKEN.get());
	//Handle shard count and index for multiple java instances
	clientBuilder.setShardIndex(Integer.valueOf(BotSettings.SHARD_INDEX.get()));
	clientBuilder.setShardCount(Integer.valueOf(BotSettings.SHARD_COUNT.get()));
	clientBuilder.setInitialPresence(Presence.online(Activity.playing("Booting Up!")));


	//Redis info + store service for caching
	if (BotSettings.USE_REDIS_STORES.get().equalsIgnoreCase("true")) {
		RedisURI uri = RedisURI.Builder
			.redis(BotSettings.REDIS_HOSTNAME.get(), Integer.valueOf(BotSettings.REDIS_PORT.get()))
			.withPassword(BotSettings.REDIS_PASSWORD.get())
			.build();

		RedisStoreService rss = new RedisStoreService(RedisClient.create(uri));

		MappingStoreService mss = MappingStoreService.create()
			.setMappings(rss, GuildBean.class, MessageBean.class)
			.setFallback(new JdkStoreService());

		clientBuilder.setStoreService(mss);
	} else {
		clientBuilder.setStoreService(new JdkStoreService());
	}

	return clientBuilder.build();
}
 
Example #4
Source File: ReadyListener.java    From KaellyBot with GNU General Public License v3.0 5 votes vote down vote up
public void onReady(DiscordClient client) {

        if (!isReadyOnce.containsKey(client)) {
            long time = System.currentTimeMillis();

            LOG.info("Ajout des différents listeners...");
            client.getEventDispatcher().on(GuildCreateEvent.class)
                    .subscribe(guildCreateEvent -> guildCreateListener.onReady(client, guildCreateEvent));
            client.getEventDispatcher().on(GuildDeleteEvent.class)
                    .subscribe(guildDeleteEvent -> guildLeaveListener.onReady(guildDeleteEvent));
            client.getEventDispatcher().on(GuildUpdateEvent.class)
                    .subscribe(guildUpdateEvent -> guildUpdateListener.onReady(guildUpdateEvent));
            client.getEventDispatcher().on(TextChannelDeleteEvent.class)
                    .subscribe(textChannelDeleteEvent -> channelDeleteListener.onReady(textChannelDeleteEvent));

            LOG.info("Présence mise à jour...");
            // Joue à...
            client.updatePresence(Presence.online(Activity.watching(Constants.discordInvite))).subscribe();

            LOG.info("Ecoute des flux RSS du site Dofus...");
            RSSFinder.start();

            LOG.info("Lancement du calendrier Almanax...");
            AlmanaxCalendar.start();

            LOG.info("Connexion à l'API Twitter...");
            TwitterFinder.start();

            LOG.info("Ecoute des messages...");
            client.getEventDispatcher().on(MessageCreateEvent.class)
                    .subscribe(event -> messageListener.onReady(event));

            isReadyOnce.put(client, true);
            LOG.info("Mise en place des ressources en " + (System.currentTimeMillis() - time) + "ms");

        }
    }
 
Example #5
Source File: StatCommand.java    From KaellyBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void request(Message message, Matcher m, Language lg) {
    if (m.group(1) == null || m.group(1).replaceAll("^\\s+", "").isEmpty()){
        long totalGuild = ClientConfig.DISCORD()
                .flatMap(DiscordClient::getGuilds).distinct()
                .count().blockOptional().orElse(0L);

        int totalUser = ClientConfig.DISCORD()
                .flatMap(DiscordClient::getGuilds).distinct()
                .map(Guild::getMemberCount)
                .map(count -> count.orElse(0))
                .collect(Collectors.summingInt(Integer::intValue))
                .blockOptional().orElse(0);

        String answer = Translator.getLabel(lg, "stat.request")
                .replace("{guilds.size}", String.valueOf(totalGuild))
                .replace("{users_max.size}", String.valueOf(totalUser));
        message.getChannel().flatMap(chan -> chan.createMessage(answer)).subscribe();
    }
    else if (m.group(1).matches("\\s+-g(\\s+\\d+)?")){
        int limit = GULD_LIMIT;
        if (m.group(2) != null) limit = Integer.parseInt(m.group(2).trim());
        StringBuilder st = new StringBuilder();
        List<discord4j.core.object.entity.Guild> guilds = getBiggestGuilds(limit);
        int ladder = 1;
        for(discord4j.core.object.entity.Guild guild : guilds)
            st.append(ladder++).append(" : **").append(guild.getName()).append("**, ")
                    .append(guild.getMemberCount().orElse(0)).append(" users\n");

        message.getChannel().flatMap(chan -> chan.createMessage(st.toString())).subscribe();
    }
    else if (m.group(1).matches("\\s+-hist"))
        message.getChannel().flatMap(chan -> chan.createMessage(spec ->
                decorateImageMessage(spec, getJoinTimeGuildsGraph())))
        .subscribe();
}
 
Example #6
Source File: StatCommand.java    From KaellyBot with GNU General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param limit nombre de guildes à afficher
 * @return Liste des limit plus grandes guildes qui utilisent kaelly
 */
private List<discord4j.core.object.entity.Guild> getBiggestGuilds(int limit){
    return ClientConfig.DISCORD().flatMap(DiscordClient::getGuilds).distinct()
            .sort((guild1, guild2) -> guild2.getMemberCount().orElse(0) - guild1.getMemberCount().orElse(0))
            .take(limit)
            .collectList().block();
}
 
Example #7
Source File: ClientConfig.java    From KaellyBot with GNU General Public License v3.0 4 votes vote down vote up
public static Flux<DiscordClient> DISCORD() {
    return getInstance().DISCORD;
}
 
Example #8
Source File: EveryoneRoleLiveTest.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
@BeforeAll
public void setup() {
    String token = System.getenv("token");
    client = DiscordClient.create(token).login().block();
}
 
Example #9
Source File: GatewayBootstrap.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
GatewayBootstrap(DiscordClient client, Function<GatewayOptions, O> optionsModifier) {
    this.client = client;
    this.optionsModifier = optionsModifier;
}
 
Example #10
Source File: GuildCreateListener.java    From KaellyBot with GNU General Public License v3.0 4 votes vote down vote up
public void onReady(DiscordClient client, GuildCreateEvent event) {
    try {
        if (!Guild.getGuilds().containsKey(event.getGuild().getId().asString())) {

            event.getGuild().getChannels()
                    .filter(chan -> chan instanceof TextChannel)
                    .map(chan -> (TextChannel) chan).take(1).flatMap(chan -> {
                Guild guild = new Guild(event.getGuild().getId().asString(), event.getGuild().getName(),
                        Translator.detectLanguage(chan));
                guild.addToDatabase();

                Language lg = guild.getLanguage();
                LOG.info("La guilde " + guild.getId() + " - " + guild.getName() + " a ajouté " + Constants.name);

                return event.getGuild().getOwner().flatMap(owner -> {
                    String customMessage = Translator.getLabel(lg, "welcome.message")
                            .replaceAll("\\{name}", Constants.name)
                            .replaceAll("\\{game}", Constants.game.getName())
                            .replaceAll("\\{prefix}", Constants.prefixCommand)
                            .replaceAll("\\{help}", HelpCommand.NAME)
                            .replaceAll("\\{server}", new ServerCommand().getName())
                            .replaceAll("\\{lang}", new LanguageCommand().getName())
                            .replaceAll("\\{twitter}", new TwitterCommand().getName())
                            .replaceAll("\\{almanax-auto}", new AlmanaxAutoCommand().getName())
                            .replaceAll("\\{rss}", new RSSCommand().getName())
                            .replaceAll("\\{owner}", owner.getMention())
                            .replaceAll("\\{guild}", event.getGuild().getName());

                    return chan.getEffectivePermissions(client.getSelfId().orElse(null))
                            .flatMap(perm -> perm.contains(Permission.SEND_MESSAGES) ?
                                    chan.createMessage(customMessage) : event.getGuild().getOwner()
                                    .flatMap(Member::getPrivateChannel)
                                    .flatMap(ownerChan -> ownerChan.createMessage(customMessage)))
                            .thenMany(ClientConfig.DISCORD()
                                    .flatMap(cli -> cli.getChannelById(Snowflake.of(Constants.chanReportID)))
                                    .filter(channel -> channel instanceof TextChannel)
                                    .map(channel -> (TextChannel) channel)
                                    .distinct()
                                    .flatMap(channel -> channel.createMessage("[NEW] **" + event.getGuild().getName()
                                            + "** (" + guild.getLanguage().getAbrev() + "), +"
                                            + event.getGuild().getMemberCount().orElse(0) +  " utilisateurs")))
                            .collectList();
                });
            }).subscribe();
        }
    } catch(Exception e){
        Reporter.report(e, event.getGuild());
        LOG.error("onReady", e);
    }
}
 
Example #11
Source File: ClientConfig.java    From KaellyBot with GNU General Public License v3.0 4 votes vote down vote up
private static Flux<DiscordClient> DISCORD(String path) {
    return getInstance(path).DISCORD;
}
 
Example #12
Source File: ClientConfig.java    From KaellyBot with GNU General Public License v3.0 4 votes vote down vote up
public static void loginDiscord(String path) {
    DISCORD(path).flatMap(DiscordClient::login).blockLast();
}
 
Example #13
Source File: ClientConfig.java    From KaellyBot with GNU General Public License v3.0 4 votes vote down vote up
public static void loginDiscord(){
    DISCORD().flatMap(DiscordClient::login).blockLast();
}
 
Example #14
Source File: DisCalClient.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Creates the DisCal bot client.
 *
 * @return The client if successful, otherwise <code>null</code>.
 */
private static DiscordClient createClient() {
	DiscordClientBuilder clientBuilder = new DiscordClientBuilder(BotSettings.TOKEN.get());
	//Handle shard count and index for multiple java instances
	clientBuilder.setShardIndex(Integer.valueOf(BotSettings.SHARD_INDEX.get()));
	clientBuilder.setShardCount(Integer.valueOf(BotSettings.SHARD_COUNT.get()));
	clientBuilder.setInitialPresence(Presence.online(Activity.playing("Booting Up!")));


	//Redis info + store service for caching
	if (BotSettings.USE_REDIS_STORES.get().equalsIgnoreCase("true")) {
		RedisURI uri = RedisURI.Builder
			.redis(BotSettings.REDIS_HOSTNAME.get(), Integer.valueOf(BotSettings.REDIS_PORT.get()))
			.withPassword(BotSettings.REDIS_PASSWORD.get())
			.build();

		RedisStoreService rss = new RedisStoreService(RedisClient.create(uri));

		MappingStoreService mss = MappingStoreService.create()
			.setMappings(rss, GuildBean.class, MessageBean.class)
			.setFallback(new JdkStoreService());

		clientBuilder.setStoreService(mss);
	} else {
		clientBuilder.setStoreService(new JdkStoreService());
	}

	return clientBuilder.build();
}
 
Example #15
Source File: DisCalClient.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static DiscordClient getClient() {
	return client;
}
 
Example #16
Source File: Main.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  DiscordClient client = new DiscordClientBuilder(System.getProperty("botToken")).build();
  new Main().registerListeners(client.getEventDispatcher());
  client.login().block();
}
 
Example #17
Source File: DisCalClient.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static DiscordClient getClient() {
	return client;
}
 
Example #18
Source File: GatewayBootstrap.java    From Discord4J with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Create a default {@link GatewayBootstrap} based off the given {@link DiscordClient} that provides an instance
 * of {@link CoreResources} used to provide defaults while building a {@link GatewayDiscordClient}.
 *
 * @param client the {@link DiscordClient} used to set up configuration
 * @return a default builder to create {@link GatewayDiscordClient}
 */
public static GatewayBootstrap<GatewayOptions> create(DiscordClient client) {
    return new GatewayBootstrap<>(client, Function.identity());
}