Beispiel #1
0
try:
    import plugin_plugin_manager as plugin_manager
except ImportError:
    import plugins.plugin_manager as plugin_manager

util_bot.load_file('plugins/plugin_hastebin.py')
try:
    import plugin_hastebin
except ImportError:
    from plugins.plugin_hastebin import Plugin as PluginHastebin

    plugin_hastebin: PluginHastebin

NAME = 'plot'
__meta_data__ = {'name': f'plugin_{NAME}', 'commands': ['plot']}
log = util_bot.make_log_function(NAME)


class Context:
    source_message: StandardizedMessage
    source: str


class Plot:
    image: io.BytesIO
    steps_taken: int

    def __init__(self, image, steps_taken):
        self.image = image
        self.steps_taken = steps_taken
Beispiel #2
0
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
import asyncio
import typing

import twitchirc
from twitchirc import Event

import util_bot as main
NAME = 'supibot_is_alive'
__meta_data__ = {
    'name': NAME,
    'commands': []
}
log = main.make_log_function('supibot_is_alive')


class Plugin(main.Plugin):
    def __init__(self, module, source):
        super().__init__(module, source)
        self.stop_event = asyncio.Event()
        self.task = None
        self.middleware = SupibotMiddleware(self)
        main.bot.middleware.append(self.middleware)

    @property
    def no_reload(self):
        return False

    @property
Beispiel #3
0
bot.prefix = '!'
bot.storage = storage

# noinspection PyTypeHints
bot.storage: twitchirc.JsonStorage
try:
    bot.storage.load()
except twitchirc.CannotLoadError:
    bot.storage.save()
bot.permissions.update(bot.storage['permissions'])
bot.handlers['exit'] = []
bot.storage.auto_save = False

session_scope = util_bot.session_scope_local_thread

log = util_bot.make_log_function('main')
_print = print
print = lambda *args, **kwargs: log('info', *args, **kwargs)


class UserLoadingMiddleware(twitchirc.AbstractMiddleware):
    def _perm_check(self,
                    message,
                    required_permissions,
                    perm_list,
                    enable_local_bypass=True):
        missing_permissions = []
        if message.user not in perm_list:
            missing_permissions = required_permissions
        else:
            perm_state = perm_list.get_permission_state(message)
Beispiel #4
0
async def main():
    global pubsub
    languages.load_data()
    auth = {
        Platform.TWITCH:
        (bot.storage['self_twitch_name'],
         'oauth:' + util_bot.twitch_auth.json_data['access_token'])
    }
    wait = False
    for plat in Platform:
        if plat in auth:
            continue
        if plat.name.casefold() in util_bot.other_platform_auth:
            auth[plat] = util_bot.other_platform_auth[plat.name.casefold()]
        else:
            log(
                'warn',
                f'Failed to load auth for {plat.name} from auth file. Key: {plat.name.casefold()!r}'
            )
            wait = True
    if not auth:
        log('err', 'No platform authentication found')
        log('err', 'Exiting')
        return

    if wait:
        print('Please wait 5 seconds')
        time.sleep(5)

    await bot.init_clients(auth)
    bot.clients[Platform.TWITCH].connection.middleware.append(
        UserStateCapturingMiddleware())
    bot.username = bot.storage['self_twitch_name']

    if 'self_id' in bot.storage.data:
        uid = bot.storage['self_id']
    else:
        try:
            uid = util_bot.twitch_auth.new_api.get_users(
                login=bot.username.lower())[0].json()['data'][0]['id']
        except KeyError:
            util_bot.twitch_auth.refresh()
            util_bot.twitch_auth.save()
            uid = util_bot.twitch_auth.new_api.get_users(
                login=bot.username.lower())[0].json()['data'][0]['id']
        bot.storage['self_id'] = uid

    await init_server(grpc_listen_addresses)
    await bot.aconnect()
    bot.cap_reqs(False)

    for i in bot.storage['channels']:
        if i in bot.channels_connected:
            log('info', f'Skipping joining channel: {i}: Already connected.')
            continue
        await bot.join(i)

    if prog_args.restart_from:
        msg = twitchirc.ChannelMessage(
            user='******',
            channel=prog_args.restart_from[1],
            text=(f'@{prog_args.restart_from[0]} Restart OK. (debug)'
                  if prog_args.debug else
                  f'@{prog_args.restart_from[0]} Restart OK.'))
        msg.outgoing = True

        def _send_restart_message(*a):
            del a
            bot.send(msg)
            bot.flush_queue(1000)

        bot.schedule_event(1, 15, _send_restart_message, (), {})

    pubsub = await init_pubsub(util_bot.twitch_auth.new_api.auth.token)

    temp = util_bot.make_log_function('pubsub')
    pubsub.log_function = lambda *text, **kwargs: temp('debug', *text, **kwargs
                                                       )

    pubsub.listen([f'chat_moderator_actions.{uid}.{uid}'])
    bot.pubsub = pubsub
    bot.middleware.append(pubsub_middleware)
    for i in bot.channels_connected:
        pubsub_middleware.join(
            twitchirc.Event('join', {'channel': i},
                            bot,
                            cancelable=False,
                            has_result=False))

    await bot.join(bot.username.lower())

    futures = []
    log('info', 'Spam async inits')
    for plugin in util_bot.plugins.values():
        log('info', f'Call async init for {plugin}')
        futures.append(asyncio.create_task(plugin.async_init()))

    async_init_time = 5.0

    _, pending = await asyncio.wait(futures,
                                    timeout=async_init_time,
                                    return_when=asyncio.ALL_COMPLETED)
    # wait for every plugin to initialize before proceeding
    if pending:
        log(
            'err',
            f'Waiting for async inits timed out after {async_init_time} seconds. '
            f'Assuming waiting longer will not help, exiting.')

        plugin_objects = list(util_bot.plugins.values())
        table_data = [('State', 'Plugin name', 'Path')]
        for index, fut in enumerate(futures):
            fut: asyncio.Future
            plugin = plugin_objects[index]  # order should be the same.
            done = 'done' if fut.done() else 'TIMED OUT'

            table_data.append((done, plugin.name, plugin.source))
        table = ''
        cols = 3

        # calculate maximum length of elements for each row
        col_max = [
            len(max(table_data, key=lambda o: len(o[col_id]))[col_id])
            for col_id in range(cols)
        ]

        for row in table_data:
            for col_id, col in enumerate(row):
                table += col
                _print(col_max[col_id], repr(col), len(col))
                table += (col_max[col_id] - len(col) + 1) * ' '
            table += '\n'
        _print(table)
        log('warn', table)

        raise TimeoutError('Waiting for async inits timed out')
    log('warn', 'async inits done')
    try:
        done, pending = await asyncio.wait({bot.arun(), pubsub.task},
                                           return_when=asyncio.FIRST_COMPLETED)
    except KeyboardInterrupt:
        await bot.stop()
        return
    for j in done:
        await j  # retrieve any exceptions
Beispiel #5
0
import copy
import time
import typing
from typing import Dict

import regex
from twitchirc import Event
import twitchirc

from plugins.utils import arg_parser
import util_bot as main
from util_bot.clients.twitch import convert_twitchirc_to_standarized

NAME = 'pipes'
__meta_data__ = {'name': f'plugin_{NAME}', 'commands': []}
log = main.make_log_function(NAME)


class PipeWhisperMessage(main.StandardizedWhisperMessage):
    def __init__(self,
                 user_from,
                 user_to,
                 text,
                 platform,
                 flags,
                 outgoing=False,
                 pipe_id=None):
        super().__init__(
            user_from=user_from,
            user_to=user_to,
            text=text,