コード例 #1
0
    def __init__(self, bot):
        super().__init__(bot)
        self.bets = {}

        redis = RedisManager.get()

        self.last_game_start = None
        self.last_game_id = None
        try:
            last_game_start_timestamp = int(
                redis.get("{streamer}:last_hsbet_game_start".format(streamer=StreamHelper.get_streamer()))
            )
            self.last_game_start = datetime.datetime.fromtimestamp(last_game_start_timestamp, tz=datetime.timezone.utc)
        except (TypeError, ValueError):
            # Issue with the int-cast
            pass
        except (OverflowError, OSError):
            # Issue with datetime.fromtimestamp
            pass

        try:
            self.last_game_id = int(
                redis.get("{streamer}:last_hsbet_game_id".format(streamer=StreamHelper.get_streamer()))
            )
        except (TypeError, ValueError):
            pass

        self.job = ScheduleManager.execute_every(15, self.poll_trackobot)
        self.job.pause()
        self.reminder_job = ScheduleManager.execute_every(1, self.reminder_bet)
        self.reminder_job.pause()
コード例 #2
0
ファイル: action.py プロジェクト: Nacht123/pajbot
    def run(self, bot, source, message, event={}, args={}):
        resp = self.get_response(bot, self.get_extra_data(source, message, args))

        if not resp:
            return False

        if irc.client.is_channel(event.target):
            if self.num_urlfetch_subs == 0:
                return bot.say(resp, channel=event.target)
            else:
                return ScheduleManager.execute_now(urlfetch_msg,
                        args=[],
                        kwargs={
                            'args': [],
                            'kwargs': {
                                'channel': event.target
                                },
                            'method': bot.say,
                            'message': resp,
                            'num_urlfetch_subs': self.num_urlfetch_subs,
                            })
        else:
            if self.num_urlfetch_subs == 0:
                return bot.whisper(source.username, resp)
            else:
                return ScheduleManager.execute_now(urlfetch_msg,
                        args=[],
                        kwargs={
                            'args': [source.username],
                            'kwargs': {},
                            'method': bot.whisper,
                            'message': resp,
                            'num_urlfetch_subs': self.num_urlfetch_subs,
                            })
コード例 #3
0
ファイル: hsbet.py プロジェクト: Neclord9/pajbot
    def __init__(self):
        super().__init__()
        self.bets = {}

        redis = RedisManager.get()

        self.last_game_start = None
        self.last_game_id = None
        try:
            last_game_start_timestamp = int(redis.get('{streamer}:last_hsbet_game_start'.format(streamer=StreamHelper.get_streamer())))
            self.last_game_start = datetime.fromtimestamp(last_game_start_timestamp)
        except (TypeError, ValueError):
            # Issue with the int-cast
            pass
        except (OverflowError, OSError):
            # Issue with datetime.fromtimestamp
            pass

        try:
            self.last_game_id = int(redis.get('{streamer}:last_hsbet_game_id'.format(streamer=StreamHelper.get_streamer())))
        except (TypeError, ValueError):
            pass

        self.job = ScheduleManager.execute_every(15, self.poll_trackobot)
        self.job.pause()
        self.reminder_job = ScheduleManager.execute_every(1, self.reminder_bet)
        self.reminder_job.pause()
コード例 #4
0
    def __init__(self, bot):
        super().__init__(bot)
        self.action_queue = ActionQueue()
        self.action_queue.start()
        self.bets = {}
        self.betting_open = False
        self.message_closed = True
        self.isRadiant = False
        self.matchID = 0
        self.oldID = 0
        self.winPoints = 0
        self.lossPoints = 0
        self.winBetters = 0
        self.lossBetters = 0
        self.gettingTeam = False
        self.secondAttempt = False
        self.calibrating = True
        self.calibratingSecond = True
        self.jobPaused = False
        self.spectating = False

        self.job = ScheduleManager.execute_every(25, self.poll_webapi)
        self.job.pause()

        self.reminder_job = ScheduleManager.execute_every(
            200, self.reminder_bet)
        self.reminder_job.pause()
コード例 #5
0
    def pleblist_add_song(self, **options):
        message = options['message']
        bot = options['bot']
        source = options['source']

        if message:
            # 1. Find youtube ID in message
            msg_split = message.split(' ')
            youtube_id = find_youtube_id_in_string(msg_split[0])

            force = False

            try:
                if msg_split[1] == 'force' and source.level >= 500:
                    force = True
            except:
                pass

            if youtube_id is False:
                bot.whisper(source.username, 'Could not find a valid youtube ID in your argument.')
                return False

            # 2. Make sure the stream is live
            stream_id = StreamHelper.get_current_stream_id()
            if stream_id is None or stream_id is False:
                bot.whisper(source.username, 'You cannot request songs while the stream is offline.')
                return False

            ScheduleManager.execute_now(self.bg_pleblist_add_song, args=[stream_id, youtube_id, force], kwargs=options)
コード例 #6
0
ファイル: pleblist.py プロジェクト: MrBean355/pajbot
    def pleblist_add_song(self, bot, source, message, **rest):
        if not message:
            return False

        # 1. Find youtube ID in message
        msg_split = message.split(" ")
        youtube_id = find_youtube_id_in_string(msg_split[0])

        force = False

        try:
            if msg_split[1] == "force" and source.level >= 500:
                force = True
        except:
            pass

        if youtube_id is False:
            bot.whisper(source, "Could not find a valid youtube ID in your argument.")
            return False

        # 2. Make sure the stream is live
        stream_id = StreamHelper.get_current_stream_id()
        if stream_id is None or stream_id is False:
            bot.whisper(source, "You cannot request songs while the stream is offline.")
            return False

        ScheduleManager.execute_now(self.bg_pleblist_add_song, args=[stream_id, youtube_id, force, bot, source])
コード例 #7
0
ファイル: pubsubapi.py プロジェクト: metrize/troybot
    def ping_server(self):
        if self.sent_ping:
            return

        self.sendData({"type": "PING"})
        self.sent_ping = True
        ScheduleManager.execute_delayed(30, self.check_ping)
コード例 #8
0
    def enable(self, bot):
        # Web interface, nothing to do
        if not bot:
            return

        # every 10 minutes, add the subscribers update to the action queue
        ScheduleManager.execute_every(10 * 60, lambda: self.bot.action_queue.submit(self._update_subscribers))
コード例 #9
0
    def run(self, bot, source, message, event={}, args={}, whisper=False):
        if self.action is None:
            log.warning('This command is not available.')
            return False

        if source.level < self.level:
            # User does not have a high enough power level to run this command
            bot.whisper(source.username, 'You don\'t have a high enough access level to use this command. If you think you are supposed to, ' \
                                         'contact DatGuy1/Darth_Henry/AdmiralBulldog')
            return False

        if whisper and self.can_execute_with_whisper is False and source.level < Command.MIN_WHISPER_LEVEL and source.moderator is False:
            # This user cannot execute the command through a whisper
            bot.whisper(source.username, 'You can\'t use this command in whispers you baboon')
            return False

        if self.sub_only and source.subscriber is False and source.level < Command.BYPASS_SUB_ONLY_LEVEL and source.moderator is False:
            # User is not a sub or a moderator, and cannot use the command.
            bot.whisper(source.username, 'This is a sub only command :)')
            return False

        if self.mod_only and source.moderator is False and source.level < Command.BYPASS_MOD_ONLY_LEVEL:
            # User is not a twitch moderator, or a bot moderator
            return False

        cd_modifier = 0.2 if source.level >= 500 or source.moderator is True else 1.0

        cur_time = time.time()
        time_since_last_run = (cur_time - self.last_run) / cd_modifier

        if time_since_last_run < self.delay_all and source.level < Command.BYPASS_DELAY_LEVEL:
            log.debug('Command was run {0:.2f} seconds ago, waiting...'.format(time_since_last_run))
            return False

        time_since_last_run_user = (cur_time - self.last_run_by_user.get(source.username, 0)) / cd_modifier

        if time_since_last_run_user < self.delay_user and source.level < Command.BYPASS_DELAY_LEVEL:
            log.debug('{0} ran command {1:.2f} seconds ago, waiting...'.format(source.username, time_since_last_run_user))
            return False

        if self.cost > 0 and not source.can_afford(self.cost):
            if self.notify_on_error:
                bot.whisper(source.username, 'You do not have the required {} points to execute this command. (You have {} points)'.format(self.cost, source.points_available()))
            # User does not have enough points to use the command
            return False

        if self.tokens_cost > 0 and not source.can_afford_with_tokens(self.tokens_cost):
            if self.notify_on_error:
                bot.whisper(source.username, 'You do not have the required {} tokens to execute this command. (You have {} tokens)'.format(self.tokens_cost, source.tokens))
            # User does not have enough tokens to use the command
            return False

        args.update(self.extra_args)
        if self.run_in_thread:
            log.debug('Running {} in a thread'.format(self))
            ScheduleManager.execute_now(self.run_action, args=[bot, source, message, event, args])
        else:
            self.run_action(bot, source, message, event, args)
コード例 #10
0
ファイル: command.py プロジェクト: morenoMe/pajbot
    def run(self, bot, source, message, event={}, args={}, whisper=False):
        if self.action is None:
            log.warning("This command is not available.")
            return False

        if not self.can_run_command(source, whisper):
            return False

        cd_modifier = 0.2 if source.level >= 500 or source.moderator is True else 1.0

        cur_time = pajbot.utils.now().timestamp()
        time_since_last_run = (cur_time - self.last_run) / cd_modifier

        if time_since_last_run < self.delay_all and source.level < Command.BYPASS_DELAY_LEVEL:
            log.debug(
                f"Command was run {time_since_last_run:.2f} seconds ago, waiting..."
            )
            return False

        time_since_last_run_user = (
            cur_time - self.last_run_by_user.get(source.id, 0)) / cd_modifier

        if time_since_last_run_user < self.delay_user and source.level < Command.BYPASS_DELAY_LEVEL:
            log.debug(
                f"{source} ran command {time_since_last_run_user:.2f} seconds ago, waiting..."
            )
            return False

        if self.cost > 0 and not source.can_afford(self.cost):
            if self.notify_on_error:
                bot.whisper(
                    source,
                    f"You do not have the required {self.cost} points to execute this command. (You have {source.points} points)",
                )
            # User does not have enough points to use the command
            return False

        if self.tokens_cost > 0 and not source.can_afford_with_tokens(
                self.tokens_cost):
            if self.notify_on_error:
                bot.whisper(
                    source,
                    f"You do not have the required {self.tokens_cost} tokens to execute this command. (You have {source.tokens} tokens)",
                )
            # User does not have enough tokens to use the command
            return False

        args.update(self.extra_args)
        if self.run_in_thread:
            log.debug(f"Running {self} in a thread")
            ScheduleManager.execute_now(
                self.run_action, args=[bot, source, message, event, args])
        else:
            self.run_action(bot, source, message, event, args)

        return True
コード例 #11
0
ファイル: pubsubapi.py プロジェクト: metrize/troybot
 def __init__(self, bot, token):
     self.bot = bot
     self.token = token
     self.sent_ping = False
     self.websocket = None
     self.ping_schedule = ScheduleManager.execute_every(
         60, self.ping_server)
     self.check_connection_schedule = ScheduleManager.execute_every(
         30, self.check_connection)
     ScheduleManager.execute_now(self.check_connection)
コード例 #12
0
ファイル: user_ranks_refresh.py プロジェクト: sgaweda/troybot
    def start(action_queue):
        # We add up to 1 minute of jitter to try to alleviate CPU spikes when multiple pajbot instances restart at the same time.
        # The jitter is added to both the initial refresh, and the scheduled one every 5 minutes.

        # Initial refresh
        ScheduleManager.execute_delayed(
            UserRanksRefreshManager._jitter(),
            lambda: action_queue.submit(UserRanksRefreshManager._refresh,
                                        action_queue),
        )
コード例 #13
0
ファイル: command.py プロジェクト: Neclord9/pajbot
    def run(self, bot, source, message, event={}, args={}, whisper=False):
        if self.action is None:
            log.warning('This command is not available.')
            return False

        if source.level < self.level:
            # User does not have a high enough power level to run this command
            return False

        if whisper and self.can_execute_with_whisper is False and source.level < Command.MIN_WHISPER_LEVEL and source.moderator is False:
            # This user cannot execute the command through a whisper
            return False

        if self.sub_only and source.subscriber is False and source.level < Command.BYPASS_SUB_ONLY_LEVEL and source.moderator is False:
            # User is not a sub or a moderator, and cannot use the command.
            return False

        if self.mod_only and source.moderator is False and source.level < Command.BYPASS_MOD_ONLY_LEVEL:
            # User is not a twitch moderator, or a bot moderator
            return False

        cd_modifier = 0.2 if source.level >= 500 or source.moderator is True else 1.0

        cur_time = time.time()
        time_since_last_run = (cur_time - self.last_run) / cd_modifier

        if time_since_last_run < self.delay_all and source.level < Command.BYPASS_DELAY_LEVEL:
            log.debug('Command was run {0:.2f} seconds ago, waiting...'.format(time_since_last_run))
            return False

        time_since_last_run_user = (cur_time - self.last_run_by_user.get(source.username, 0)) / cd_modifier

        if time_since_last_run_user < self.delay_user and source.level < Command.BYPASS_DELAY_LEVEL:
            log.debug('{0} ran command {1:.2f} seconds ago, waiting...'.format(source.username, time_since_last_run_user))
            return False

        if self.cost > 0 and not source.can_afford(self.cost):
            if self.notify_on_error:
                bot.whisper(source.username, 'You do not have the required {} points to execute this command. (You have {} points)'.format(self.cost, source.points_available()))
            # User does not have enough points to use the command
            return False

        if self.tokens_cost > 0 and not source.can_afford_with_tokens(self.tokens_cost):
            if self.notify_on_error:
                bot.whisper(source.username, 'You do not have the required {} tokens to execute this command. (You have {} tokens)'.format(self.tokens_cost, source.tokens))
            # User does not have enough tokens to use the command
            return False

        args.update(self.extra_args)
        if self.run_in_thread:
            log.debug('Running {} in a thread'.format(self))
            ScheduleManager.execute_now(self.run_action, args=[bot, source, message, event, args])
        else:
            self.run_action(bot, source, message, event, args)
コード例 #14
0
    def disable_showemote(self, bot, source, args, **rest):
        if not self.showemote_disabled:
            self.showemote_disabled = True
            bot.whisper(source,
                        f"Successfully disabled the show emote feature")
            ScheduleManager.execute_delayed(self.settings["disable_duration"],
                                            self.enable_showemote)
            return True

        bot.whisper(source, f"Show emote is already disabled!")
        return False
コード例 #15
0
    def run(self, bot, source, message, event={}, args={}):
        extra = self.get_extra_data(source, message, args)
        resp = self.get_response(bot, extra)

        if not resp:
            return False

        if irc.client.is_channel(event.target):
            if self.num_urlfetch_subs == 0:
                return bot.say(resp, channel=event.target)
            else:
                return ScheduleManager.execute_now(urlfetch_msg,
                                                   args=[],
                                                   kwargs={
                                                       'args': [],
                                                       'kwargs': {
                                                           'channel':
                                                           event.target
                                                       },
                                                       'method':
                                                       bot.say,
                                                       'bot':
                                                       bot,
                                                       'extra':
                                                       extra,
                                                       'message':
                                                       resp,
                                                       'num_urlfetch_subs':
                                                       self.num_urlfetch_subs,
                                                   })
        else:
            if self.num_urlfetch_subs == 0:
                return bot.whisper(source.username, resp)
            else:
                return ScheduleManager.execute_now(urlfetch_msg,
                                                   args=[],
                                                   kwargs={
                                                       'args':
                                                       [source.username],
                                                       'kwargs': {},
                                                       'method':
                                                       bot.whisper,
                                                       'bot':
                                                       bot,
                                                       'extra':
                                                       extra,
                                                       'message':
                                                       resp,
                                                       'num_urlfetch_subs':
                                                       self.num_urlfetch_subs,
                                                   })
コード例 #16
0
ファイル: user_ranks_refresh.py プロジェクト: sgaweda/troybot
 def _refresh(action_queue):
     try:
         with DBManager.create_dbapi_cursor_scope(
                 autocommit=True) as cursor:
             cursor.execute(
                 "REFRESH MATERIALIZED VIEW CONCURRENTLY user_rank")
             cursor.execute("VACUUM user_rank")
     finally:
         # Queue up the refresh in 5-6 minutes
         ScheduleManager.execute_delayed(
             UserRanksRefreshManager.delay +
             UserRanksRefreshManager._jitter(),
             lambda: action_queue.submit(UserRanksRefreshManager._refresh,
                                         action_queue),
         )
コード例 #17
0
ファイル: action.py プロジェクト: TalVivian/pajbot
 def run(self, bot, source, message, event={}, args={}):
     resp = self.get_response(bot, self.get_extra_data(source, message, args))
     if resp:
         if self.num_urlfetch_subs == 0:
             bot.whisper(source.username, resp)
         else:
             ScheduleManager.execute_now(urlfetch_msg,
                     args=[],
                     kwargs={
                         'args': [source.username],
                         'kwargs': {},
                         'method': bot.whisper,
                         'message': resp,
                         'num_urlfetch_subs': self.num_urlfetch_subs,
                         })
コード例 #18
0
ファイル: bet.py プロジェクト: metrize/troybot
    def lock_bets(self):
        self.lock_schedule = None
        if self.close_schedule:
            try:
                self.close_schedule.remove()
            except:
                pass
        self.close_schedule = None
        with DBManager.create_session_scope() as db_session:
            current_game = self.get_current_game(db_session)
            if current_game.bets_closed:
                return False

            points_by_outcome = current_game.get_points_by_outcome(db_session)
            investment_ratios = self.get_odds_ratio(points_by_outcome)
            winRatio = investment_ratios[BetGameOutcome.win]
            lossRatio = investment_ratios[BetGameOutcome.loss]

            self.bot.me(
                f"The betting for the current game has been closed! Winners can expect {winRatio} (win bettors) or {lossRatio} (loss bettors) point return on their bet"
            )
            self.bot.websocket_manager.emit(
                event="notification",
                widget_id=WIDGET_ID,
                data={
                    "message":
                    "The betting for the current game has been closed!"
                },
            )

            self.close_schedule = ScheduleManager.execute_delayed(
                15,
                self.bot.websocket_manager.emit,
                args=["bet_close_game", WIDGET_ID])
            current_game.bets_closed = True
コード例 #19
0
ファイル: bet.py プロジェクト: metrize/troybot
    def command_stop_bet(self, bot, message, **rest):
        reason = message if message else "No reason given EleGiggle"
        with DBManager.create_session_scope() as db_session:
            current_game = self.get_current_game(db_session,
                                                 with_bets=True,
                                                 with_users=True)
            for bet in current_game.bets:
                bet.user.points = User.points + bet.points
                bot.whisper(
                    bet.user,
                    f"Your {bet.points} points bet has been refunded. The reason given is: '{reason}'"
                )

                db_session.delete(bet)

            db_session.delete(current_game)

        self.spectating = False
        if self.close_schedule:
            try:
                self.close_schedule.remove()
            except:
                pass
        self.close_schedule = ScheduleManager.execute_now(
            self.bot.websocket_manager.emit,
            args=["bet_close_game", WIDGET_ID])

        bot.me("All your bets have been refunded and betting has been closed.")
コード例 #20
0
    def __init__(self, twitch_helix_api, action_queue) -> None:
        self.action_queue = action_queue
        self.streamer = StreamHelper.get_streamer()
        self.streamer_id = StreamHelper.get_streamer_id()
        self.twitch_emote_manager = TwitchEmoteManager(twitch_helix_api)
        self.ffz_emote_manager = FFZEmoteManager()
        self.bttv_emote_manager = BTTVEmoteManager()
        self.seventv_emote_manager = SevenTVEmoteManager()

        # every 1 hour
        # note: whenever emotes are refreshed (cache is saved to redis), the key is additionally set to expire
        # in one hour. This is to prevent emotes from never refreshing if the bot restarts in less than an hour.
        # (This also means that the bot will never have emotes older than 2 hours)
        ScheduleManager.execute_every(1 * 60 * 60, self.update_all_emotes)

        self.load_all_emotes()
コード例 #21
0
ファイル: trivia.py プロジェクト: wronlol/bullbot
    def command_start(self, bot, source, message, **rest):
        if self.trivia_running:
            bot.me(f"{source}, a trivia is already running")
            return

        if bot.is_online:
            bot.whisper(source,
                        "You can't start a trivia when the stream is live.")
            return

        self.trivia_running = True
        self.job = ScheduleManager.execute_every(1, self.poll_trivia)

        try:
            self.point_bounty = int(message)
            if self.point_bounty < 0:
                self.point_bounty = 0
            if source.level < 500:
                self.point_bounty = 20
        except:
            self.point_bounty = self.settings["default_point_bounty"]

        if self.point_bounty > 0:
            self.bot.safe_me(
                f"The trivia has started! {self.point_bounty} points for each right answer!"
            )
        else:
            self.bot.safe_me("The trivia has started!")

        HandlerManager.add_handler("on_message", self.on_message)
コード例 #22
0
ファイル: trivia.py プロジェクト: sgaweda/troybot
    def command_start(self, bot, source, message, **rest):
        if self.trivia_running:
            bot.safe_me(f"{source}, a trivia is already running")
            return

        self.trivia_running = True
        self.job = ScheduleManager.execute_every(1, self.poll_trivia)

        try:
            self.point_bounty = int(message)
            if self.point_bounty < 0:
                self.point_bounty = 0
            elif self.point_bounty > 50:
                self.point_bounty = 50
        except:
            self.point_bounty = self.settings["default_point_bounty"]

        if self.point_bounty > 0:
            bot.safe_me(
                f"The trivia has started! {self.point_bounty} points for each right answer!"
            )
        else:
            bot.safe_me("The trivia has started!")

        HandlerManager.add_handler("on_message", self.on_message)
コード例 #23
0
    def run(self, bot, source, message, event={}, args={}):
        extra = self.get_extra_data(source, message, args)
        resp = self.get_response(bot, extra)

        if not resp:
            return False

        if self.num_urlfetch_subs == 0:
            return bot.me(resp)
        else:
            return ScheduleManager.execute_now(urlfetch_msg,
                                               args=[],
                                               kwargs={
                                                   'args': [],
                                                   'kwargs': {},
                                                   'method':
                                                   bot.me,
                                                   'bot':
                                                   bot,
                                                   'extra':
                                                   extra,
                                                   'message':
                                                   resp,
                                                   'num_urlfetch_subs':
                                                   self.num_urlfetch_subs,
                                               })
コード例 #24
0
ファイル: duel.py プロジェクト: sgaweda/troybot
    def enable(self, bot):
        if not bot:
            return

        # We can't use bot.execute_every directly since we can't later cancel jobs created through bot.execute_every
        self.gc_job = ScheduleManager.execute_every(
            30, lambda: self.bot.execute_now(self._cancel_expired_duels))
コード例 #25
0
    def spread_points(self, gameResult):
        with DBManager.create_session_scope() as db_session:
            # What is faster? Doing it like this or with a generator afterwards?
            winners = 0
            losers = 0
            current_game = self.get_current_game(db_session, with_bets=True, with_users=True)

            current_game.outcome = gameResult
            points_by_outcome = current_game.get_points_by_outcome(db_session)
            investment_ratios = self.get_odds_ratio(points_by_outcome)
            total_winnings = 0
            total_losings = 0
            for bet in current_game.bets:
                if bet.outcome == current_game.outcome:
                    winners += 1
                    investment_ratio = investment_ratios[bet.outcome]
                    bet.profit = int(bet.points * (investment_ratio - 1))
                    bet.user.points += int(bet.points + bet.profit)
                    total_winnings += bet.profit
                    self.bot.whisper(
                        bet.user,
                        f"You bet {bet.points} points on the correct outcome and gained an extra {bet.profit} points, you now have {bet.user.points} points PogChamp",
                    )
                else:
                    losers += 1
                    bet.profit = -bet.points
                    total_losings += -bet.profit
                    self.bot.whisper(
                        bet.user,
                        f"You bet {bet.points} points on the wrong outcome, so you lost it all :( . You now have {bet.user.points} points sadKEK",
                    )

            startString = f"The game ended as a {gameResult.name}. {winners} users won an extra {total_winnings} points, while {losers} users lost {total_losings} points."

            if self.spectating:
                resultString = startString[:20] + "radiant " + startString[20:]
            else:
                resultString = startString

            # Just to make sure
            current_game.bets_closed = True
            self.spectating = False

            self.bot.websocket_manager.emit(
                event="notification", widget_id=WIDGET_ID, data={"message": resultString, "length": 8}
            )
            self.bot.me(resultString)

            db_session.flush()
            self.bot.websocket_manager.emit(event="bet_show_bets", widget_id=WIDGET_ID)
            if self.close_schedule:
                try:
                    self.close_schedule.remove()
                except:
                    pass
            self.close_schedule = ScheduleManager.execute_delayed(
                15, self.bot.websocket_manager.emit, args=["bet_close_game", WIDGET_ID]
            )
コード例 #26
0
    def enable(self, bot):
        # Web interface, nothing to do
        if not bot:
            return

        # every 10 minutes, add the chatters update to the action queue
        self.scheduled_job = ScheduleManager.execute_every(
            self.UPDATE_INTERVAL * 60,
            lambda: self.bot.action_queue.submit(self._update_chatters))
コード例 #27
0
    def __init__(self, twitch_v5_api, twitch_legacy_api, action_queue):
        self.action_queue = action_queue
        self.twitch_emote_manager = TwitchEmoteManager(twitch_v5_api, twitch_legacy_api)
        self.ffz_emote_manager = FFZEmoteManager()
        self.bttv_emote_manager = BTTVEmoteManager()

        self.epm = {}

        try:
            # every 1 hour
            # note: whenever emotes are refreshed (cache is saved to redis), the key is additionally set to expire
            # in one hour. This is to prevent emotes from never refreshing if the bot restarts in less than an hour.
            # (This also means that the bot will never have emotes older than 2 hours)
            ScheduleManager.execute_every(1 * 60 * 60, self.update_all_emotes)
        except:
            log.exception("Something went wrong trying to initialize automatic emote refresh")

        self.load_all_emotes()
コード例 #28
0
ファイル: bet.py プロジェクト: yustinuspr/bullbot
    def enable(self, bot):
        if not bot:
            return

        HandlerManager.add_handler("on_open_bets", self.start_game)
        HandlerManager.add_handler("on_lock_bets", self.automated_lock)
        HandlerManager.add_handler("on_end_bets", self.automated_end)

        self.reminder_job = ScheduleManager.execute_every(200, self.reminder_bet)
コード例 #29
0
 def on_message(self, ws, message):
     msg = json.loads(message)
     if msg["type"].lower() == "pong":
         self.sent_ping = False
     elif msg["type"].lower() == "reconnect":
         ScheduleManager.execute_now(self.reset)
     elif msg["type"].lower() == "message":
         if msg["data"][
                 "topic"] == "channel-bits-events-v2." + self.bot.streamer_user_id:
             messageR = json.loads(msg["data"]["message"])
             user_id_of_cheer = str(messageR["data"]["user_id"])
             bits_cheered = str(messageR["data"]["bits_used"])
             with DBManager.create_session_scope() as db_session:
                 user = User.find_by_id(db_session, user_id_of_cheer)
                 if user is not None:
                     HandlerManager.trigger("on_cheer",
                                            True,
                                            user=user,
                                            bits_cheered=bits_cheered)
コード例 #30
0
ファイル: action.py プロジェクト: morenoMe/pajbot
    def run(self, bot, source, message, event={}, args={}):
        extra = self.get_extra_data(source, message, args)
        resp = self.get_response(bot, extra)

        if not resp:
            return False

        if irc.client.is_channel(event.target):
            if self.num_urlfetch_subs == 0:
                return bot.say(resp, channel=event.target)

            return ScheduleManager.execute_now(
                urlfetch_msg,
                args=[],
                kwargs={
                    "args": [],
                    "kwargs": {
                        "channel": event.target
                    },
                    "method": bot.say,
                    "bot": bot,
                    "extra": extra,
                    "message": resp,
                    "num_urlfetch_subs": self.num_urlfetch_subs,
                },
            )

        if self.num_urlfetch_subs == 0:
            return bot.whisper(source, resp)

        return ScheduleManager.execute_now(
            urlfetch_msg,
            args=[],
            kwargs={
                "args": [source],
                "kwargs": {},
                "method": bot.whisper,
                "bot": bot,
                "extra": extra,
                "message": resp,
                "num_urlfetch_subs": self.num_urlfetch_subs,
            },
        )
コード例 #31
0
ファイル: action.py プロジェクト: TalVivian/pajbot
 def run(self, bot, source, message, event={}, args={}):
     resp = self.get_response(bot,
                              self.get_extra_data(source, message, args))
     if resp:
         if self.num_urlfetch_subs == 0:
             bot.whisper(source.username, resp)
         else:
             ScheduleManager.execute_now(urlfetch_msg,
                                         args=[],
                                         kwargs={
                                             'args': [source.username],
                                             'kwargs': {},
                                             'method':
                                             bot.whisper,
                                             'message':
                                             resp,
                                             'num_urlfetch_subs':
                                             self.num_urlfetch_subs,
                                         })
コード例 #32
0
    def __init__(self):
        super().__init__()

        self.job = ScheduleManager.execute_every(1, self.poll_trivia)
        self.job.pause()
        self.checkjob = ScheduleManager.execute_every(10, self.check_run)
        self.checkjob.pause()
        self.checkPaused = True

        self.jservice = False
        self.trivia_running = False
        self.manualStart = False
        self.last_question = None
        self.question = None
        self.step = 0
        self.last_step = None
        self.correct_dict = {}

        self.point_bounty = 0
コード例 #33
0
    def enable(self, bot):
        # Web interface, nothing to do
        if not bot:
            return

        HandlerManager.add_handler("on_pubnotice", self._on_pubnotice)

        # every 10 minutes, send the /vips command (response is received via _on_pubnotice)
        self.scheduled_job = ScheduleManager.execute_every(
            self.UPDATE_INTERVAL * 60,
            lambda: self.bot.execute_now(self._update_vips))
コード例 #34
0
ファイル: action.py プロジェクト: Zob3k/pajbot
    def run(self, bot, source, message, event={}, args={}):
        extra = self.get_extra_data(source, message, args)
        resp = self.get_response(bot, extra)

        if not resp:
            return False

        if irc.client.is_channel(event.target):
            if self.num_urlfetch_subs == 0:
                return bot.say(resp, channel=event.target)
            else:
                return ScheduleManager.execute_now(
                    urlfetch_msg,
                    args=[],
                    kwargs={
                        "args": [],
                        "kwargs": {"channel": event.target},
                        "method": bot.say,
                        "bot": bot,
                        "extra": extra,
                        "message": resp,
                        "num_urlfetch_subs": self.num_urlfetch_subs,
                    },
                )
        else:
            if self.num_urlfetch_subs == 0:
                return bot.whisper(source.username, resp)
            else:
                return ScheduleManager.execute_now(
                    urlfetch_msg,
                    args=[],
                    kwargs={
                        "args": [source.username],
                        "kwargs": {},
                        "method": bot.whisper,
                        "bot": bot,
                        "extra": extra,
                        "message": resp,
                        "num_urlfetch_subs": self.num_urlfetch_subs,
                    },
                )
コード例 #35
0
 def on_open(self, ws):
     log.info("Pubsub Started!")
     self.sendData({
         "type": "LISTEN",
         "data": {
             "topics":
             ["channel-bits-events-v2." + self.bot.streamer_user_id],
             "auth_token": self.token.token.access_token,
         },
     })
     self.schedule = ScheduleManager.execute_every(120,
                                                   self.check_connection)
コード例 #36
0
ファイル: emote.py プロジェクト: Nacht123/pajbot
    def __init__(self, bot):
        # this should probably not even be a dictionary
        self.bot = bot
        self.streamer = bot.streamer
        self.bttv_emote_manager = BTTVEmoteManager()
        redis = RedisManager.get()
        self.subemotes = redis.hgetall('global:emotes:twitch_subemotes')

        # Emote current EPM
        self.epm = {}

        try:
            # Update BTTV Emotes every 2 hours
            ScheduleManager.execute_every(60 * 60 * 2, self.bttv_emote_manager.update_emotes)

            # Update Twitch emotes every 3 hours
            ScheduleManager.execute_every(60 * 60 * 3, self.update_emotes)
        except:
            pass

        # Used as caching to store emotes
        self.global_emotes = []
コード例 #37
0
ファイル: trivia.py プロジェクト: pajlada/pajbot
    def __init__(self):
        super().__init__()

        self.job = ScheduleManager.execute_every(1, self.poll_trivia)
        self.job.pause()

        self.trivia_running = False
        self.last_question = None
        self.question = None
        self.step = 0
        self.last_step = None

        self.point_bounty = 0
コード例 #38
0
ファイル: action.py プロジェクト: Nacht123/pajbot
    def run(self, bot, source, message, event={}, args={}):
        resp = self.get_response(bot, self.get_extra_data(source, message, args))

        if not resp:
            return False

        if self.num_urlfetch_subs == 0:
            return bot.me(resp)
        else:
            return ScheduleManager.execute_now(urlfetch_msg,
                    args=[],
                    kwargs={
                        'args': [],
                        'kwargs': {},
                        'method': bot.me,
                        'message': resp,
                        'num_urlfetch_subs': self.num_urlfetch_subs,
                        })
コード例 #39
0
ファイル: action.py プロジェクト: nuuls/pajbot
    def run(self, bot, source, message, event={}, args={}):
        extra = self.get_extra_data(source, message, args)
        resp = self.get_response(bot, extra)

        if not resp:
            return False

        if self.num_urlfetch_subs == 0:
            return bot.whisper(source.username, resp)
        else:
            return ScheduleManager.execute_now(urlfetch_msg,
                    args=[],
                    kwargs={
                        'args': [source.username],
                        'kwargs': {},
                        'method': bot.whisper,
                        'bot': bot,
                        'extra': extra,
                        'message': resp,
                        'num_urlfetch_subs': self.num_urlfetch_subs,
                        })
コード例 #40
0
ファイル: action.py プロジェクト: Zob3k/pajbot
    def run(self, bot, source, message, event={}, args={}):
        extra = self.get_extra_data(source, message, args)
        resp = self.get_response(bot, extra)

        if not resp:
            return False

        if self.num_urlfetch_subs == 0:
            return bot.me(resp)
        else:
            return ScheduleManager.execute_now(
                urlfetch_msg,
                args=[],
                kwargs={
                    "args": [],
                    "kwargs": {},
                    "method": bot.me,
                    "bot": bot,
                    "extra": extra,
                    "message": resp,
                    "num_urlfetch_subs": self.num_urlfetch_subs,
                },
            )
コード例 #41
0
ファイル: user.py プロジェクト: Neclord9/pajbot
 def init():
     ScheduleManager.execute_every(30 * 60, UserSQLCache._clear_cache)
コード例 #42
0
ファイル: bot.py プロジェクト: jardg/pajbot
    def __init__(self, config, args=None):
        # Load various configuration variables from the given config object
        # The config object that should be passed through should
        # come from pajbot.utils.load_config
        self.load_config(config)

        # Update the database scheme if necessary using alembic
        # In case of errors, i.e. if the database is out of sync or the alembic
        # binary can't be called, we will shut down the bot.
        pajbot.utils.alembic_upgrade()

        # Actions in this queue are run in a separate thread.
        # This means actions should NOT access any database-related stuff.
        self.action_queue = ActionQueue()
        self.action_queue.start()

        self.reactor = irc.client.Reactor(self.on_connect)
        self.start_time = datetime.datetime.now()
        ActionParser.bot = self

        HandlerManager.init_handlers()

        self.socket_manager = SocketManager(self)
        self.stream_manager = StreamManager(self)

        StreamHelper.init_bot(self, self.stream_manager)
        ScheduleManager.init()

        self.users = UserManager()
        self.decks = DeckManager()
        self.module_manager = ModuleManager(self.socket_manager, bot=self).load()
        self.commands = CommandManager(
                socket_manager=self.socket_manager,
                module_manager=self.module_manager,
                bot=self).load()
        self.filters = FilterManager().reload()
        self.banphrase_manager = BanphraseManager(self).load()
        self.timer_manager = TimerManager(self).load()
        self.kvi = KVIManager()
        self.emotes = EmoteManager(self)
        self.twitter_manager = TwitterManager(self)

        HandlerManager.trigger('on_managers_loaded')

        # Reloadable managers
        self.reloadable = {
                'filters': self.filters,
                }

        # Commitable managers
        self.commitable = {
                'commands': self.commands,
                'filters': self.filters,
                'banphrases': self.banphrase_manager,
                }

        self.execute_every(10 * 60, self.commit_all)
        self.execute_every(1, self.do_tick)

        try:
            self.admin = self.config['main']['admin']
        except KeyError:
            log.warning('No admin user specified. See the [main] section in config.example.ini for its usage.')
        if self.admin:
            with self.users.get_user_context(self.admin) as user:
                user.level = 2000

        self.parse_version()

        relay_host = self.config['main'].get('relay_host', None)
        relay_password = self.config['main'].get('relay_password', None)
        if relay_host is None or relay_password is None:
            self.irc = MultiIRCManager(self)
        else:
            self.irc = SingleIRCManager(self)

        self.reactor.add_global_handler('all_events', self.irc._dispatcher, -10)

        twitch_client_id = None
        twitch_oauth = None
        if 'twitchapi' in self.config:
            twitch_client_id = self.config['twitchapi'].get('client_id', None)
            twitch_oauth = self.config['twitchapi'].get('oauth', None)

        # A client ID is required for the bot to work properly now, give an error for now
        if twitch_client_id is None:
            log.error('MISSING CLIENT ID, SET "client_id" VALUE UNDER [twitchapi] SECTION IN CONFIG FILE')

        self.twitchapi = TwitchAPI(twitch_client_id, twitch_oauth)

        self.data = {}
        self.data_cb = {}
        self.url_regex = re.compile(self.url_regex_str, re.IGNORECASE)

        self.data['broadcaster'] = self.streamer
        self.data['version'] = self.version
        self.data['version_brief'] = self.version_brief
        self.data['bot_name'] = self.nickname
        self.data_cb['status_length'] = self.c_status_length
        self.data_cb['stream_status'] = self.c_stream_status
        self.data_cb['bot_uptime'] = self.c_uptime
        self.data_cb['current_time'] = self.c_current_time

        self.silent = True if args.silent else self.silent

        if self.silent:
            log.info('Silent mode enabled')

        """
        For actions that need to access the main thread,
        we can use the mainthread_queue.
        """
        self.mainthread_queue = ActionQueue()
        self.execute_every(1, self.mainthread_queue.parse_action)

        self.websocket_manager = WebSocketManager(self)

        try:
            if self.config['twitchapi']['update_subscribers'] == '1':
                self.execute_every(30 * 60,
                                   self.action_queue.add,
                                   (self.update_subscribers_stage1, ))
        except:
            pass

        # XXX: TEMPORARY UGLY CODE
        HandlerManager.add_handler('on_user_gain_tokens', self.on_user_gain_tokens)
        HandlerManager.add_handler('send_whisper', self.whisper)
コード例 #43
0
ファイル: emote.py プロジェクト: jardg/pajbot
 def epm_incr(self, code, count):
     if code in self.epm:
         self.epm[code] += count
     else:
         self.epm[code] = count
     ScheduleManager.execute_delayed(60, self.epm_decr, args=[code, count])