net.dv8tion.jda.api.events.GenericEvent Java Examples

The following examples show how to use net.dv8tion.jda.api.events.GenericEvent. 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: GuildListener.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void onEvent(@Nonnull GenericEvent event) {
    if (event instanceof GuildJoinEvent) {
        this.onGuildJoin((GuildJoinEvent) event);
    } else if (event instanceof GuildLeaveEvent) {
        this.onGuildLeave((GuildLeaveEvent) event);
    } else if (event instanceof GuildVoiceLeaveEvent) {
        this.onGuildVoiceLeave((GuildVoiceLeaveEvent) event);
    } else if (event instanceof GuildVoiceJoinEvent) {
        this.onGuildVoiceJoin((GuildVoiceJoinEvent) event);
    } else if (event instanceof GuildVoiceMoveEvent) {
        this.onGuildVoiceMove((GuildVoiceMoveEvent) event);
    } else if (event instanceof GuildBanEvent) {
        this.onGuildBan((GuildBanEvent) event);
    } else if (event instanceof GuildUnbanEvent) {
        this.onGuildUnban((GuildUnbanEvent) event);
    }
}
 
Example #2
Source File: SourceResolverServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Guild getGuild(GenericEvent event) {
    if (event == null) {
        return null;
    }
    Class<? extends GenericEvent> clazz = event.getClass();
    Method method;
    if (!guildAccessors.containsKey(clazz)) {
        method = ReflectionUtils.findMethod(clazz, "getGuild");
        guildAccessors.put(clazz, method);
    } else {
        method = guildAccessors.get(clazz);
    }
    if (method != null) {
        try {
            Object result = ReflectionUtils.invokeMethod(method, event);
            if (result instanceof Guild) {
                return (Guild) result;
            }
        } catch (Exception e) {
            // we don't care
        }
    }
    return null;
}
 
Example #3
Source File: InterfacedEventManager.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(@Nonnull GenericEvent event)
{
    for (EventListener listener : listeners)
    {
        try
        {
            listener.onEvent(event);
        }
        catch (Throwable throwable)
        {
            JDAImpl.LOG.error("One of the EventListeners had an uncaught exception", throwable);
            if (throwable instanceof Error)
                throw (Error) throwable;
        }
    }
}
 
Example #4
Source File: ContextEventManagerImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
private void loopListeners(GenericEvent event) {
    if (event instanceof GuildMessageReceivedEvent) {
        dispatchChain(GuildMessageReceivedEvent.class, (GuildMessageReceivedEvent) event);
    }
    for (EventListener listener : listeners) {
        try {
            listener.onEvent(event);
        } catch (ObjectOptimisticLockingFailureException e) {
            log.warn("[{}] optimistic lock happened for {}#{} while handling {}",
                    listener.getClass().getSimpleName(),
                    e.getPersistentClassName(),
                    e.getIdentifier(),
                    event);
        } catch (Throwable throwable) {
            log.error("[{}] had an uncaught exception for handling {}",
                    listener.getClass().getSimpleName(),
                    event,
                    throwable);
        }
    }
}
 
Example #5
Source File: ContextEventManagerImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private void handleEvent(GenericEvent event) {
    try {
        contextService.initContext(event);
        loopListeners(event);
    } catch (Exception e) {
        log.error("Event manager caused an uncaught exception", e);
    } finally {
        contextService.resetContext();
    }
}
 
Example #6
Source File: CommandListener.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(@NotNull GenericEvent event) {
    if (event instanceof GuildMessageReceivedEvent) {
        GuildMessageReceivedEvent msg = (GuildMessageReceivedEvent) event;
        //Inserts a cached message into the cache. This only holds the id and the content, and is way lighter than saving the entire jda object.
        messageCache.put(msg.getMessage().getIdLong(), Optional.of(new CachedMessage(msg.getAuthor().getIdLong(), msg.getMessage().getContentDisplay())));

        //Ignore myself and bots.
        if (msg.getAuthor().isBot() || msg.isWebhookMessage() || msg.getAuthor().equals(msg.getJDA().getSelfUser()))
            return;

        threadPool.execute(() -> onCommand(msg));
    }
}
 
Example #7
Source File: InteractiveOperations.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(@Nonnull GenericEvent e) {
    if (!(e instanceof GuildMessageReceivedEvent))
        return;

    GuildMessageReceivedEvent event = (GuildMessageReceivedEvent) e;

    //Don't listen to ourselves...
    if (event.getAuthor().equals(event.getJDA().getSelfUser()))
        return;

    long channelId = event.getChannel().getIdLong();
    List<RunningOperation> l = OPS.get(channelId);

    if (l == null || l.isEmpty())
        return;

    l.removeIf(o -> {
        try {
            int i = o.operation.run(event);
            if (i == Operation.COMPLETED) {
                o.future.complete(null);
                return true;
            }
            if (i == Operation.RESET_TIMEOUT) {
                o.resetTimeout();
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    });
}
 
Example #8
Source File: MantaroCore.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(@Nonnull GenericEvent event) {
    if (event instanceof ReadyEvent) {
        var sm = event.getJDA().getShardManager();
        if (sm == null)
            throw new AssertionError();

        latch.countDown();
    }
}
 
Example #9
Source File: VoiceChannelListener.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(@NotNull GenericEvent event) {
    if (event instanceof GuildVoiceMoveEvent) {
        onGuildVoiceMove((GuildVoiceMoveEvent) event);
    } else if (event instanceof GuildVoiceJoinEvent) {
        onGuildVoiceJoin((GuildVoiceJoinEvent) event);
    } else if (event instanceof GuildVoiceLeaveEvent) {
        onGuildVoiceLeave((GuildVoiceLeaveEvent) event);
    } else if (event instanceof GuildVoiceMuteEvent) {
        onGuildVoiceMute((GuildVoiceMuteEvent) event);
    }
}
 
Example #10
Source File: AnnotatedEventManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void handle(@Nonnull GenericEvent event)
{
    Class<?> eventClass = event.getClass();
    do
    {
        Map<Object, List<Method>> listeners = methods.get(eventClass);
        if (listeners != null)
        {
            listeners.forEach((key, value) -> value.forEach(method ->
            {
                try
                {
                    method.setAccessible(true);
                    method.invoke(key, event);
                }
                catch (IllegalAccessException | InvocationTargetException e1)
                {
                    JDAImpl.LOG.error("Couldn't access annotated EventListener method", e1);
                }
                catch (Throwable throwable)
                {
                    JDAImpl.LOG.error("One of the EventListeners had an uncaught exception", throwable);
                    if (throwable instanceof Error)
                        throw (Error) throwable;
                }
            }));
        }
        eventClass = eventClass == Event.class ? null : (Class<? extends GenericEvent>) eventClass.getSuperclass();
    }
    while (eventClass != null);
}
 
Example #11
Source File: AnnotatedEventManager.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void updateMethods()
{
    methods.clear();
    for (Object listener : listeners)
    {
        boolean isClass = listener instanceof Class;
        Class<?> c = isClass ? (Class) listener : listener.getClass();
        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods)
        {
            if (!m.isAnnotationPresent(SubscribeEvent.class) || (isClass && !Modifier.isStatic(m.getModifiers())))
            {
                continue;
            }
            Class<?>[] pType  = m.getParameterTypes();
            if (pType.length == 1 && GenericEvent.class.isAssignableFrom(pType[0]))
            {
                Class<?> eventClass = pType[0];
                if (!methods.containsKey(eventClass))
                {
                    methods.put(eventClass, new ConcurrentHashMap<>());
                }

                if (!methods.get(eventClass).containsKey(listener))
                {
                    methods.get(eventClass).put(listener, new CopyOnWriteArrayList<>());
                }

                methods.get(eventClass).get(listener).add(m);
            }
        }
    }
}
 
Example #12
Source File: EventManagerProxy.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(@Nonnull GenericEvent event)
{
    try
    {
        if (executor != null && !executor.isShutdown())
            executor.execute(() -> handleInternally(event));
        else
            handleInternally(event);
    }
    catch (Exception ex)
    {
        JDAImpl.LOG.error("Encountered exception trying to schedule event", ex);
    }
}
 
Example #13
Source File: ContextEventManagerImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(GenericEvent event) {
    if (workerProperties.getEvents().isAsyncExecution()) {
        try {
            getTaskExecutor(event.getJDA()).execute(() -> handleEvent(event));
        } catch (TaskRejectedException e) {
            log.debug("Event rejected: {}", event);
        }
    } else {
        handleEvent(event);
    }
}
 
Example #14
Source File: ContextServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void initContext(GenericEvent event) {
    Guild guild = null;
    User user = null;

    if (event instanceof GenericGuildMemberEvent) {
        GenericGuildMemberEvent memberEvent = (GenericGuildMemberEvent) event;
        guild = memberEvent.getMember().getGuild();
        user = memberEvent.getMember().getUser();
    }

    if (guild == null && event instanceof GenericGuildEvent) {
        guild = ((GenericGuildEvent) event).getGuild();
    }

    if (guild == null || user == null) {
        Member member = resolverService.getMember(event);
        if (member != null) {
            guild = member.getGuild();
            user = member.getUser();
        }
    }
    if (guild == null) {
        guild = resolverService.getGuild(event);
    }
    if (user == null) {
        user = resolverService.getUser(event);
    }
    if (guild != null) {
        initContext(guild);
    }
    if (user != null) {
        initContext(user);
    }
}
 
Example #15
Source File: SourceResolverServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private Object getAuthor(GenericEvent event) {
    if (event == null) {
        return null;
    }
    Class<? extends GenericEvent> clazz = event.getClass();
    Method method;
    if (!userAccessors.containsKey(clazz)) {
        method = ReflectionUtils.findMethod(clazz, "getUser");
        if (method == null) {
            method = ReflectionUtils.findMethod(clazz, "getAuthor");
        }
        userAccessors.put(clazz, method);
    } else {
        method = userAccessors.get(clazz);
    }
    if (method != null) {
        try {
            Object result = ReflectionUtils.invokeMethod(method, event);
            if (result instanceof User) {
                return result;
            }
        } catch (Exception e) {
            // we don't care
        }
    }
    return null;
}
 
Example #16
Source File: EventManagerProxy.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void handleInternally(@Nonnull GenericEvent event)
{
    // don't allow mere exceptions to obstruct the socket handler
    try
    {
        subject.handle(event);
    }
    catch (RuntimeException e)
    {
        JDAImpl.LOG.error("The EventManager.handle() call had an uncaught exception", e);
    }
}
 
Example #17
Source File: IrcConnection.java    From Yui with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(GenericEvent event)
{
    Message msg;
    if (event instanceof GuildMessageReceivedEvent)
    {
        msg = ((GuildMessageReceivedEvent) event).getMessage();
    }
    else if (event instanceof GuildMessageUpdateEvent)
    {
        msg = ((GuildMessageUpdateEvent) event).getMessage();
    }
    else
    {
        return;
    }

    //Basically: If we are the ones that sent the message, don't send it to IRC.
    if (event.getJDA().getSelfUser().equals(msg.getAuthor()))
        return;

    //If this returns null, then this EndPoint isn't part of a bridge.
    EndPoint endPoint = BridgeManager.getInstance().getOtherEndPoint(EndPointInfo.createFromDiscordChannel(msg.getTextChannel()));
    if (endPoint != null)
    {
        EndPointMessage message = EndPointMessage.createFromDiscordEvent(msg);
        endPoint.sendMessage(message);
    }
}
 
Example #18
Source File: ReadyShutdownListener.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(@Nonnull GenericEvent event) {
    if (event instanceof ReadyEvent) {
        this.onReady((ReadyEvent) event);
    } else if (event instanceof GuildMessageUpdateEvent) {
        this.onGuildMessageUpdate((GuildMessageUpdateEvent) event);
    } else if (event instanceof GuildMessageReceivedEvent) {
        this.onGuildMessageReceived((GuildMessageReceivedEvent) event);
    }
}
 
Example #19
Source File: GuildMemberListener.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(@Nonnull GenericEvent event) {
    if (event instanceof GuildMemberJoinEvent) {
        this.onGuildMemberJoin((GuildMemberJoinEvent) event);
    } else if (event instanceof GuildMemberRemoveEvent) {
        this.onGuildMemberRemove((GuildMemberRemoveEvent) event);
    } else if (event instanceof GuildMemberRoleRemoveEvent) {
        this.onGuildMemberRoleRemove((GuildMemberRoleRemoveEvent) event);
    } else if (event instanceof GuildMemberRoleAddEvent) {
        this.onGuildMemberRoleAdd((GuildMemberRoleAddEvent) event);
    }
}
 
Example #20
Source File: EventManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handle(@Nonnull GenericEvent event) {
    final JDA.ShardInfo shardInfo = event.getJDA().getShardInfo();

    if (shouldFakeBlock) {
        //noinspection ConstantConditions
        if (shardInfo == null) {
            logger.warn(TextColor.RED + "Shard booting up (Event {})." + TextColor.RESET, event.getClass().getSimpleName());
            return;
        }

        if (restartingShard == -1 || restartingShard == shardInfo.getShardId()) {
            return;
        }
    }

    for (final EventListener listener : this.listeners) {
        try {
            listener.onEvent(event);
        }
        catch (Throwable thr) {
            Sentry.capture(thr);

            logger.error("Error while handling event {}({}); {}",
                event.getClass().getName(),
                listener.getClass().getSimpleName(),
                thr.getLocalizedMessage());
            logger.error("", thr);
        }
    }
}
 
Example #21
Source File: ShardWatcher.java    From SkyBot with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void onEvent(@Nonnull GenericEvent event) {
    if (event instanceof GatewayPingEvent) {
        this.onGatewayPing((GatewayPingEvent) event);
    }
}
 
Example #22
Source File: JDAImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
public void handleEvent(@Nonnull GenericEvent event)
{
    eventManager.handle(event);
}
 
Example #23
Source File: MantaroEventManager.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void handle(@NotNull GenericEvent event) {
    lastJdaEvent = System.currentTimeMillis();
    super.handle(event);
}
 
Example #24
Source File: SourceResolverServiceImpl.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Member getMember(GenericEvent event) {
    Object author = getAuthor(event);
    return author instanceof Member ? (Member) author : null;
}
 
Example #25
Source File: SourceResolverServiceImpl.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public User getUser(GenericEvent event) {
    Object author = getAuthor(event);
    return author instanceof User ? (User) author : null;
}
 
Example #26
Source File: IEventManager.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Handles the provided {@link net.dv8tion.jda.api.events.GenericEvent GenericEvent}.
 * <br>How this is handled is specified by the implementation.
 *
 * <p>An implementation should not throw exceptions.
 *
 * @param event
 *        The event to handle
 */
void handle(@Nonnull GenericEvent event);
 
Example #27
Source File: EventListener.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Handles any {@link net.dv8tion.jda.api.events.GenericEvent GenericEvent}.
 *
 * <p>To get specific events with Methods like {@code onMessageReceived(MessageReceivedEvent event)}
 * take a look at: {@link net.dv8tion.jda.api.hooks.ListenerAdapter ListenerAdapter}
 *
 * @param  event
 *         The Event to handle.
 */
void onEvent(@Nonnull GenericEvent event);
 
Example #28
Source File: ContextService.java    From JuniperBot with GNU General Public License v3.0 votes vote down vote up
void initContext(GenericEvent event); 
Example #29
Source File: SourceResolverService.java    From JuniperBot with GNU General Public License v3.0 votes vote down vote up
Member getMember(GenericEvent event); 
Example #30
Source File: SourceResolverService.java    From JuniperBot with GNU General Public License v3.0 votes vote down vote up
User getUser(GenericEvent event);