• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python actions.ActionQueue类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pajbot.actions.ActionQueue的典型用法代码示例。如果您正苦于以下问题:Python ActionQueue类的具体用法?Python ActionQueue怎么用?Python ActionQueue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ActionQueue类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self):
        super().__init__()
        self.db_session = None
        self.links = {}

        self.blacklisted_links = []
        self.whitelisted_links = []

        self.cache = LinkCheckerCache()  # cache[url] = True means url is safe, False means the link is bad

        self.action_queue = ActionQueue()
        self.action_queue.start()
开发者ID:ManikDV,项目名称:pajbot,代码行数:12,代码来源:linkchecker.py


示例2: parse_args

class Bot:
    """
    Main class for the twitch bot
    """

    version = '1.30'
    date_fmt = '%H:%M'
    admin = None
    url_regex_str = r'\(?(?:(http|https):\/\/)?(?:((?:[^\W\s]|\.|-|[:]{1})+)@{1})?((?:www.)?(?:[^\W\s]|\.|-)+[\.][^\W\s]{2,4}|localhost(?=\/)|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d*))?([\/]?[^\s\?]*[\/]{1})*(?:\/?([^\s\n\?\[\]\{\}\#]*(?:(?=\.)){1}|[^\s\n\?\[\]\{\}\.\#]*)?([\.]{1}[^\s\?\#]*)?)?(?:\?{1}([^\s\n\#\[\]]*))?([\#][^\s\n]*)?\)?'

    last_ping = datetime.datetime.now()
    last_pong = datetime.datetime.now()

    def parse_args():
        parser = argparse.ArgumentParser()
        parser.add_argument('--config', '-c',
                            default='config.ini',
                            help='Specify which config file to use '
                                    '(default: config.ini)')
        parser.add_argument('--silent',
                            action='count',
                            help='Decides whether the bot should be '
                            'silent or not')
        # TODO: Add a log level argument.

        return parser.parse_args()

    def load_config(self, config):
        self.config = config

        self.domain = config['web'].get('domain', 'localhost')

        self.nickname = config['main'].get('nickname', 'pajbot')
        self.password = config['main'].get('password', 'abcdef')

        self.timezone = config['main'].get('timezone', 'UTC')

        self.trusted_mods = config.getboolean('main', 'trusted_mods')

        TimeManager.init_timezone(self.timezone)

        if 'streamer' in config['main']:
            self.streamer = config['main']['streamer']
            self.channel = '#' + self.streamer
        elif 'target' in config['main']:
            self.channel = config['main']['target']
            self.streamer = self.channel[1:]

        self.wolfram = None
        if 'wolfram' in config['main']:
            try:
                import wolframalpha
                self.wolfram = wolframalpha.Client(config['main']['wolfram'])
            except ImportError:
                pass

        self.silent = False
        self.dev = False

        if 'flags' in config:
            self.silent = True if 'silent' in config['flags'] and config['flags']['silent'] == '1' else self.silent
            self.dev = True if 'dev' in config['flags'] and config['flags']['dev'] == '1' else self.dev

        DBManager.init(self.config['main']['db'])

        redis_options = {}
        if 'redis' in config:
            redis_options = config._sections['redis']

        RedisManager.init(**redis_options)

    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()
#.........这里部分代码省略.........
开发者ID:jardg,项目名称:pajbot,代码行数:101,代码来源:bot.py


示例3: __init__

    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
#.........这里部分代码省略.........
开发者ID:jardg,项目名称:pajbot,代码行数:101,代码来源:bot.py


示例4: LinkCheckerModule

class LinkCheckerModule(BaseModule):

    ID = __name__.split('.')[-1]
    NAME = 'Link Checker'
    DESCRIPTION = 'Checks links if they\'re bad'
    ENABLED_DEFAULT = True
    CATEGORY = 'Filter'
    SETTINGS = [
            ModuleSetting(
                key='ban_pleb_links',
                label='Disallow links from non-subscribers',
                type='boolean',
                required=True,
                default=False)
            ]

    def __init__(self):
        super().__init__()
        self.db_session = None
        self.links = {}

        self.blacklisted_links = []
        self.whitelisted_links = []

        self.cache = LinkCheckerCache()  # cache[url] = True means url is safe, False means the link is bad

        self.action_queue = ActionQueue()
        self.action_queue.start()

    def enable(self, bot):
        self.bot = bot
        pajbot.managers.handler.HandlerManager.add_handler('on_message', self.on_message, priority=100)
        pajbot.managers.handler.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)

    def disable(self, bot):
        pajbot.managers.handler.HandlerManager.remove_handler('on_message', self.on_message)
        pajbot.managers.handler.HandlerManager.remove_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.blacklisted_links = []
            self.whitelisted_links = []

    def reload(self):

        log.info('Loaded {0} bad links and {1} good links'.format(len(self.blacklisted_links), len(self.whitelisted_links)))
        return self

    super_whitelist = ['pajlada.se', 'pajlada.com', 'forsen.tv', 'pajbot.com']

    def on_message(self, source, message, emotes, whisper, urls, event):
        if not whisper and source.level < 500 and source.moderator is False:
            if self.settings['ban_pleb_links'] is True and source.subscriber is False and len(urls) > 0:
                # Check if the links are in our super-whitelist. i.e. on the pajlada.se domain o forsen.tv
                for url in urls:
                    parsed_url = Url(url)
                    if len(parsed_url.parsed.netloc.split('.')) < 2:
                        continue
                    whitelisted = False
                    for whitelist in self.super_whitelist:
                        if is_subdomain(parsed_url.parsed.netloc, whitelist):
                            whitelisted = True
                            break
                    if whitelisted is False:
                        self.bot.timeout(source.username, 30, reason='Non-subs cannot post links')
                        if source.minutes_in_chat_online > 60:
                            self.bot.whisper(source.username, 'You cannot post non-verified links in chat if you\'re not a subscriber.')
                        return False

            for url in urls:
                # Action which will be taken when a bad link is found
                action = Action(self.bot.timeout, args=[source.username, 20], kwargs={'reason': 'Banned link'})
                # First we perform a basic check
                if self.simple_check(url, action) == self.RET_FURTHER_ANALYSIS:
                    # If the basic check returns no relevant data, we queue up a proper check on the URL
#.........这里部分代码省略.........
开发者ID:Neclord9,项目名称:pajbot,代码行数:101,代码来源:linkchecker.py


示例5: LinkCheckerModule

class LinkCheckerModule(BaseModule):

    ID = __name__.split('.')[-1]
    NAME = 'Link Checker'
    DESCRIPTION = 'Checks links if they\'re bad'
    ENABLED_DEFAULT = True
    SETTINGS = []

    def __init__(self):
        super().__init__()
        self.db_session = None
        self.links = {}

        self.blacklisted_links = []
        self.whitelisted_links = []

        self.cache = LinkCheckerCache()  # cache[url] = True means url is safe, False means the link is bad

        self.action_queue = ActionQueue()
        self.action_queue.start()

    def enable(self, bot):
        self.bot = bot
        if bot:
            bot.add_handler('on_message', self.on_message, priority=100)
            bot.add_handler('on_commit', self.on_commit)
            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)

    def disable(self, bot):
        if bot:
            bot.remove_handler('on_message', self.on_message)
            bot.remove_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.blacklisted_links = []
            self.whitelisted_links = []

    def reload(self):

        log.info('Loaded {0} bad links and {1} good links'.format(len(self.blacklisted_links), len(self.whitelisted_links)))
        return self

    def on_message(self, source, message, emotes, whisper, urls):
        if not whisper and source.level < 500 and source.moderator is False:
            for url in urls:
                # Action which will be taken when a bad link is found
                action = Action(self.bot.timeout, args=[source.username, 20])
                # First we perform a basic check
                if self.simple_check(url, action) == self.RET_FURTHER_ANALYSIS:
                    # If the basic check returns no relevant data, we queue up a proper check on the URL
                    self.action_queue.add(self.check_url, args=[url, action])

    def on_commit(self):
        if self.db_session is not None:
            self.db_session.commit()

    def delete_from_cache(self, url):
        if url in self.cache:
            log.debug("LinkChecker: Removing url {0} from cache".format(url))
            del self.cache[url]

    def cache_url(self, url, safe):
        if url in self.cache and self.cache[url] == safe:
            return

        log.debug("LinkChecker: Caching url {0} as {1}".format(url, 'SAFE' if safe is True else 'UNSAFE'))
        self.cache[url] = safe
        self.run_later(20, self.delete_from_cache, (url, ))

    def counteract_bad_url(self, url, action=None, want_to_cache=True, want_to_blacklist=True):
        log.debug("LinkChecker: BAD URL FOUND {0}".format(url.url))
        if action:
            action.run()
        if want_to_cache:
            self.cache_url(url.url, False)
        if want_to_blacklist:
#.........这里部分代码省略.........
开发者ID:ManikDV,项目名称:pajbot,代码行数:101,代码来源:linkchecker.py


示例6: MathModule

class MathModule(BaseModule):

    ID = __name__.split('.')[-1]
    NAME = 'Math'
    DESCRIPTION = 'Adds a !math command for simple arithmetic'
    CATEGORY = 'Feature'

    SETTINGS = [
            ModuleSetting(
                key='online_global_cd',
                label='Global cooldown (seconds)',
                type='number',
                required=True,
                placeholder='',
                default=2,
                constraints={
                    'min_value': 0,
                    'max_value': 120,
                    }),
            ModuleSetting(
                key='online_user_cd',
                label='Per-user cooldown (seconds)',
                type='number',
                required=True,
                placeholder='',
                default=6,
                constraints={
                    'min_value': 0,
                    'max_value': 240,
                    }),
            ]

    def __init__(self):
        super().__init__()
        self.action_queue = ActionQueue()
        self.action_queue.start()

    def load_commands(self, **options):
        self.commands['math'] = pajbot.models.command.Command.raw_command(self.math,
                delay_all=self.settings['online_global_cd'],
                delay_user=self.settings['online_user_cd'],
                description='Calculate some simple math',
                examples=[
                    ],
                )

    def do_math(self, bot, source, message):
        expr_res = None
        with time_limit(1):
            try:
                expr_res = PBMath.eval_expr(''.join(message))
            except OverflowError:
                # Result is too big
                pass
            except KeyError:
                # Something wrong with the operator
                pass
            except TypeError:
                # Something wrong with the evaluation
                pass
            except SyntaxError:
                # Something invalid was passed through message
                pass
            except pajbot.exc.TimeoutException:
                # took longer than 1 second
                pass
            except:
                log.exception('Uncaught exception in Math module')

        if expr_res is None:
            return False

        emote = 'Kappa'
        try:
            if int(expr_res) == 69 or expr_res == 69.69:
                emote = 'Kreygasm'
            elif int(expr_res) == 420:
                emote = 'CiGrip'
        except:
            pass

        bot.say('{}, {} {}'.format(source.username_raw, expr_res, emote))

    def math(self, **options):
        bot = options['bot']
        source = options['source']
        message = options['message']

        if source.username == 'karl_kons':
            bot.say('{}, 8 Kappa'.format(source.username_raw))
            return True

        if message:
            message = message.replace('pi', str(math.pi))
            message = message.replace('e', str(math.e))
            message = message.replace('π', str(math.pi))
            message = message.replace('^', '**')
            message = message.replace(',', '.')

            self.do_math(bot, source, message)
开发者ID:Neclord9,项目名称:pajbot,代码行数:100,代码来源:math.py


示例7: __init__

 def __init__(self):
     super().__init__()
     self.action_queue = ActionQueue()
     self.action_queue.start()
开发者ID:Neclord9,项目名称:pajbot,代码行数:4,代码来源:math.py


示例8: MathModule

class MathModule(BaseModule):

    ID = __name__.split('.')[-1]
    NAME = 'Math'
    DESCRIPTION = 'Adds a !math command for simple arithmetic'

    def __init__(self):
        super().__init__()
        self.action_queue = ActionQueue()
        self.action_queue.start()

    def load_commands(self, **options):
        # TODO: Have delay modifiable in settings

        self.commands['math'] = Command.raw_command(self.math,
                delay_all=2,
                delay_user=6,
                description='Calculate some simple math',
                examples=[
                    ],
                )

    def do_math(self, bot, source, message):
        expr_res = None
        with time_limit(1):
            try:
                expr_res = PBMath.eval_expr(''.join(message))
            except OverflowError:
                # Result is too big
                pass
            except KeyError:
                # Something wrong with the operator
                pass
            except TypeError:
                # Something wrong with the evaluation
                pass
            except SyntaxError:
                # Something invalid was passed through message
                pass
            except TimeoutException:
                # took longer than 1 second
                pass
            except:
                log.exception('Uncaught exception in Math module')

        if expr_res is None:
            return False

        emote = 'Kappa'
        try:
            if int(expr_res) == 69 or expr_res == 69.69:
                emote = 'Kreygasm'
            elif int(expr_res) == 420:
                emote = 'CiGrip'
        except:
            pass

        bot.say('{}, {} {}'.format(source.username_raw, expr_res, emote))

    def math(self, **options):
        bot = options['bot']
        source = options['source']
        message = options['message']

        if source.username == 'karl_kons':
            bot.say('{}, 8 Kappa'.format(source.username_raw))
            return True

        if message:
            message = message.replace('pi', str(math.pi))
            message = message.replace('e', str(math.e))
            message = message.replace('π', str(math.pi))
            message = message.replace('^', '**')
            message = message.replace(',', '.')

            self.do_math(bot, source, message)
开发者ID:ManikDV,项目名称:pajbot,代码行数:76,代码来源:math.py


示例9: FollowAgeModule

class FollowAgeModule(BaseModule):

    ID = __name__.split('.')[-1]
    NAME = 'Follow age'
    DESCRIPTION = 'Makes two commands available: !followage and !followsince'
    CATEGORY = 'Feature'

    def __init__(self):
        super().__init__()
        self.action_queue = ActionQueue()
        self.action_queue.start()

    def load_commands(self, **options):
        # TODO: Have delay modifiable in settings

        self.commands['followage'] = pajbot.models.command.Command.raw_command(self.follow_age,
                delay_all=4,
                delay_user=8,
                description='Check your or someone elses follow age for a channel',
                examples=[
                    pajbot.models.command.CommandExample(None, 'Check your own follow age',
                        chat='user:!followage\n'
                        'bot:pajlada, you have been following Karl_Kons for 4 months and 24 days',
                        description='Check how long you have been following the current streamer (Karl_Kons in this case)').parse(),
                    pajbot.models.command.CommandExample(None, 'Check someone elses follow age',
                        chat='user:!followage NightNacht\n'
                        'bot:pajlada, NightNacht has been following Karl_Kons for 5 months and 4 days',
                        description='Check how long any user has been following the current streamer (Karl_Kons in this case)').parse(),
                    pajbot.models.command.CommandExample(None, 'Check someones follow age for a certain streamer',
                        chat='user:!followage NightNacht forsenlol\n'
                        'bot:pajlada, NightNacht has been following forsenlol for 1 year and 4 months',
                        description='Check how long NightNacht has been following forsenlol').parse(),
                    pajbot.models.command.CommandExample(None, 'Check your own follow age for a certain streamer',
                        chat='user:!followage pajlada forsenlol\n'
                        'bot:pajlada, you have been following forsenlol for 1 year and 3 months',
                        description='Check how long you have been following forsenlol').parse(),
                    ],
                )

        self.commands['followsince'] = pajbot.models.command.Command.raw_command(self.follow_since,
                delay_all=4,
                delay_user=8,
                description='Check from when you or someone else first followed a channel',
                examples=[
                    pajbot.models.command.CommandExample(None, 'Check your own follow since',
                        chat='user:!followsince\n'
                        'bot:pajlada, you have been following Karl_Kons since 04 March 2015, 07:02:01 UTC',
                        description='Check when you first followed the current streamer (Karl_Kons in this case)').parse(),
                    pajbot.models.command.CommandExample(None, 'Check someone elses follow since',
                        chat='user:!followsince NightNacht\n'
                        'bot:pajlada, NightNacht has been following Karl_Kons since 03 July 2014, 04:12:42 UTC',
                        description='Check when NightNacht first followed the current streamer (Karl_Kons in this case)').parse(),
                    pajbot.models.command.CommandExample(None, 'Check someone elses follow since for another streamer',
                        chat='user:!followsince NightNacht forsenlol\n'
                        'bot:pajlada, NightNacht has been following forsenlol since 13 June 2013, 13:10:51 UTC',
                        description='Check when NightNacht first followed the given streamer (forsenlol)').parse(),
                    pajbot.models.command.CommandExample(None, 'Check your follow since for another streamer',
                        chat='user:!followsince pajlada forsenlol\n'
                        'bot:pajlada, you have been following forsenlol since 16 December 1990, 03:06:51 UTC',
                        description='Check when you first followed the given streamer (forsenlol)').parse(),
                    ],
                )

    def check_follow_age(self, bot, source, username, streamer):
        streamer = bot.streamer if streamer is None else streamer.lower()
        age = bot.twitchapi.get_follow_relationship(username, streamer)
        if source.username == username:
            if age is False:
                bot.say('{}, you are not following {}'.format(source.username_raw, streamer))
            else:
                bot.say('{}, you have been following {} for {}'.format(source.username_raw, streamer, time_since(datetime.datetime.now().timestamp() - age.timestamp(), 0)))
        else:
            if age is False:
                bot.say('{}, {} is not following {}'.format(source.username_raw, username, streamer))
            else:
                bot.say('{}, {} has been following {} for {}'.format(
                    source.username_raw,
                    username,
                    streamer,
                    time_since(datetime.datetime.now().timestamp() - age.timestamp(), 0)))

    def check_follow_since(self, bot, source, username, streamer):
        streamer = bot.streamer if streamer is None else streamer.lower()
        follow_since = bot.twitchapi.get_follow_relationship(username, streamer)
        if source.username == username:
            if follow_since is False:
                bot.say('{}, you are not following {}'.format(source.username_raw, streamer))
            else:
                bot.say('{}, you have been following {} since {} UTC'.format(
                    source.username_raw,
                    streamer,
                    follow_since.strftime('%d %B %Y, %X')))
        else:
            if follow_since is False:
                bot.say('{}, {} is not following {}'.format(source.username_raw, username, streamer))
            else:
                bot.say('{}, {} has been following {} since {} UTC'.format(
                    source.username_raw,
                    username,
                    streamer,
#.........这里部分代码省略.........
开发者ID:nuuls,项目名称:pajbot,代码行数:101,代码来源:followage.py


示例10: MathModule

class MathModule(BaseModule):

    ID = __name__.split(".")[-1]
    NAME = "Math"
    DESCRIPTION = "Adds a !math command for simple arithmetic"

    SETTINGS = [
        ModuleSetting(
            key="online_global_cd",
            label="Global cooldown (seconds)",
            type="number",
            required=True,
            placeholder="",
            default=2,
            constraints={"min_value": 0, "max_value": 120},
        ),
        ModuleSetting(
            key="online_user_cd",
            label="Per-user cooldown (seconds)",
            type="number",
            required=True,
            placeholder="",
            default=6,
            constraints={"min_value": 0, "max_value": 240},
        ),
    ]

    def __init__(self):
        super().__init__()
        self.action_queue = ActionQueue()
        self.action_queue.start()

    def load_commands(self, **options):
        self.commands["math"] = Command.raw_command(
            self.math,
            delay_all=self.settings["online_global_cd"],
            delay_user=self.settings["online_user_cd"],
            description="Calculate some simple math",
            examples=[],
        )

    def do_math(self, bot, source, message):
        expr_res = None
        with time_limit(1):
            try:
                expr_res = PBMath.eval_expr("".join(message))
            except OverflowError:
                # Result is too big
                pass
            except KeyError:
                # Something wrong with the operator
                pass
            except TypeError:
                # Something wrong with the evaluation
                pass
            except SyntaxError:
                # Something invalid was passed through message
                pass
            except TimeoutException:
                # took longer than 1 second
                pass
            except:
                log.exception("Uncaught exception in Math module")

        if expr_res is None:
            return False

        emote = "Kappa"
        try:
            if int(expr_res) == 69 or expr_res == 69.69:
                emote = "Kreygasm"
            elif int(expr_res) == 420:
                emote = "CiGrip"
        except:
            pass

        bot.say("{}, {} {}".format(source.username_raw, expr_res, emote))

    def math(self, **options):
        bot = options["bot"]
        source = options["source"]
        message = options["message"]

        if source.username == "karl_kons":
            bot.say("{}, 8 Kappa".format(source.username_raw))
            return True

        if message:
            message = message.replace("pi", str(math.pi))
            message = message.replace("e", str(math.e))
            message = message.replace("π", str(math.pi))
            message = message.replace("^", "**")
            message = message.replace(",", ".")

            self.do_math(bot, source, message)
开发者ID:Cophy08,项目名称:pajbot,代码行数:95,代码来源:math.py


示例11: parse_args


#.........这里部分代码省略.........
            log.info(config._sections['redis'])
            redis_options = config._sections['redis']

        RedisManager.init(**redis_options)

    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 = {
开发者ID:kyroskoh,项目名称:pajbot,代码行数:67,代码来源:bot.py


示例12: __init__

    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

#.........这里部分代码省略.........
开发者ID:kyroskoh,项目名称:pajbot,代码行数:101,代码来源:bot.py



注:本文中的pajbot.actions.ActionQueue类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python managers.AdminLogManager类代码示例发布时间:2022-05-27
下一篇:
Python pair.list函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap