Esempio n. 1
0
    def start_quest(self):
        HandlerManager.add_handler('on_duel_complete', self.on_duel_complete)

        redis = RedisManager.get()

        self.progress = {}
        old_progress = redis.hgetall(self.progress_key)
        for user, progress in old_progress.items():
            try:
                self.progress[user.decode('utf8')] = int(progress)
            except (TypeError, ValueError):
                pass

        self.points_required = redis.get(self.points_required_key)
        try:
            self.points_required = int(self.points_required)
        except (TypeError, ValueError):
            pass
        if self.points_required is None:
            try:
                self.points_required = random.randint(self.settings['min_value'], self.settings['max_value'] + 1)
            except ValueError:
                # someone f****d up
                self.points_required = 500
            redis.set(self.points_required_key, self.points_required)
Esempio n. 2
0
    def command_start(self, **options):
        bot = options['bot']
        source = options['source']
        message = options['message']

        if self.trivia_running:
            bot.me('{}, a trivia is already running'.format(source.username_raw))
            return

        self.trivia_running = True
        self.job.resume()

        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.me('The trivia has started! {} points for each right answer!'.format(self.point_bounty))
        else:
            bot.me('The trivia has started!')

        HandlerManager.add_handler('on_message', self.on_message)
Esempio n. 3
0
    def enable(self, bot):
        self.bot = bot
        HandlerManager.add_handler('on_message', self.on_message, priority=100)
        HandlerManager.add_handler('on_commit', self.on_commit)
        if bot:
            self.run_later = bot.execute_delayed

            if 'safebrowsingapi' in bot.config['main']:
                # XXX: This should be loaded as a setting instead.
                # There needs to be a setting for settings to have them as "passwords"
                # so they're not displayed openly
                self.safeBrowsingAPI = SafeBrowsingAPI(bot.config['main']['safebrowsingapi'], bot.nickname, bot.version)
            else:
                self.safeBrowsingAPI = None

        if self.db_session is not None:
            self.db_session.commit()
            self.db_session.close()
            self.db_session = None
        self.db_session = DBManager.create_session()
        self.blacklisted_links = []
        for link in self.db_session.query(BlacklistedLink):
            self.blacklisted_links.append(link)

        self.whitelisted_links = []
        for link in self.db_session.query(WhitelistedLink):
            self.whitelisted_links.append(link)
Esempio n. 4
0
    def start_quest(self):
        HandlerManager.add_handler('on_message', self.on_message)

        redis = RedisManager.get()

        self.load_progress(redis=redis)
        self.load_data(redis=redis)
Esempio n. 5
0
    def start_quest(self):
        HandlerManager.add_handler('on_duel_complete', self.on_duel_complete)

        redis = RedisManager.get()

        self.load_progress(redis=redis)
        self.load_data(redis=redis)

        self.LIMIT = self.points_required
Esempio n. 6
0
    def enable(self, bot):
        HandlerManager.add_handler('on_message', self.on_message, priority=100)
        HandlerManager.add_handler('on_commit', self.on_commit)

        if self.db_session is not None:
            self.db_session.commit()
            self.db_session.close()
            self.db_session = None
            self.links = {}
        self.db_session = DBManager.create_session()
Esempio n. 7
0
    def start_quest(self):
        HandlerManager.add_handler('on_message', self.on_message)

        redis = RedisManager.get()

        self.load_progress(redis=redis)

        self.current_emote = redis.get(self.current_emote_key)
        if self.current_emote is None:
            # randomize an emote
            global_twitch_emotes = self.bot.emotes.get_global_emotes()
            self.current_emote = random.choice(global_twitch_emotes)
            redis.set(self.current_emote_key, self.current_emote)
        else:
            self.current_emote = self.current_emote.decode('utf8')
Esempio n. 8
0
    def start_quest(self):
        HandlerManager.add_handler('on_message', self.on_message)

        redis = RedisManager.get()

        self.progress = {}
        old_progress = redis.hgetall(self.progress_key)
        for user, progress in old_progress.items():
            try:
                self.progress[user.decode('utf8')] = int(progress)
            except (TypeError, ValueError):
                pass
        self.current_emote = redis.get(self.current_emote_key)
        if self.current_emote is None:
            # randomize an emote
            global_twitch_emotes = self.bot.emotes.get_global_emotes()
            self.current_emote = random.choice(global_twitch_emotes)
            redis.set(self.current_emote_key, self.current_emote)
        else:
            self.current_emote = self.current_emote.decode('utf8')
Esempio n. 9
0
    def start_quest(self):
        HandlerManager.add_handler('on_message', self.on_message)

        redis = RedisManager.get()

        self.progress = {}
        old_progress = redis.hgetall(self.progress_key)
        for user, progress in old_progress.items():
            try:
                self.progress[user.decode('utf8')] = int(progress)
            except (TypeError, ValueError):
                pass
        self.current_emote = redis.get(self.current_emote_key)
        if self.current_emote is None:
            # randomize an emote
            global_twitch_emotes = self.bot.emotes.get_global_emotes()
            self.current_emote = random.choice(global_twitch_emotes)
            redis.set(self.current_emote_key, self.current_emote)
        else:
            self.current_emote = self.current_emote.decode('utf8')
Esempio n. 10
0
    def start_quest(self):
        HandlerManager.add_handler("on_duel_complete", self.on_duel_complete)

        redis = RedisManager.get()

        self.load_progress(redis=redis)

        self.points_required = redis.get(self.points_required_key)
        try:
            self.points_required = int(self.points_required)
        except (TypeError, ValueError):
            pass
        if self.points_required is None:
            try:
                self.points_required = random.randint(self.settings["min_value"], self.settings["max_value"] + 1)
            except ValueError:
                # someone f****d up
                self.points_required = 500
            redis.set(self.points_required_key, self.points_required)

        self.LIMIT = self.points_required
Esempio n. 11
0
 def enable(self, bot):
     HandlerManager.add_handler('on_paid_timeout', self.on_paid_timeout)
Esempio n. 12
0
    def start_quest(self):
        HandlerManager.add_handler('on_user_win_hs_bet', self.on_user_win_hs_bet)

        redis = RedisManager.get()

        self.load_progress(redis=redis)
Esempio n. 13
0
 def enable(self, bot):
     HandlerManager.add_handler('on_pubmsg', self.on_pubmsg)
     self.bot = bot
Esempio n. 14
0
    def enable(self, bot):
        HandlerManager.add_handler('on_stream_start', self.on_stream_start)
        HandlerManager.add_handler('on_stream_stop', self.on_stream_stop)
        HandlerManager.add_handler('on_managers_loaded', self.on_managers_loaded)

        self.bot = bot
Esempio n. 15
0
    def __init__(self, config, args=None):
        self.load_config(config)
        self.last_ping = datetime.datetime.now()
        self.last_pong = datetime.datetime.now()

        self.load_default_phrases()

        self.db_session = DBManager.create_session()

        try:
            subprocess.check_call(
                ['alembic', 'upgrade', 'head'] +
                ['--tag="{0}"'.format(' '.join(sys.argv[1:]))])
        except subprocess.CalledProcessError:
            log.exception('aaaa')
            log.error(
                'Unable to call `alembic upgrade head`, this means the database could be out of date. Quitting.'
            )
            sys.exit(1)
        except PermissionError:
            log.error(
                'No permission to run `alembic upgrade head`. This means your user probably doesn\'t have execution rights on the `alembic` binary.'
            )
            log.error(
                'The error can also occur if it can\'t find `alembic` in your PATH, and instead tries to execute the alembic folder.'
            )
            sys.exit(1)
        except FileNotFoundError:
            log.error(
                'Could not found an installation of alembic. Please install alembic to continue.'
            )
            sys.exit(1)
        except:
            log.exception('Unhandled exception when calling db update')
            sys.exit(1)

        # 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.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)

        self.users = UserManager()
        self.decks = DeckManager().reload()
        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().reload()
        self.emotes = EmoteManager(self).reload()
        self.twitter_manager = TwitterManager(self).reload()
        self.duel_manager = DuelManager(self)

        HandlerManager.trigger('on_managers_loaded')

        # Reloadable managers
        self.reloadable = {
            'filters': self.filters,
            'kvi': self.kvi,
            'emotes': self.emotes,
            'twitter': self.twitter_manager,
            'decks': self.decks,
        }

        # Commitable managers
        self.commitable = {
            'commands': self.commands,
            'filters': self.filters,
            'kvi': self.kvi,
            'emotes': self.emotes,
            'twitter': self.twitter_manager,
            'decks': self.decks,
            'users': self.users,
            'banphrases': self.banphrase_manager,
        }

        self.execute_every(10 * 60, self.commit_all)
        self.execute_every(
            30, lambda: self.connection_manager.get_main_conn().ping(
                'tmi.twitch.tv'))

        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:
            self.users[self.admin].level = 2000

        self.parse_version()

        self.connection_manager = ConnectionManager(self.reactor,
                                                    self,
                                                    TMI.message_limit,
                                                    streamer=self.streamer)
        chub = self.config['main'].get('control_hub', None)
        if chub is not None:
            self.control_hub = ConnectionManager(self.reactor,
                                                 self,
                                                 TMI.message_limit,
                                                 streamer=chub,
                                                 backup_conns=1)
            log.info('start pls')
        else:
            self.control_hub = None

        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)

        self.twitchapi = TwitchAPI(twitch_client_id, twitch_oauth)

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

        self.whisper_manager = WhisperConnectionManager(
            self.reactor, self, self.streamer, TMI.whispers_message_limit,
            TMI.whispers_limit_interval)
        self.whisper_manager.start(accounts=[{
            'username':
            self.nickname,
            'oauth':
            self.password,
            'can_send_whispers':
            self.config.getboolean('main', 'add_self_as_whisper_account')
        }])

        self.ascii_timeout_duration = 120
        self.msg_length_timeout_duration = 120

        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_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.silent = True if args.silent else self.silent

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

        self.reconnection_interval = 5
        """
        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)
        """
        Update chatters every `update_chatters_interval' minutes.
        By default, this is set to run every 5 minutes.
        """
        self.execute_every(self.update_chatters_interval * 60,
                           self.action_queue.add,
                           (self.update_chatters_stage1, ))

        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)
Esempio n. 16
0
 def add_handler(self, event, handler, priority=0):
     # Leave this until we've cleaned up everywhere they're used
     HandlerManager.add_handler(event, handler, priority)
     log.warn('Use HandlerManager.add_handler instead ({})'.format(event))
Esempio n. 17
0
    def enable(self, bot):
        self.bot = bot

        HandlerManager.add_handler('on_user_sub', self.on_user_sub)
        HandlerManager.add_handler('on_user_resub', self.on_user_resub)
Esempio n. 18
0
 def add_handler(self, event, handler, priority=0):
     # Leave this until we've cleaned up everywhere they're used
     HandlerManager.add_handler(event, handler, priority)
     log.warn('Use HandlerManager.add_handler instead ({})'.format(event))
Esempio n. 19
0
 def start_quest(self):
     HandlerManager.add_handler('on_raffle_win', self.on_raffle_win)
     HandlerManager.add_handler('on_bingo_win', self.on_bingo_win)
     HandlerManager.add_handler('on_multiraffle_win',
                                self.on_multiraffle_win)
Esempio n. 20
0
 def start_quest(self):
     HandlerManager.add_handler('on_raffle_win', self.on_raffle_win)
     HandlerManager.add_handler('on_bingo_win', self.on_bingo_win)
     HandlerManager.add_handler('on_multiraffle_win', self.on_multiraffle_win)
Esempio n. 21
0
 def enable(self, bot):
     self.bot = bot
     HandlerManager.add_handler('on_message', self.on_message)
Esempio n. 22
0
 def enable(self, bot):
     HandlerManager.add_handler('on_paid_timeout', self.on_paid_timeout)
     self.bot = bot
Esempio n. 23
0
 def enable(self, bot):
     self.bot = bot
     HandlerManager.add_handler('on_message', self.on_message)
Esempio n. 24
0
    def __init__(self, config, args=None):
        self.load_config(config)
        self.last_ping = datetime.datetime.now()
        self.last_pong = datetime.datetime.now()

        self.load_default_phrases()

        self.db_session = DBManager.create_session()

        try:
            subprocess.check_call(['alembic', 'upgrade', 'head'] + ['--tag="{0}"'.format(' '.join(sys.argv[1:]))])
        except subprocess.CalledProcessError:
            log.exception('aaaa')
            log.error('Unable to call `alembic upgrade head`, this means the database could be out of date. Quitting.')
            sys.exit(1)
        except PermissionError:
            log.error('No permission to run `alembic upgrade head`. This means your user probably doesn\'t have execution rights on the `alembic` binary.')
            log.error('The error can also occur if it can\'t find `alembic` in your PATH, and instead tries to execute the alembic folder.')
            sys.exit(1)
        except FileNotFoundError:
            log.error('Could not found an installation of alembic. Please install alembic to continue.')
            sys.exit(1)
        except:
            log.exception('Unhandled exception when calling db update')
            sys.exit(1)

        # 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.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)

        self.users = UserManager()
        self.decks = DeckManager().reload()
        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().reload()
        self.emotes = EmoteManager(self).reload()
        self.twitter_manager = TwitterManager(self).reload()
        self.duel_manager = DuelManager(self)

        HandlerManager.trigger('on_managers_loaded')

        # Reloadable managers
        self.reloadable = {
                'filters': self.filters,
                'kvi': self.kvi,
                'emotes': self.emotes,
                'twitter': self.twitter_manager,
                'decks': self.decks,
                }

        # Commitable managers
        self.commitable = {
                'commands': self.commands,
                'filters': self.filters,
                'kvi': self.kvi,
                'emotes': self.emotes,
                'twitter': self.twitter_manager,
                'decks': self.decks,
                'users': self.users,
                'banphrases': self.banphrase_manager,
                }

        self.execute_every(10 * 60, self.commit_all)
        self.execute_every(30, lambda: self.connection_manager.get_main_conn().ping('tmi.twitch.tv'))

        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:
            self.users[self.admin].level = 2000

        self.parse_version()

        self.connection_manager = ConnectionManager(self.reactor, self, TMI.message_limit, streamer=self.streamer)
        chub = self.config['main'].get('control_hub', None)
        if chub is not None:
            self.control_hub = ConnectionManager(self.reactor, self, TMI.message_limit, streamer=chub, backup_conns=1)
            log.info('start pls')
        else:
            self.control_hub = None

        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)

        self.twitchapi = TwitchAPI(twitch_client_id, twitch_oauth)

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

        self.whisper_manager = WhisperConnectionManager(self.reactor, self, self.streamer, TMI.whispers_message_limit, TMI.whispers_limit_interval)
        self.whisper_manager.start(accounts=[{'username': self.nickname, 'oauth': self.password, 'can_send_whispers': self.config.getboolean('main', 'add_self_as_whisper_account')}])

        self.ascii_timeout_duration = 120
        self.msg_length_timeout_duration = 120

        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_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.silent = True if args.silent else self.silent

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

        self.reconnection_interval = 5

        """
        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)

        """
        Update chatters every `update_chatters_interval' minutes.
        By default, this is set to run every 5 minutes.
        """
        self.execute_every(self.update_chatters_interval * 60,
                           self.action_queue.add,
                           (self.update_chatters_stage1, ))

        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)
Esempio n. 25
0
    def enable(self, bot):
        HandlerManager.add_handler('on_stream_start', self.on_stream_start)
        HandlerManager.add_handler('on_stream_stop', self.on_stream_stop)
        HandlerManager.add_handler('on_managers_loaded', self.on_managers_loaded)

        self.bot = bot
Esempio n. 26
0
    def start_quest(self):
        HandlerManager.add_handler('on_duel_complete', self.on_duel_complete)

        redis = RedisManager.get()

        self.load_progress(redis=redis)