public final Emote getEmote(int index, boolean consume) { if (guild == null) { return null; } final String temp = getRaw(index); if (temp == null) { return null; } final Matcher matcher = PATTERN_MARKDOWN_CUSTOM_EMOJI.matcher(temp); if (!matcher.matches()) { return null; } if (consume) { consumeRaw(index); } return guild.getEmoteById(matcher.group(1)); }
/** * verify that a supplied emoji string is a valid discord emoji * @param emoji emoji string (either raw emoji char or discord emoji ID) * @return true if valid */ public static boolean verifyEmoji(String emoji) { if(!EmojiManager.isEmoji(emoji)) { String emoteId = emoji.replaceAll("[^\\d]", ""); Emote emote = null; try { for(JDA jda : Main.getShardManager().getShards()) { emote = jda.getEmoteById(emoteId); if(emote != null) break; } } catch(Exception e) { return false; } if(emote == null) { return false; } } return true; }
/** * helper to addRSVPReactions(..) * @param emoji string emoticon, or emote ID * @param message message object to react to */ private static void addRSVPReaction(String emoji, Message message) { if(EmojiManager.isEmoji(emoji)) { message.addReaction(emoji).queue(); } else { Emote emote; for(JDA shard : Main.getShardManager().getShards()) { emote = shard.getEmoteById(emoji); if(emote != null) { message.addReaction(emote).queue(); break; } } } }
@Override protected void execute(String args, MessageReceivedEvent event) { String id = args.replaceAll("<:.+:(\\d+)>", "$1"); Emote emote = event.getJDA().getEmoteById(id); if(emote==null) tempReply("Invalid emote or emote ID", event); else { EmbedBuilder builder = new EmbedBuilder(); if(event.getGuild()!=null) builder.setColor(event.getGuild().getSelfMember().getColor()); builder.setImage(emote.getImageUrl()); builder.setDescription(emote.getAsMention()+" **:"+emote.getName()+":**\nID: **"+emote.getId()+"**\nGuild: **"+emote.getGuild().getName()+"**"); reply(builder.build(), event); } }
private void handleReplace(Emote oldEmote, Emote newEmote) { if (oldEmote == null || newEmote == null) return; if (!Objects.equals(oldEmote.getName(), newEmote.getName())) { api.getEventManager().handle( new EmoteUpdateNameEvent( api, responseNumber, newEmote, oldEmote.getName())); } if (!CollectionUtils.isEqualCollection(oldEmote.getRoles(), newEmote.getRoles())) { api.getEventManager().handle( new EmoteUpdateRolesEvent( api, responseNumber, newEmote, oldEmote.getRoles())); } }
public static final AdvancedEmote parse(Guild guild, String text) { final Matcher matcher = ArgumentList.PATTERN_MARKDOWN_CUSTOM_EMOJI.matcher(text); if (guild == null && !matcher.matches()) { return parse(text); } else if (guild != null) { Emote emote = guild.getEmoteById(text); if (emote == null) { emote = guild.getEmotesByName(text, false).stream().findFirst().orElse(null); } return new AdvancedEmote(emote != null ? emote.getName() : text, null, emote); } else { final String id = matcher.group(2); return new AdvancedEmote(matcher.group(1), null, Standard.getGuilds().stream().filter((advancedGuild) -> advancedGuild.getGuild() != null).map((advancedGuild) -> advancedGuild.getGuild().getEmoteById(id)).filter((emote) -> emote != null).findFirst().orElse(null)); } }
public final Emote getGuildReactionOnMention(Guild guild) { final String reaction_on_mention = getValue(guild.getIdLong(), 0, KEY_GUILD_REACTION_ON_MENTION, null); if (reaction_on_mention == null) { return null; } final Matcher matcher = ArgumentList.PATTERN_MARKDOWN_CUSTOM_EMOJI.matcher(reaction_on_mention); if (!matcher.matches()) { return null; } return guild.getEmoteById(matcher.group(2)); }
public final Emote getGuildReactionOnCommandNotFound(Guild guild) { final String reaction_on_command_not_found = getValue(guild.getIdLong(), 0, KEY_GUILD_REACTION_ON_COMMAND_NOT_FOUND, () -> Emoji.QUESTION_MARK); if (reaction_on_command_not_found == null) { return null; } final Matcher matcher = ArgumentList.PATTERN_MARKDOWN_CUSTOM_EMOJI.matcher(reaction_on_command_not_found); if (!matcher.matches()) { return null; } return guild.getEmoteById(matcher.group(2)); }
@Override protected void execute(CommandEvent event) { final List<Emote> currentEmotes = event.getGuild().getEmotes(); final Set<String> emoteNamesToInstall = new HashSet<>(Arrays.asList("mystic", "valor", "instinct")); boolean emotesAlreadyInstalled = false; for (Emote emote : currentEmotes) { final String emoteToInstall = emote.getName().toLowerCase(); if (emoteNamesToInstall.contains(emoteToInstall)) { event.reply(localeService.getMessageFor(LocaleService.EMOTE_INSTALLED_ALREADY, localeService.getLocaleForUser(event.getAuthor()), emoteToInstall)); emotesAlreadyInstalled = true; } } if (emotesAlreadyInstalled) { return; } final InputStream mysticPngResource = InstallEmotesCommand.class.getResourceAsStream("/static/img/mystic.png"); final InputStream valorPngResource = InstallEmotesCommand.class.getResourceAsStream("/static/img/valor.png"); final InputStream instinctPngResource = InstallEmotesCommand.class.getResourceAsStream("/static/img/instinct.png"); try { event.reply("Installing icons for Pokemon go teams..."); createEmote("mystic", event, Icon.from(mysticPngResource)); createEmote("valor", event, Icon.from(valorPngResource)); createEmote("instinct", event, Icon.from(instinctPngResource)); event.reply("Emotes installed. Try them out: :mystic: :valor: :instinct:"); } catch (Throwable t) { event.reply(t.getMessage()); } }
public final Emote consumeEmoteFirst() { return consumeEmote(0); }
public final Emote consumeEmoteLast() { return consumeEmote(size() - 1); }
public final Emote consumeEmote(int index) { return getEmote(index, true); }
public final Emote getEmoteFirst() { return getEmote(0); }
public final Emote getEmoteLast() { return getEmote(size() - 1); }
public final Emote getEmote(int index) { return getEmote(index, false); }
public AdvancedEmote(Emote emote) { this(emote.getName(), null, emote); }
public AdvancedEmote(String name, Emoji emoji, Emote emote) { this.name = name; this.emoji = emoji; this.emote = emote; }
public final Emote getEmote() { return emote; }
public static final Emote parseEmote(Guild guild, String emote_id) { return guild.getEmoteById(emote_id); }
private final void onMessage(final Object event_original, final MessageEvent event, boolean newMessage) { Updater.submit(() -> { try { final String content_raw = event.getMessage().getRawContent().trim(); final String content = event.getMessage().getContent().trim(); final Guild guild = event.getGuild(); final CommandType commandType = CommandType.getCommandType(content, content_raw, event); if (commandType.isCommand()) { CommandHandler.handleCommand(CommandParser.parser(commandType, content, content_raw, event)); } else if (content_raw.contains(Standard.getSelfUser().getAsMention()) || content_raw.contains(Standard.getSelfMemberByGuild(guild).getAsMention())) { final Emote reaction_emote = Config.CONFIG.getGuildReactionOnMention(guild); if (reaction_emote != null) { event.getMessage().addReaction(reaction_emote).queue(); } else { final Emoji reaction_emoji = Config.CONFIG.getGuildReactionOnMention(guild.getIdLong()); if (reaction_emoji != null) { event.getMessage().addReaction(reaction_emoji.getUnicode()).queue(); } } } final Object[] output = ListenerManager.fireListeners(MessageListener.class, CommandHandler.ADMIN_PREDICATE, new Object[]{newMessage ? event : event_original, newMessage ? MessageType.RECEIVED : MessageType.UPDATED}); String embed_messages = event.getMessage().getEmbeds().stream().map((messageEmbed) -> Util.embedMessageToString(messageEmbed)).collect(Collectors.joining(Standard.NEW_LINE_DISCORD)); if (!embed_messages.isEmpty()) { embed_messages = Standard.NEW_LINE_DISCORD + embed_messages; } final List<Attachment> attachments = event.getMessage().getAttachments(); if (attachments == null || attachments.isEmpty()) { System.out.println(String.format("[Used %d time%s] [%s] [%s] %s: %s%s", output.length, (output.length == 1 ? "" : "s"), (guild != null ? guild.getName() : "PRIVATE"), event.getMessageChannel().getName(), Standard.getCompleteName(event.getAuthor(), true), content, embed_messages)); } else { String text = ""; for (Attachment attachment : attachments) { text += Standard.NEW_LINE_DISCORD; if (attachment.isImage()) { text += String.format("IMAGE: \"%s\" (ID: %s) (PROXYURL: %s) (W: %d, H: %d)", attachment.getFileName(), attachment.getId(), attachment.getProxyUrl(), attachment.getWidth(), attachment.getHeight()); } else { text += String.format("FILE: \"%s\" (ID: %s) (URL: %s)", attachment.getFileName(), attachment.getId(), attachment.getUrl()); } } System.out.println(String.format("[Used %d time%s] [%s] [%s] %s: %s%s%s", output.length, (output.length == 1 ? "" : "s"), event.getGuild().getName(), event.getMessageChannel().getName(), Standard.getCompleteName(event.getAuthor(), true), content, text, embed_messages)); } } catch (Exception ex) { ex.printStackTrace(); } }); }
private void createEmote(String iconName, CommandEvent commandEvent, Icon icon, Role... roles) { JSONObject body = new JSONObject(); body.put("name", iconName); body.put("image", icon.getEncoding()); if (roles.length > 0) // making sure none of the provided roles are null before mapping them to the snowflake id { body.put("roles", Stream.of(roles).filter(Objects::nonNull).map(ISnowflake::getId).collect(Collectors.toSet())); } // todo: check bot permissions, must be able to handle emojis GuildImpl guild = (GuildImpl) commandEvent.getGuild(); JDA jda = commandEvent.getJDA(); Route.CompiledRoute route = Route.Emotes.CREATE_EMOTE.compile(guild.getId()); AuditableRestAction<Emote> action = new AuditableRestAction<Emote>(jda, route, body) { @Override protected void handleResponse(Response response, Request<Emote> request) { if (response.isOk()) { JSONObject obj = response.getObject(); final long id = obj.getLong("id"); String name = obj.getString("name"); EmoteImpl emote = new EmoteImpl(id, guild).setName(name); // managed is false by default, should always be false for emotes created by client accounts. JSONArray rolesArr = obj.getJSONArray("roles"); Set<Role> roleSet = emote.getRoleSet(); for (int i = 0; i < rolesArr.length(); i++) { roleSet.add(guild.getRoleById(rolesArr.getString(i))); } // put emote into cache guild.getEmoteMap().put(id, emote); request.onSuccess(emote); } else { request.onFailure(response); throw new RuntimeException("Couldn't install emojis. " + "Make sure that pokeraidbot has access to manage emojis."); } } }; action.queue(); }
@Override public void exec(String[] args, String rawArgs, MessageReceivedEvent e, GuildPreferences guildPreferences) { EmbedBuilder eb = new EmbedBuilder(); eb.setColor(Globals.EMBED_COLOR_PRIMARY); eb.setAuthor("Mac's Grimoire: An MTG Discord Bot", Grimoire.WEBSITE, e.getJDA().getSelfUser().getAvatarUrl()); eb.appendDescription("**Mac's Grimoire** is a Discord bot that brings many **Magic The Gathering** related tools straight into your discord server. "); eb.appendDescription("I can perform tasks like card-, price- or rule lookups, and more!"); if (e.getGuild() != null) eb.appendDescription("\n\n:large_blue_diamond: The current command prefix for guild **'" + e.getGuild().getName() + "'** is set to `" + guildPreferences.getPrefix() + "`."); eb.appendDescription("\n\n**Type any of the following options to get more info:**"); eb.addField("commands", "List all available commands", false); eb.addField("help <command>", "Get help with a specific command", false); eb.addField("inline references", "Explain inline references", false); StringBuilder sb = new StringBuilder(); sb.append("\n:white_check_mark: [Invite me!](" + Grimoire.WEBSITE + "/invite)"); sb.append("\n:earth_africa: [Website](" + Grimoire.WEBSITE + ")"); sb.append("\n:wrench: [Preference Dashboard](" + Grimoire.WEBSITE + "/dashboard)"); eb.addField("", sb.toString(), true); sb.delete(0, sb.length()); sb.append("\n:link: [Command Reference](" + Grimoire.WEBSITE + "/reference)"); sb.append("\n:speech_balloon: [Support Server](" + Grimoire.WEBSITE + "/support)"); sb.append("\n:heart: [Donate](https://paypal.me/BeMacized)"); eb.addField("", sb.toString(), true); sb.delete(0, sb.length()); Guild dbotsorgGuild = e.getJDA().getGuildById(264445053596991498L); Emote dbotsorgEmote = dbotsorgGuild == null ? null : dbotsorgGuild.getEmotesByName("discordbot", true).stream().findFirst().orElse(null); sb.append("\n:gear: [Source Code](https://github.com/BeMacized/Grimoire)"); sb.append("\n" + (dbotsorgEmote == null ? ":link:" : dbotsorgEmote.getAsMention()) + " [DiscordBots.org Page](https://discordbots.org/bot/239399098862665728)"); eb.addField("", sb.toString(), true); sb.delete(0, sb.length()); eb.addField(":globe_with_meridians: Server Count", "**" + e.getJDA().getGuilds().size() + "** Server" + (e.getJDA().getGuilds().size() > 1 ? "s" : ""), true); long users = e.getJDA().getGuilds().parallelStream().map(g -> g.getMembers().parallelStream()).flatMap(o -> o).map(m -> m.getUser().getId()).distinct().count(); eb.addField(":busts_in_silhouette: Total Users", "**" + users + "** User" + (users > 1 ? "s" : ""), true); eb.addField(":gear: Discord Library", "JDA", true); if (e.getGuild() != null) sendEmbed(e.getChannel(), "I've sent you help in a private message!"); try { e.getAuthor().openPrivateChannel().submit().get().sendMessage(eb.build()).submit(); } catch (InterruptedException | ExecutionException ex) { LOG.log(Level.SEVERE, "Could not send help", ex); } }
private void trigger(MessageCommandCaller caller, String message, String[] groups) throws RateLimitedException { DiscordConversation conversation = (DiscordConversation) caller.getConversation(); conversation.getChannel().sendMessage(message).queue((msg) -> { List<ImmutablePair<String, String>> entries = new ArrayList<>(); for (String group : groups) { String[] split = group.split("\\/"); String groupName = split[0].replace("#", "/"); String emoteName = split[1]; List<Emote> emotes = conversation.getChannel().getJDA().getEmotesByName(emoteName, true); if (emotes.size() == 0) { conversation.getChannel().sendMessage(mention(caller.getUser()) + " Impossible de trouver l'emote '" + emoteName + "'").queue(); msg.deleteMessage().queue(); return; } Group gr = null; for (Group g : this.groups) { if (g.getName().trim().equalsIgnoreCase(groupName.trim())) { gr = g; break; } } if (gr == null) { conversation.getChannel().sendMessage(mention(caller.getUser()) + " Impossible de trouver le groupe '" + groupName + "'").queue(); msg.deleteMessage().queue(); return; } Emote emote = emotes.get(0); msg.addReaction(emote).queue(); entries.add(new ImmutablePair<>(emote.getId(), gr.getName())); } shenron.getGroupListener().addTrigger(new GroupTrigger(msg.getId(), entries)); }); }
@Override protected Long handleInternally(JSONObject content) { JSONObject emoji = content.getJSONObject("emoji"); final long userId = content.getLong("user_id"); final long messageId = content.getLong("message_id"); final long channelId = content.getLong("channel_id"); final Long emojiId = emoji.isNull("id") ? null : emoji.getLong("id"); String emojiName = emoji.optString("name", null); final boolean emojiAnimated = emoji.optBoolean("animated"); if (emojiId == null && emojiName == null) { WebSocketClient.LOG.debug("Received a reaction {} with no name nor id. json: {}", JDALogger.getLazyString(() -> add ? "add" : "remove"), content); return null; } User user = api.getUserById(userId); if (user == null) user = api.getFakeUserMap().get(userId); if (user == null) { api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug("Received a reaction for a user that JDA does not currently have cached"); return null; } MessageChannel channel = api.getTextChannelById(channelId); if (channel == null) { channel = api.getPrivateChannelById(channelId); } if (channel == null) { channel = api.getFakePrivateChannelMap().get(channelId); } if (channel == null && api.getAccountType() == AccountType.CLIENT) { channel = api.asClient().getGroupById(channelId); } if (channel == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug("Received a reaction for a channel that JDA does not currently have cached"); return null; } MessageReaction.ReactionEmote rEmote; if (emojiId != null) { Emote emote = api.getEmoteById(emojiId); if (emote == null) { if (emojiName != null) { emote = new EmoteImpl(emojiId, api).setAnimated(emojiAnimated).setName(emojiName); } else { WebSocketClient.LOG.debug("Received a reaction {} with a null name. json: {}", JDALogger.getLazyString(() -> add ? "add" : "remove"), content); return null; } } rEmote = new MessageReaction.ReactionEmote(emote); } else { rEmote = new MessageReaction.ReactionEmote(emojiName, null, api); } MessageReaction reaction = new MessageReaction(channel, rEmote, messageId, user.equals(api.getSelfUser()), -1); if (add) onAdd(reaction, user); else onRemove(reaction, user); return null; }
public EmoteRemovedEvent(JDA api, long responseNumber, Emote emote) { super(api, responseNumber, emote); }
public GenericEmoteUpdateEvent(JDA api, long responseNumber, Emote emote) { super(api, responseNumber, emote); }
public EmoteUpdateRolesEvent(JDA api, long responseNumber, Emote emote, Collection<Role> oldRoles) { super(api, responseNumber, emote); this.oldRoles = Collections.unmodifiableList(new LinkedList<>(oldRoles)); }
public EmoteUpdateNameEvent(JDA api, long responseNumber, Emote emote, String oldName) { super(api, responseNumber, emote); this.oldName = oldName; }
public EmoteAddedEvent(JDA api, long responseNumber, Emote emote) { super(api, responseNumber, emote); }
public GenericEmoteEvent(JDA api, long responseNumber, Emote emote) { super(api, responseNumber); this.emote = emote; }
public Emote getEmote() { return emote; }
/** * Adds custom {@link net.dv8tion.jda.core.entities.Emote Emote}s as button choices. * * <p>Any regular unicode emojis should be added using {@link ButtonMenuBuilder#addChoices(String...)}. * * @param emotes * The Emote objects to add * * @return This builder */ public ButtonMenuBuilder addChoices(Emote... emotes) { Arrays.asList(emotes).stream().map(e -> e.getId()).forEach(e -> this.choices.add(e)); return this; }
/** * Sets the {@link net.dv8tion.jda.core.entities.Emote Emote}s as button choices. * * <p>Any regular unicode emojis should be set using {@link ButtonMenuBuilder#addChoices(String...)}. * * @param emotes * The Emote objects to set * * @return This builder */ public ButtonMenuBuilder setChoices(Emote... emotes) { this.choices.clear(); Arrays.asList(emotes).stream().map(e -> e.getId()).forEach(e -> this.choices.add(e)); return this; }
/** * The target {@link net.dv8tion.jda.core.entities.Emote Emote} * that will be modified by this Manager * * @return The target Emote */ public Emote getEmote() { return updatable.getEmote(); }
/** * The target {@link net.dv8tion.jda.core.entities.Emote Emote} * that will be modified by this Manager * * @return The target Emote */ public Emote getEmote() { return emote; }