本文整理汇总了Python中pajbot.actions.ActionQueue.start方法的典型用法代码示例。如果您正苦于以下问题:Python ActionQueue.start方法的具体用法?Python ActionQueue.start怎么用?Python ActionQueue.start使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pajbot.actions.ActionQueue
的用法示例。
在下文中一共展示了ActionQueue.start方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_args
# 需要导入模块: from pajbot.actions import ActionQueue [as 别名]
# 或者: from pajbot.actions.ActionQueue import start [as 别名]
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()
#.........这里部分代码省略.........
示例2: LinkCheckerModule
# 需要导入模块: from pajbot.actions import ActionQueue [as 别名]
# 或者: from pajbot.actions.ActionQueue import start [as 别名]
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
#.........这里部分代码省略.........
示例3: LinkCheckerModule
# 需要导入模块: from pajbot.actions import ActionQueue [as 别名]
# 或者: from pajbot.actions.ActionQueue import start [as 别名]
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:
#.........这里部分代码省略.........
示例4: MathModule
# 需要导入模块: from pajbot.actions import ActionQueue [as 别名]
# 或者: from pajbot.actions.ActionQueue import start [as 别名]
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)
示例5: MathModule
# 需要导入模块: from pajbot.actions import ActionQueue [as 别名]
# 或者: from pajbot.actions.ActionQueue import start [as 别名]
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)
示例6: FollowAgeModule
# 需要导入模块: from pajbot.actions import ActionQueue [as 别名]
# 或者: from pajbot.actions.ActionQueue import start [as 别名]
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,
#.........这里部分代码省略.........
示例7: MathModule
# 需要导入模块: from pajbot.actions import ActionQueue [as 别名]
# 或者: from pajbot.actions.ActionQueue import start [as 别名]
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)
示例8: parse_args
# 需要导入模块: from pajbot.actions import ActionQueue [as 别名]
# 或者: from pajbot.actions.ActionQueue import start [as 别名]
#.........这里部分代码省略.........
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 = {
'filters': self.filters,