Пример #1
0
    def updatePoints(self, usdPoints, args):
        if args[0]["type"] != "donation":
            return False

        detailedArgs = args[0]["message"][0]

        if "historical" in detailedArgs:
            return False

        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, detailedArgs["name"])
            if user is None:
                return False

            usdAmount = self.currencyConverter.convert(
                float(detailedArgs["amount"]), detailedArgs["currency"], "USD")

            finalValue = int(usdAmount * int(usdPoints))

            user.points = user.points + finalValue

            self.bot.whisper(
                user,
                f"You have been given {finalValue} points due to a donation in your name"
            )
Пример #2
0
 def on_event(self, data):
     if data["type"] == "donation":
         try:
             sub_data = data["message"][0]
             amount = float(str(sub_data["amount"]))
             username = str(sub_data["from"])
             currency = str(sub_data["currency"])
             c = CurrencyConverter()
             log.info(username)
             amount = round(c.convert(amount, currency, "USD"), 2)
             with DBManager.create_session_scope() as db_session:
                 user = User.find_by_user_input(db_session, username)
                 if user is not None:
                     log.info(f"User {user} donated ${amount}")
                     HandlerManager.trigger("on_donate",
                                            user=user,
                                            amount=amount)
         except Exception as e:
             log.error(e)
     if "message" in data and "event" in data["message"]:
         if data["message"][
                 "event"] == "pop":  # new song request pause : pause spotify
             username = data["message"]["media"]["action_by"]
             title = data["message"]["media"]["media_title"]
             HandlerManager.trigger("pause_spotify", title=title)
         elif data["message"]["event"] == "play":  # on resume:
             HandlerManager.trigger("change_state", state=False)
         elif data["message"]["event"] == "pause":  # on pause:
             HandlerManager.trigger("change_state", state=True)
         elif (data["message"]["event"] == "next"
               and data["message"]["media"] is
               None):  # no new songs requested : resume spotify
             HandlerManager.trigger("resume_spotify")
Пример #3
0
    def points_reset(bot, source, message, **options):
        if message is None or len(message) == 0:
            return

        username = message.split(" ")[0]
        if len(username) < 2:
            return

        with DBManager.create_session_scope() as db_session:
            victim = User.find_by_user_input(db_session, username)
            if victim is None:
                bot.whisper(source, "This user does not exist FailFish")
                return

            if victim.points >= 0:
                bot.whisper(source,
                            f"{victim} doesn't have negative points FailFish")
                return

            if victim.points <= -1:
                old_points = victim.points
                victim.points = 0
                bot.whisper(
                    source,
                    f"You changed the points for {victim} from {old_points} to {victim.points} points"
                )
Пример #4
0
    def set_points(self, bot, source, message, **rest):
        if not message:
            return False

        msg_split = message.split(" ")
        if len(msg_split) < 2:
            # The user did not supply enough arguments
            bot.whisper(source, f"Usage: !{self.command_name} USERNAME POINTS")
            return False

        username = msg_split[0]
        if len(username) < 2:
            # The username specified was too short. ;-)
            return False

        try:
            num_points = int(msg_split[1])
        except (ValueError, TypeError):
            # The user did not specify a valid integer for points
            bot.whisper(source, f"Invalid amount of points. Usage: !{self.command_name} USERNAME POINTS")
            return False

        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, username)
            if not user:
                bot.whisper(source, "This user does not exist FailFish")
                return False

            user.points = num_points

            bot.whisper(source, f"Successfully set {user}'s points to {num_points}.")
Пример #5
0
    def edit_points(self, bot, source, message, **rest):
        if not message:
            return False

        msg_split = message.split(" ")
        if len(msg_split) < 2:
            # The user did not supply enough arguments
            bot.whisper(source, f"Usage: !{self.command_name} USERNAME POINTS")
            return False

        username_input = msg_split[0]

        try:
            num_points = int(msg_split[1])
        except (ValueError, TypeError):
            # The user did not specify a valid integer for points
            bot.whisper(source, f"Invalid amount of points. Usage: !{self.command_name} USERNAME POINTS")
            return False

        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, username_input)
            if not user:
                bot.whisper(source, "This user does not exist FailFish")
                return False

            user.points += num_points

            if num_points >= 0:
                bot.whisper(source, f"Successfully gave {user} {num_points} points.")
            else:
                bot.whisper(source, f"Successfully removed {abs(num_points)} points from {user}.")
Пример #6
0
    def permaban_command(bot, source, message, **rest) -> bool:
        if not message:
            return False

        username = message.split(" ")[0]
        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, username)
            if not user:
                bot.whisper(source, "No user with that name found.")
                return False

            if user.banned:
                bot.whisper(source, "User is already permabanned.")
                return False

            user.banned = True
            bot.ban(
                user,
                reason=
                f"User has been added to the {bot.bot_user.login} banlist. Contact a moderator level 1000 or higher for unban.",
            )
            log_msg = f"{user} has been permabanned"
            bot.whisper(source, log_msg)

            AdminLogManager.add_entry("Permaban added", source, log_msg)

        return True
Пример #7
0
    def unpermaban_command(self, bot, source, message, **rest):
        if not message:
            return

        username = message.split(" ")[0]
        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, username)
            if not user:
                bot.whisper(source, "No user with that name found.")
                return False

            if user.banned is False:
                bot.whisper(source, "User is not permabanned.")
                return False

            user.banned = False
            log_msg = f"{user} is no longer permabanned"
            bot.whisper(source, log_msg)

            AdminLogManager.add_entry("Permaban remove", source, log_msg)

            if self.settings["unban_from_chat"] is True:
                bot.unban(user)

                if self.settings["enable_send_timeout"] is True:
                    bot.timeout(
                        user,
                        1,
                        self.settings["timeout_reason"].format(source=source),
                        once=True)
Пример #8
0
 def request_function(self, video_id, requested_by, queue=None):
     if not self.module_state["enabled"]:
         return False
     with DBManager.create_session_scope() as db_session:
         requested_by = User.find_by_user_input(db_session, requested_by)
         if not requested_by:
             return False
         requested_by_id = requested_by.id
         song_info = SongRequestSongInfo._create_or_get(
             db_session, video_id, self.youtube)
         if not song_info:
             log.error("There was an error!")
             return False
         skip_after = (self.settings["max_song_length"] if
                       song_info.duration > self.settings["max_song_length"]
                       else None)
         song = SongrequestQueue._create(db_session, video_id, skip_after,
                                         requested_by_id)
         if queue:
             song._move_song(queue)
         db_session.commit()
         current_song = SongrequestQueue._from_id(db_session,
                                                  self.current_song_id)
         if not current_song or not current_song.requested_by:
             self.load_song()
     return True
Пример #9
0
    def give_points(self, bot, source, message, **rest):
        if message is None or len(message) == 0:
            # The user did not supply any arguments
            return False

        msg_split = message.split(" ")
        if len(msg_split) < 2:
            # The user did not supply enough arguments
            bot.whisper(source, f"Usage: !{self.command_name} USERNAME POINTS")
            return False

        input = msg_split[0]

        try:
            num_points = utils.parse_points_amount(source, msg_split[1])
        except InvalidPointAmount as e:
            bot.whisper(source, f"{e}. Usage: !{self.command_name} USERNAME POINTS")
            return False

        if num_points <= 0:
            # The user tried to specify a negative amount of points
            bot.whisper(source, "You cannot give away negative points admiralCute")
            return True
        # elif num_points < 250:
        #     bot.whisper(source, "You must give 250 points or more :) Be charitable :)")
        #     return True

        if not source.can_afford(num_points):
            # The user tried giving away more points than he owns
            bot.whisper(source, f"You cannot give away more points than you have. You have {source.points} points.")
            return False

        with DBManager.create_session_scope() as db_session:
            target = User.find_by_user_input(db_session, input)
            if target is None:
                # The user tried donating points to someone who doesn't exist in our database
                bot.whisper(source, "This user does not exist FailFish")
                return False

            if target == "admiralbulldog":
                bot.whisper(source, "But why?")
                return False

            if target == source:
                # The user tried giving points to themselves
                bot.whisper(source, "You can't give points to yourself Bruh")
                return True

            if self.settings["target_requires_sub"] is True and target.subscriber is False:
                # Settings indicate that the target must be a subscriber, which he isn't
                bot.whisper(source, "Your target must be a subscriber.")
                return False

            source.points -= num_points
            target.points += num_points

            bot.whisper(source, f"Successfully gave away {num_points} points to {target}")
            bot.whisper(target, f"{source} just gave you {num_points} points! You should probably thank them ;-)")
Пример #10
0
 def skip_function(self, skipped_by):
     with DBManager.create_session_scope() as db_session:
         skipped_by = User.find_by_user_input(db_session, skipped_by)
         if not skipped_by:
             return
         skipped_by_id = skipped_by.id
     if not self.enabled and self.current_song_id:
         return False
     self.load_song(skipped_by_id)
     return True
Пример #11
0
    def get_user_value(self, key, extra={}):
        try:
            with DBManager.create_session_scope() as db_session:
                user = User.find_by_user_input(db_session, extra["argument"])
                if user is not None:
                    return getattr(user, key)
        except:
            log.exception("Caught exception in get_source_value")

        return None
Пример #12
0
 def step_end(self):
     if self.question is not None:
         self.winstreak = 0
         self.bot.safe_me(
             f'MingLee No one could answer the trivia! The answer was "{self.question["answer"]}" MingLee'
         )
         self.question = None
         self.step = 0
         self.last_question = utils.now()
         with DBManager.create_session_scope() as db_session:
             user = User.find_by_user_input(db_session, "datguy1")
             user.points = user.points + 1
Пример #13
0
 def play_function(self, database_id, skipped_by):
     if not self.module_state["enabled"]:
         return False
     with DBManager.create_session_scope() as db_session:
         skipped_by = User.find_by_user_input(db_session, skipped_by)
         if not skipped_by:
             return
         skipped_by_id = skipped_by.id
         song = SongrequestQueue._from_id(db_session, database_id)
         song._move_song(db_session, 1)
         db_session.commit()
     self.load_song(skipped_by_id)
     return True
Пример #14
0
    def unban(bot, source, message, event, args):
        if not message:
            bot.say(f"That user was not found in the user database")
            return False

        input = message.split(" ")[0]
        with DBManager.create_session_scope(expire_on_commit=False) as db_session:
            user = User.find_by_user_input(db_session, input)

            if user is None:
                bot.say(f"That user was not found in the user database")

        bot.execute_delayed(1, bot.unban, user)
Пример #15
0
 def previous_function(self, requested_by):
     if not self.enabled:
         return False
     with DBManager.create_session_scope() as db_session:
         requested_by = User.find_by_user_input(db_session, requested_by)
         if not requested_by:
             return
         requested_by_id = requested_by.id
         SongrequestHistory._insert_previous(db_session, requested_by_id,
                                             self.previous_queue)
         db_session.commit()
     self.previous_queue += 1
     self.load_song(requested_by_id)
     return True
Пример #16
0
 def requeue_function(self, database_id, requested_by):
     if not self.enabled:
         return False
     with DBManager.create_session_scope() as db_session:
         requested_by = User.find_by_user_input(db_session, requested_by)
         if not requested_by:
             return False
         requested_by_id = requested_by.id
         SongrequestHistory._from_id(db_session, database_id).requeue(
             db_session, requested_by_id)
         db_session.commit()
     SongrequestQueue._update_queue()
     self._playlist()
     return True
Пример #17
0
    def check_sub(bot, source, message, event, args):
        if message:
            input = message.split(" ")[0]
            with DBManager.create_session_scope(expire_on_commit=False) as db_session:
                user = User.find_by_user_input(db_session, input)

                if user is None:
                    bot.say("That user was not found in the user database")
        else:
            user = source

        if user.subscriber:
            bot.say(f"{user} is a subscriber PogChamp")
        else:
            bot.say(f"{user} is not a subscriber FeelsBadMan")
Пример #18
0
    def ignore_command(bot, source, message, **rest):
        if not message:
            return False

        with DBManager.create_session_scope() as db_session:
            username = message.split(" ")[0]
            user = User.find_by_user_input(db_session, username)

            if user == source:
                bot.whisper(source, "You cannot ignore yourself")
                return False

        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, username)
            if user is None:
                bot.whisper(source, "No user with that name found.")
                return False

            if user.ignored:
                bot.whisper(source, "User is already ignored.")
                return False

            user.ignored = True
            bot.whisper(source, f"Now ignoring {user}")
Пример #19
0
 def replay_function(self, requested_by):
     if not self.enabled:
         return False
     with DBManager.create_session_scope() as db_session:
         requested_by = User.find_by_user_input(db_session, requested_by)
         if not requested_by:
             return False
         requested_by_id = requested_by.id
         current_song = SongrequestQueue._from_id(db_session,
                                                  self.current_song_id)
         self.request_function(current_song.video_id,
                               current_song.requested_by_id, 1)
         db_session.commit()
     self.load_song(requested_by_id)
     SongrequestQueue._update_queue()
     return True
Пример #20
0
    def check_mod(bot, source, message, **rest):
        if message:
            username = message.split(" ")[0]
            with DBManager.create_session_scope(
                    expire_on_commit=False) as db_session:
                user = User.find_by_user_input(db_session, username)

                if user is None:
                    bot.say(f"{username} was not found in the user database")
        else:
            user = source

        if user.moderator:
            bot.say(f"{user} is a moderator PogChamp")
        else:
            bot.say(f"{user} is not a moderator FeelsBadMan")
Пример #21
0
    async def _connections(self, message):
        if not self.guild:
            return

        requestor = self.guild.get_member(message.author.id)
        if not requestor:
            return

        with DBManager.create_session_scope() as db_session:
            userconnections = None
            admin_role = self.guild.get_role(int(self.settings["admin_role"]))
            if admin_role in requestor.roles:
                args = message.content.split(" ")[1:]
                if len(args) > 0:
                    check_user = args[0]
                    user = User.find_by_user_input(db_session, check_user)
                    if user:
                        userconnections = db_session.query(
                            UserConnections).filter_by(
                                twitch_id=user.id).one_or_none()
                    if not userconnections:
                        await self.private_message(
                            requestor,
                            f"Connection data not found for user " + args[0])
                        return
            if not userconnections:
                userconnections = (db_session.query(UserConnections).filter_by(
                    discord_user_id=str(requestor.id)).one_or_none())
            if not userconnections:
                await self.private_message(
                    requestor,
                    f"You have not set up your account info yet, go to https://{self.bot.bot_domain}/connections to pair your twitch and steam to your discord account!",
                )
                return
            user = userconnections.twitch_user
            if user.tier is None:
                tier = 0
            elif user.tier >= 1:
                tier = user.tier
            else:
                tier = 0
            discord = await self.get_discord_string(
                userconnections.discord_user_id)
            await self.private_message(
                message.author,
                f"Tier {tier} sub:\nTwitch: {user} (<https://twitch.tv/{user.login}>){discord}\nSteam: <https://steamcommunity.com/profiles/{userconnections.steam_id}>",
            )
Пример #22
0
    def unignore_command(bot, source, message, **rest):
        if not message:
            return

        username = message.split(" ")[0]
        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, username)
            if not user:
                bot.whisper(source, "No user with that name found.")
                return False

            if user.ignored is False:
                bot.whisper(source, "User is not ignored.")
                return False

            user.ignored = False
            bot.whisper(source, f"No longer ignoring {user}")
Пример #23
0
 def requeue_function(self, database_id, requested_by):
     if not self.module_state["enabled"]:
         return False
     with DBManager.create_session_scope() as db_session:
         requested_by = User.find_by_user_input(db_session, requested_by)
         if not requested_by:
             return False
         requested_by_id = requested_by.id
         SongrequestHistory._from_id(db_session, database_id).requeue(
             db_session, requested_by_id)
         db_session.commit()
         current_song = SongrequestQueue._from_id(db_session,
                                                  self.current_song_id)
         if not current_song or not current_song.requested_by:
             self.load_song()
     self._playlist()
     return True
Пример #24
0
    def debug_user(bot, source, message, **options):
        if not message or len(message) <= 0:
            bot.whisper(source, "Usage: !debug user USERNAME")
            return False

        username = message.split(" ")[0]
        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, username)

            if user is None:
                bot.whisper(source, "No user with this username found.")
                return False

            # TODO the time_in_chat_ properties could be displayed in a more user-friendly way
            #  current output format is time_in_chat_online=673800.0, time_in_chat_offline=7651200.0
            data = user.jsonify()

            bot.whisper(source, ", ".join([f"{key}={value}" for (key, value) in data.items()]))
Пример #25
0
    def timeout(bot, source, message, event, args):
        if not message:
            bot.say(f"That user was not found in the user database")
            return False

        message_split = message.split()
        input = message.split()[0]
        if len(message_split) < 2:
            bot.say(f"No timeout duration specified")
            return False

        with DBManager.create_session_scope(expire_on_commit=False) as db_session:
            user = User.find_by_user_input(db_session, input)

            if user is None:
                bot.say(f"That user was not found in the user database")
                return False

        bot.execute_delayed(1, bot.timeout, user, message[1], " ".join(message[2:]))
Пример #26
0
    def permaban_command(bot, source, message, **rest):
        if not message:
            return

        username = message.split(" ")[0]
        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, username)
            if not user:
                bot.whisper(source, "No user with that name found.")
                return False

            if user.banned:
                bot.whisper(source, "User is already permabanned.")
                return False

            user.banned = True
            log_msg = f"{user} has been permabanned"
            bot.whisper(source, log_msg)

            AdminLogManager.add_entry("Permaban added", source, log_msg)
Пример #27
0
    def get(login):
        # add ?user_input=true to query user more fuzzily
        query_by_user_input = request.args.get("user_input") == "true"

        with DBManager.create_session_scope() as db_session:
            if query_by_user_input:
                user = User.find_by_user_input(db_session, login)
            else:
                user = User.find_by_login(db_session, login)
            if user is None:
                return {"error": "Not found"}, 404

            # these are provided for legacy purposes - so we don't break the API interface.
            json = user.jsonify()
            json["username_raw"] = json["name"]
            json["username"] = json["login"]
            json["nl_rank"] = json["num_lines_rank"]
            json["minutes_in_chat_online"] = int(json["time_in_chat_online"] / 60)
            json["minutes_in_chat_offline"] = int(json["time_in_chat_offline"] / 60)
            return json
Пример #28
0
    def updatePoints(self, usdPoints, args):
        if args[0]["type"] != "donation":
            return False

        donation = args[0]["message"][0]

        if "historical" in donation:
            return False

        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, donation["name"])
            if user is None:
                return False

            finalValue = int(
                float(donation["formatted_amount"][1:]) *
                int(usdPoints))  # formatted_amount changes to USD

            user.points = user.points + finalValue
            self.bot.whisper(
                user,
                f"You have been given {finalValue} points due to a donation in your name. If you want to see your donation, visit https://donations.admiralbulldog.live",
            )
Пример #29
0
    def initiate_duel(self, bot, source, message, **rest):
        """
        Initiate a duel with a user.
        You can also bet points on the winner.
        By default, the maximum amount of points you can spend is 420.

        How to use: !duel USERNAME POINTS_TO_BET
        """

        if message is None:
            bot.whisper(source, f"Invalid Usage !duel USERNAME POINTS_TO_BET")
            return False

        msg_split = message.split()
        input = msg_split[0]

        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, input)
            if user is None:
                # No user was found with this username
                bot.whisper(
                    source,
                    f"The user, {input}, has never typed in chat before FailFish"
                )
                return False
            if user == source:
                bot.whisper(source, f"You cannot duel yourself")
                return False
            duel_price = 0
            if len(msg_split) > 1:
                try:
                    duel_price = int(msg_split[1])
                    if duel_price < 0:
                        return False
                except ValueError:
                    pass

            if source.id in self.duel_requests:
                currently_duelling = User.find_by_id(
                    db_session, self.duel_requests[source.id])
                if currently_duelling is None:
                    del self.duel_requests[source.id]
                    return False
                bot.whisper(
                    source,
                    f"You already have a duel request active with {currently_duelling}. Type !cancelduel to cancel your duel request.",
                )
                return False
            if user.last_active is None or (
                    utils.now() - user.last_active) > timedelta(minutes=5):
                bot.whisper(
                    source,
                    "This user has not been active in chat within the last 5 minutes. Get them to type in chat before sending another challenge",
                )
                return False

            if not user.can_afford(duel_price) or not source.can_afford(
                    duel_price):
                bot.whisper(
                    source,
                    f"You or your target do not have more than {duel_price} points, therefore you cannot duel for that amount.",
                )
                return False

            if user.id in self.duel_targets:
                challenged_by = User.find_by_id(db_session,
                                                self.duel_requests[user.id])
                bot.whisper(
                    source,
                    f"This person is already being challenged by {challenged_by}. Ask them to answer the offer by typing !deny or !accept",
                )
                return False

            self.duel_targets[user.id] = source.id
            self.duel_requests[source.id] = user.id
            self.duel_request_price[source.id] = duel_price
            self.duel_begin_time[source.id] = utils.now()
            bot.whisper(
                user,
                f"You have been challenged to a duel by {source} for {duel_price} points. You can either !accept or !deny this challenge.",
            )
            bot.whisper(source,
                        f"You have challenged {user} for {duel_price} points")
Пример #30
0
    def user_profile(login):
        with DBManager.create_session_scope() as db_session:
            user = User.find_by_user_input(db_session, login)
            if user is None:
                return render_template("no_user.html"), 404

            roulettes = db_session.query(Roulette).filter_by(
                user_id=user.id).order_by(Roulette.created_at.desc()).all()

            roulette_stats = None
            if len(roulettes) > 0:
                profit = 0
                total_points = 0
                biggest_loss = 0
                biggest_win = 0
                biggest_winstreak = 0
                biggest_losestreak = 0
                num_wins = 0
                num_losses = 0
                winrate = 0
                num_roulettes = len(roulettes)
                cw = 0
                for roulette in roulettes:
                    profit += roulette.points
                    total_points += abs(roulette.points)

                    if roulette.points > 0:
                        # a win!
                        num_wins += 1
                        if cw < 0:
                            if abs(cw) > biggest_losestreak:
                                biggest_losestreak = abs(cw)
                            cw = 0
                        cw += 1
                    else:
                        # a loss
                        num_losses += 1
                        if cw > 0:
                            if cw > biggest_winstreak:
                                biggest_winstreak = cw
                            cw = 0
                        cw -= 1

                    if roulette.points < biggest_loss:
                        biggest_loss = roulette.points
                    elif roulette.points > biggest_win:
                        biggest_win = roulette.points

                # Calculate winrate
                if num_losses == 0:
                    winrate = 1
                elif num_wins == 0:
                    winrate = 0
                else:
                    winrate = num_wins / num_roulettes

                # Finalize win/lose streaks in case we're currently
                # on the biggest win/lose streak
                if cw < 0:
                    if abs(cw) > biggest_losestreak:
                        biggest_losestreak = abs(cw)
                elif cw > 0:
                    if cw > biggest_winstreak:
                        biggest_winstreak = cw

                if "roulette" in app.module_manager:
                    roulette_base_winrate = 1.0 - app.module_manager[
                        "roulette"].settings["rigged_percentage"] / 100
                else:
                    roulette_base_winrate = 0.45

                roulette_stats = {
                    "profit": profit,
                    "total_points": total_points,
                    "biggest_win": biggest_win,
                    "biggest_loss": biggest_loss,
                    "num_roulettes": num_roulettes,
                    "biggest_winstreak": biggest_winstreak,
                    "biggest_losestreak": biggest_losestreak,
                    "winrate": winrate,
                    "winrate_str": f"{winrate * 100:.2f}%",
                    "roulette_base_winrate": roulette_base_winrate,
                }
            return render_template("user.html",
                                   user=user,
                                   roulette_stats=roulette_stats,
                                   roulettes=roulettes)