Search in sources :

Example 1 with User

use of com.github.twitch4j.helix.domain.User in project pgda by jonteohr.

the class BankHandler method onDaily.

@EventSubscriber
public void onDaily(IRCMessageEvent e) {
    if (!e.getChannel().getName().equalsIgnoreCase("tejbz"))
        return;
    if (!e.getMessage().isPresent() || e.getUser() == null)
        return;
    String[] args = e.getMessage().get().split("\\s+");
    String user = e.getTags().get("display-name");
    if (!args[0].equalsIgnoreCase("!bank") && !args[0].equalsIgnoreCase("!collect") && !args[0].equalsIgnoreCase("!roll") && !args[0].equalsIgnoreCase("!givecoins") && !args[0].equalsIgnoreCase("!transfer") && !args[0].equalsIgnoreCase("!dropcoins"))
        return;
    BankSQL bankSQL = new BankSQL();
    if (args[0].equalsIgnoreCase("!bank")) {
        int coins = bankSQL.getCoins(user);
        String fCoins = String.format("%,d", coins);
        Twitch.sendPm(user, "You currently have " + fCoins + " PGDA coins.");
        return;
    }
    /*
			MODERATOR
			COMMANDS
		 */
    if (Twitch.isModerator(e.getTags())) {
        if (args[0].equalsIgnoreCase("!givecoins")) {
            if (args.length < 3) {
                Twitch.sendPm(user, "Correct usage: !givecoins [user] [amount]");
                return;
            }
            User target = Twitch.getUser(args[1]);
            if (target == null) {
                Twitch.sendPm(user, "Couldn't find user " + args[1]);
                return;
            }
            if (!bankSQL.isUserInDatabase(target.getDisplayName())) {
                Twitch.sendPm(user, target.getDisplayName() + " has never collected any coins. They must have done this at least once!");
                return;
            }
            try {
                int amount = Integer.parseInt(args[2]);
                bankSQL.incrementCoins(target.getDisplayName(), amount);
                Twitch.sendPm(user, "You've awarded " + target.getDisplayName() + " " + amount + " PGDA Coins.");
                Twitch.sendPm(target.getDisplayName(), user + " has awarded you " + amount + " PGDA Coins.");
                return;
            } catch (NumberFormatException ex) {
                Twitch.sendPm(user, args[2] + " is not a valid number.");
                return;
            }
        }
        if (args[0].equalsIgnoreCase("!dropcoins") && (user.equalsIgnoreCase("tejbz") || user.equalsIgnoreCase("rlhypr"))) {
            int coins;
            if (args.length < 2) {
                coins = 100;
            } else {
                try {
                    coins = Integer.parseInt(args[1]);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace();
                    Twitch.chat(user + " " + args[1] + " is not a valid number.");
                    return;
                }
            }
            List<String> chatters = Twitch.twitchClient.getMessagingInterface().getChatters("tejbz").execute().getAllViewers();
            int finalCoins = coins;
            chatters.forEach(chatter -> {
                if (bankSQL.isUserInDatabase(chatter))
                    bankSQL.incrementCoins(chatter, finalCoins);
            });
            Twitch.chatMe("tejbzBeer " + user + " Just awarded all viewers with " + coins + " PGDA Coins! tejbzPog");
            return;
        }
    }
    if (args[0].equalsIgnoreCase("!collect")) {
        Random random = new Random();
        int maxDaily = 1000;
        int minDaily = 500;
        int coins = random.nextInt(maxDaily - minDaily) + minDaily;
        String fCoins = String.format("%,d", coins);
        if (!bankSQL.isUserInDatabase(user)) {
            if (bankSQL.collectDaily(user, coins)) {
                Twitch.sendPm(user, "You've collected your daily " + fCoins + " PGDA coins!");
            }
            return;
        }
        if (bankSQL.getLastCollected(user) == null) {
            if (bankSQL.collectDaily(user, coins))
                Twitch.sendPm(user, "You've collected your daily " + fCoins + " PGDA coins!");
            return;
        }
        Calendar current = Calendar.getInstance();
        current.set(Calendar.HOUR_OF_DAY, 0);
        current.set(Calendar.MINUTE, 0);
        current.set(Calendar.SECOND, 0);
        current.set(Calendar.MILLISECOND, 0);
        Calendar last = Calendar.getInstance();
        last.setTime(bankSQL.getLastCollected(user));
        last.set(Calendar.HOUR_OF_DAY, 0);
        last.set(Calendar.MINUTE, 0);
        last.set(Calendar.SECOND, 0);
        last.set(Calendar.MILLISECOND, 0);
        if (last.compareTo(current) < 0) {
            if (bankSQL.collectDaily(user, coins)) {
                Twitch.sendPm(user, "You've collected your daily " + fCoins + " PGDA coins!");
            }
        } else {
            Twitch.sendPm(user, "You've already collected your daily PGDA Coins!");
        }
        return;
    }
    if (args[0].equalsIgnoreCase("!roll")) {
        if (CoinsTimer.isCooldown(user)) {
            Twitch.sendPm(user, "That command is currently in a cooldown! Try again in " + CoinsTimer.getCooldown(user) + " minutes.");
            return;
        }
        if (args.length < 2) {
            Twitch.chat("@" + user + " You didn't specify a bet amount.");
            return;
        }
        try {
            int bet = Integer.parseInt(args[1]);
            rollCoins(user, bet);
            return;
        } catch (NumberFormatException ex) {
            if (!args[1].equalsIgnoreCase("all")) {
                Twitch.chat("@" + user + " Bet amount was not a valid number.");
                return;
            }
            rollCoins(user, bankSQL.getCoins(user));
            return;
        }
    }
    if (args[0].equalsIgnoreCase("!transfer")) {
        if (args.length < 3) {
            Twitch.sendPm(user, "Invalid arguments. Need to specify who you want to give coins and how much. Like this: !transfer rlHypr 1337");
            return;
        }
        try {
            User target = Twitch.getUser(args[1]);
            int amount = Integer.parseInt(args[2]);
            if (target == null) {
                Twitch.sendPm(user, "Could not find user " + args[1]);
                return;
            }
            if (bankSQL.getCoins(user) < amount) {
                Twitch.sendPm(user, "You don't have " + amount + " coins.");
                return;
            }
            if (!bankSQL.incrementCoins(target.getDisplayName(), amount) && bankSQL.decrementCoins(user, amount)) {
                Twitch.sendPm(user, "Couldn't transfer at the moment. Please try again later!");
                return;
            }
            Twitch.sendPm(user, "You've given " + target + " " + amount + " Coins!");
            Twitch.sendPm(target.getDisplayName(), user + " has given you " + amount + " Coins!");
        } catch (NumberFormatException ex) {
            Twitch.sendPm(user, args[2] + " is not a valid number.");
            return;
        }
    }
}
Also used : BankSQL(com.github.jonteohr.tejbz.twitch.sql.BankSQL) User(com.github.twitch4j.helix.domain.User) Random(java.util.Random) Calendar(java.util.Calendar) EventSubscriber(com.github.philippheuer.events4j.simple.domain.EventSubscriber)

Example 2 with User

use of com.github.twitch4j.helix.domain.User in project Ree6 by Ree6-Applications.

the class Notifier method registerTwitchEventHandler.

// region Twitch
/**
 * Register a EventHandler for the Twitch Livestream Event.
 */
public void registerTwitchEventHandler() {
    getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> {
        // Go through every Webhook that is registered for the Twitch Channel
        for (String[] credits : Main.getInstance().getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getStream().getUserName().toLowerCase())) {
            // Create Webhook Message.
            WebhookMessageBuilder wmb = new WebhookMessageBuilder();
            wmb.setAvatarUrl(BotInfo.botInstance.getSelfUser().getAvatarUrl());
            wmb.setUsername("Ree6");
            WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder();
            webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), null));
            webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotInfo.botInstance.getSelfUser().getAvatarUrl(), null));
            // Try getting the User.
            Optional<User> twitchUserRequest = getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst();
            if (getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst().isPresent()) {
                webhookEmbedBuilder.setImageUrl(twitchUserRequest.orElseThrow().getProfileImageUrl());
            } else {
                webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrl());
            }
            // Set rest of the Information.
            webhookEmbedBuilder.setDescription(channelGoLiveEvent.getStream().getUserName() + " is now Live on Twitch! Come and join the Stream <https://twitch.tv/" + channelGoLiveEvent.getChannel().getName() + "> !");
            webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Title**", channelGoLiveEvent.getStream().getTitle()));
            webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Game**", channelGoLiveEvent.getStream().getGameName()));
            webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Viewer**", "" + channelGoLiveEvent.getStream().getViewerCount()));
            webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(Data.ADVERTISEMENT, BotInfo.botInstance.getSelfUser().getAvatarUrl()));
            webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB());
            wmb.addEmbeds(webhookEmbedBuilder.build());
            Webhook.sendWebhook(null, wmb.build(), Long.parseLong(credits[0]), credits[1], false);
        }
    });
}
Also used : WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) User(com.github.twitch4j.helix.domain.User) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder)

Example 3 with User

use of com.github.twitch4j.helix.domain.User in project spotifybot by NotEchoDE.

the class CallbackController method twitchCallback.

@GetMapping("/twitch/callback")
public String twitchCallback(@RequestParam(name = "code", defaultValue = "null") String code, HttpServletResponse response, Model model) {
    if (code.equals("null"))
        return "redirect:/erorr?code=503";
    OAuth2Credential credentialByCode = oAuth2IdentityProvider.getCredentialByCode(code);
    List<User> users = twitchClient.getHelix().getUsers(credentialByCode.getAccessToken(), null, null).execute().getUsers();
    if (users.size() == 0)
        return "redirect:/erorr?code=503";
    User twitchUser = users.get(0);
    BotUser user = repository.findByTwitchId(twitchUser.getId());
    if (user == null) {
        user = new BotUser(0L, twitchUser.getId(), DefaultModules.defaultList(), Collections.singletonList(new TokenPair(0L, credentialByCode.getAccessToken(), credentialByCode.getRefreshToken(), TokenType.TWITCH)));
    } else {
        user.twitchTokens().setAccessToken(credentialByCode.getAccessToken());
        user.twitchTokens().setRefreshToken(credentialByCode.getRefreshToken());
    }
    repository.saveAndFlush(user);
    Cookie cookie = new Cookie("session", sessionManagementService.createSession(user));
    cookie.setPath("/");
    cookie.setMaxAge(3600);
    response.addCookie(cookie);
    return "redirect:/dashboard";
}
Also used : Cookie(javax.servlet.http.Cookie) BotUser(de.notecho.spotify.database.user.entities.BotUser) OAuth2Credential(com.github.philippheuer.credentialmanager.domain.OAuth2Credential) BotUser(de.notecho.spotify.database.user.entities.BotUser) User(com.github.twitch4j.helix.domain.User) TokenPair(de.notecho.spotify.database.user.entities.TokenPair) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 4 with User

use of com.github.twitch4j.helix.domain.User in project spotifybot by NotEchoDE.

the class DashboardController method dashboard.

@GetMapping("/dashboard")
public String dashboard(@CookieValue(name = "session", defaultValue = "null") String session, Model model) {
    BotUser user = sessionManagementService.getUser(session);
    if (session.equals("null") || user == null)
        return "redirect:/login";
    List<User> twitchUsers = twitchClient.getHelix().getUsers(user.twitchTokens().getAccessToken(), null, null).execute().getUsers();
    User twitchUser = twitchUsers.get(0);
    model.addAttribute("username", twitchUser.getLogin());
    model.addAttribute("spotifyConnected", user.spotifyTokens() != null);
    return "dashboard";
}
Also used : BotUser(de.notecho.spotify.database.user.entities.BotUser) User(com.github.twitch4j.helix.domain.User) BotUser(de.notecho.spotify.database.user.entities.BotUser) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 5 with User

use of com.github.twitch4j.helix.domain.User in project spotifybot by NotEchoDE.

the class BotInstance method updateTwitchToken.

private void updateTwitchToken(TokenPair tokenPair) {
    OAuth2Credential credential = new OAuth2Credential("twitch", tokenPair.getAccessToken());
    credential.setRefreshToken(tokenPair.getRefreshToken());
    Optional<OAuth2Credential> credentialOptional = context.getBean(OAuth2IdentityProvider.class).refreshCredential(credential);
    if (credentialOptional.isPresent()) {
        credential = credentialOptional.get();
        User twitchUser = client.getHelix().getUsers(credential.getAccessToken(), null, null).execute().getUsers().get(0);
        if (tokenPair.getTokenType().equals(TokenType.TWITCH)) {
            id = twitchUser.getId();
            login = twitchUser.getLogin();
        }
        tokenPair.setAccessToken(credential.getAccessToken());
        tokenPair.setRefreshToken(credential.getRefreshToken());
        Logger.log(LogType.DEBUG, "[" + user.getId() + "] Got new Twitch Token(" + tokenPair.getTokenType().name() + ") for " + twitchUser.getLogin() + " | " + credential.getAccessToken(), "Twitch", tokenPair.getTokenType().name(), login, credential.getAccessToken());
    }
}
Also used : OAuth2Credential(com.github.philippheuer.credentialmanager.domain.OAuth2Credential) BotUser(de.notecho.spotify.database.user.entities.BotUser) User(com.github.twitch4j.helix.domain.User) OAuth2IdentityProvider(com.github.philippheuer.credentialmanager.identityprovider.OAuth2IdentityProvider)

Aggregations

User (com.github.twitch4j.helix.domain.User)5 BotUser (de.notecho.spotify.database.user.entities.BotUser)3 OAuth2Credential (com.github.philippheuer.credentialmanager.domain.OAuth2Credential)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)1 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)1 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)1 BankSQL (com.github.jonteohr.tejbz.twitch.sql.BankSQL)1 OAuth2IdentityProvider (com.github.philippheuer.credentialmanager.identityprovider.OAuth2IdentityProvider)1 EventSubscriber (com.github.philippheuer.events4j.simple.domain.EventSubscriber)1 TokenPair (de.notecho.spotify.database.user.entities.TokenPair)1 Calendar (java.util.Calendar)1 Random (java.util.Random)1 Cookie (javax.servlet.http.Cookie)1