コード例 #1
0
ファイル: cli.py プロジェクト: elderlabs/disco2
def disco_main(run=False):
    """
    Creates an argument parser and parses a standard set of command line arguments,
    creating a new :class:`Client`.

    Returns
    -------
    :class:`Client`
        A new Client from the provided command line arguments
    """
    from disco.client import Client, ClientConfig
    from disco.bot import Bot, BotConfig
    from disco.util.logging import setup_logging

    # Parse out all our command line arguments
    args = parser.parse_args()

    # Create the base configuration object
    if args.config:
        config = ClientConfig.from_file(args.config)
    else:
        if os.path.exists('config.json'):
            config = ClientConfig.from_file('config.json')
        elif os.path.exists('config.yaml'):
            config = ClientConfig.from_file('config.yaml')
        else:
            config = ClientConfig()

    for arg_key, config_key in six.iteritems(CONFIG_OVERRIDE_MAPPING):
        if getattr(args, arg_key) is not None:
            setattr(config, config_key, getattr(args, arg_key))

    # Setup the auto-sharder
    if args.shard_auto:
        from disco.gateway.sharder import AutoSharder
        AutoSharder(config).run()
        return

    # Setup logging based on the configured level
    setup_logging(level=getattr(logging, config.log_level.upper()))

    # Build out client object
    client = Client(config)

    # If applicable, build the bot and load plugins
    bot = None
    if args.run_bot or hasattr(config, 'bot'):
        bot_config = BotConfig(config.bot) if hasattr(config,
                                                      'bot') else BotConfig()
        if not hasattr(bot_config, 'plugins'):
            bot_config.plugins = args.plugin
        else:
            bot_config.plugins += args.plugin

        bot = Bot(client, bot_config)

    if run:
        (bot or client).run_forever()

    return bot or client
コード例 #2
0
def get_client():
    from disco.client import ClientConfig, Client
    from rowboat.config import token

    config = ClientConfig()
    config.token = token
    return Client(config)
コード例 #3
0
    def __init__(self):
        setup_logging(level=logging.WARNING)

        self.client_config = ClientConfig()
        self.client_config.token = app.config['DISCORD_BOT_TOKEN']

        self.client = Client(self.client_config)

        self.bot = Bot(self.client)
        self.bot.add_plugin(RwrsBotDiscoPlugin)
コード例 #4
0
ファイル: base.py プロジェクト: Defaulttt/mee6
    def __init__(self, **kwargs):
        self.db = redis.from_url(kwargs.get('redis_url'),
                                 decode_responses=True)

        discord_config = ClientConfig()
        discord_config.token = kwargs.get('discord_token')
        discord_client = Client(discord_config)
        self.api = discord_client.api

        self.log = logging.getLogger(self.__class__.__name__).info
コード例 #5
0
ファイル: cli.py プロジェクト: soulthreads/disco
def disco_main(run=False):
    """
    Creates an argument parser and parses a standard set of command line arguments,
    creating a new :class:`Client`.

    Returns
    -------
    :class:`Client`
        A new Client from the provided command line arguments
    """
    args = parser.parse_args()

    from disco.client import Client, ClientConfig
    from disco.bot import Bot, BotConfig
    from disco.util.token import is_valid_token
    from disco.util.logging import setup_logging

    if os.path.exists(args.config):
        config = ClientConfig.from_file(args.config)
    else:
        config = ClientConfig()

    for k, v in six.iteritems(vars(args)):
        if hasattr(config, k) and v is not None:
            setattr(config, k, v)

    if not is_valid_token(config.token):
        print('Invalid token passed')
        return

    if args.shard_auto:
        from disco.gateway.sharder import AutoSharder
        AutoSharder(config).run()
        return

    if hasattr(config, 'logging_format'):
        setup_logging(level=logging.INFO, format=config.logging_format)
    else:
        setup_logging(level=logging.INFO)

    client = Client(config)

    bot = None
    if args.run_bot or hasattr(config, 'bot'):
        bot_config = BotConfig(config.bot) if hasattr(config, 'bot') else BotConfig()
        if not hasattr(bot_config, 'plugins'):
            bot_config.plugins = args.plugin
        else:
            bot_config.plugins += args.plugin
        bot = Bot(client, bot_config)

    if run:
        (bot or client).run_forever()

    return (bot or client)
コード例 #6
0
 def __init__(self, token, channel_id):
     """Creates a new message in the given `channel_id`."""
     super(DiscordIO, self).__init__()
     config = ClientConfig()
     config.token = token
     client = Client(config)
     self.text = self.__class__.__name__
     try:
         self.message = client.api.channels_messages_create(channel_id, self.text)
     except Exception as e:
         tqdm_auto.write(str(e))
コード例 #7
0
ファイル: discord.py プロジェクト: Sazpaimon/pylink-discord-1
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if 'token' not in self.serverdata:
            raise ProtocolError("No API token defined under server settings")
        self.client_config = ClientConfig({'token': self.serverdata['token']})
        self.client = Client(self.client_config)
        self.bot_config = BotConfig()
        self.bot = Bot(self.client, self.bot_config)
        self.bot_plugin = DiscordBotPlugin(self, self.bot, self.bot_config)
        self.bot.add_plugin(self.bot_plugin)
        #setup_logging(level='DEBUG')
        self._children = {}
        self.message_queue = queue.Queue()
コード例 #8
0
ファイル: bot.py プロジェクト: ev0x/rowboat-rewrite-public
    def _on_rpc_request(self, op, data):
        log.info('RPC REQUEST: %s', op)

        if op == 'INIT' and not self.client:
            config = ClientConfig()
            config.token = data['token']
            config.state = {
                'sync_guild_members': False,
                'track_messages': False
            }
            self.client = Client(config)
            self.state = self.client.state
            self._bind_events()
        elif op == 'DISPATCH':
            self._on_dispatch(*data)
コード例 #9
0
ファイル: worker_bot.py プロジェクト: realtirey/botirey
    def __init__(self, *args, **kwargs):
        self.broker_url = config.BROKER_URL or DEFAULT_BROKER_URL
        self.redis_url = config.REDIS_URL or DEFAULT_BROKER_URL

        self.log = logging.getLogger('worker').info

        self.redis = redis.from_url(self.redis_url, decode_responses=True)
        self.log('Connected to redis database')

        discord_config = ClientConfig()
        discord_config.token = config.MEE6_TOKEN
        discord_client = Client(discord_config)
        self.api = discord_client.api

        self.listeners = []
        self.plugins = []
コード例 #10
0
    def __init__(self, *args, **kwargs):
        self.broker_url = kwargs.get('broker_url',
                                     'redis://localhost')
        self.redis_url = kwargs.get('redis_url',
                                    'redis://localhost')

        self.log = logging.getLogger('worker').info

        self.redis = redis.from_url(self.redis_url,
                                    decode_responses=True)
        self.log('Connected to redis database')

        discord_config = ClientConfig()
        discord_config.token = kwargs.get('discord_token')
        discord_client = Client(discord_config)
        self.api = discord_client.api

        self.listeners = []
        self.plugins = []
コード例 #11
0
ファイル: discord.py プロジェクト: PyLink/pylink-discord
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if 'token' not in self.serverdata:
            raise ProtocolError("No API token defined under server settings")

        client_config = ClientConfig({'token': self.serverdata['token'],
                                      'max_reconnects': 0})
        self.client = Client(client_config)

        bot_config = BotConfig()
        self.bot = Bot(self.client, bot_config)

        self.bot_plugin = DiscordBotPlugin(self, self.bot, bot_config)
        self.bot.add_plugin(self.bot_plugin)

        self._children = {}
        self.message_queue = queue.Queue()
        self.webhooks = {}
        self._message_thread = None
コード例 #12
0
    def load(self, config=None, state=None):
        super().load(config=config, state=state)

        conf = ClientConfig()
        conf.token = self.config.get('token')
        conf.max_reconnects = 0
        self.client = Client(conf)
        self.client.parent = self
        self.client.agent = self.agent

        self.bot = None
        bot_config = BotConfig()
        bot_config.commands_require_mention = False
        bot_config.commands_prefix = self.config.get('command_prefix', '.')

        bot_config.levels = self.config.get('access', {})

        bot_config.commands_level_getter = self.level_getter
        self.bot = Bot(self.client, bot_config)

        for unique_id, pconf in self.config.get('plugins').items():
            if pconf is None:
                pconf = {}

            pconf.setdefault("_autoload", True)
            pconf.setdefault("_module", unique_id)
            if not pconf["_autoload"]:
                continue

            self.bot.add_plugin_module(pconf["_module"], pconf)  #TODO: replace

        for _, plugin in self.bot.plugins.items():
            plugin.parent = self

        self.bot.agent = self.agent
        self.bot.parent = self

        self.me = self.client.api.users_me_get()
コード例 #13
0
def disco_main(run=False):
    """
    Creates an argument parser and parses a standard set of command line arguments,
    creating a new :class:`Client`.

    Returns
    -------
    :class:`Client`
        A new Client from the provided command line arguments
    """
    args = parser.parse_args()

    from disco.client import Client, ClientConfig
    from disco.bot import Bot, BotConfig
    from disco.util.token import is_valid_token
    from disco.util.logging import setup_logging

    if os.path.exists(args.config):
        config = ClientConfig.from_file(args.config)
    else:
        config = ClientConfig()

    config.manhole_enable = args.manhole
    if args.manhole_bind:
        config.manhole_bind = args.manhole_bind

    for k, v in six.iteritems(vars(args)):
        if hasattr(config, k) and v is not None:
            setattr(config, k, v)

    if not is_valid_token(config.token):
        print('Invalid token passed')
        return

    if args.shard_auto:
        from disco.gateway.sharder import AutoSharder
        AutoSharder(config).run()
        return

    # TODO: make configurable
    setup_logging(level=getattr(logging, args.log_level.upper()))

    client = Client(config)

    bot = None
    if args.run_bot or hasattr(config, 'bot'):
        bot_config = BotConfig(config.bot) if hasattr(config,
                                                      'bot') else BotConfig()
        if not hasattr(bot_config, 'plugins'):
            bot_config.plugins = args.plugin
        else:
            bot_config.plugins += args.plugin

        if args.http_bind:
            bot_config.http_enabled = True
            host, port = args.http_bind.split(':', 1)
            bot_config.http_host = host
            bot_config.http_port = int(port)

        bot = Bot(client, bot_config)

    if run:
        (bot or client).run_forever()

    return (bot or client)
コード例 #14
0
def setup_config(args):
    if os.path.exists(args.config):
        config = ClientConfig.from_file(args.config)
    else:
        config = ClientConfig()
    return config
コード例 #15
0
ファイル: __init__.py プロジェクト: ThatGuyJustin/TurtleBop
def get_client():
    from disco.client import ClientConfig, Client

    config = ClientConfig()
    config.token = bot_config.token
    return Client(config)
コード例 #16
0
from disco.bot import Plugin
from disco.client import ClientConfig, Client, APIClient
from disco.types.channel import MessageIterator
from disco.types.permissions import Permissions
from datetime import datetime

from util.encoders import MessageEncoder
from util.toCSV import toCSVLine

with open('./config.json') as file:  #Pull config variables from file
    data = json.load(file)
AUTH_TOKEN = data['token']
DEBUG = data['debug']

mConfig = ClientConfig()
mConfig.token = AUTH_TOKEN
mClient = Client(mConfig)


class ArchivePlugin(Plugin):
    @Plugin.command('ping')
    def command_ping(self, event):
        event.msg.reply('Pong!')

    @Plugin.command('archive', parser=True)
    @Plugin.parser.add_argument('--JSON',
                                help="Archive in JSON format",
                                action="store_true",
                                default=False)
    @Plugin.parser.add_argument('--CSV',
コード例 #17
0
def disco_main(run=False):
    """
    Creates an argument parser and parses a standard set of command line arguments,
    creating a new :class:`Client`.
    Returns
    -------
    :class:`Client`
        A new Client from the provided command line arguments
    """
    from disco.client import Client, ClientConfig
    from disco.bot import Bot, BotConfig
    from disco.util.logging import setup_logging, LOG_FORMAT

    from bot.base import bot

    args = bot.local.disco

    # Create the base configuration object
    if args.config:
        config = ClientConfig.from_file(args.config)
    else:
        config = ClientConfig(args.to_dict())

    for arg_key, config_key in six.iteritems(CONFIG_OVERRIDE_MAPPING):
        if getattr(args, arg_key) is not None:
            setattr(config, config_key, getattr(args, arg_key))

    # Setup the auto-sharder
    if args.shard_auto:
        from disco.gateway.sharder import AutoSharder
        AutoSharder(config).run()
        return

    # Setup logging based on the configured level

    if not os.path.exists("logs"):
        os.makedirs("logs")

    file_handler = logging.FileHandler("logs/bot.log")
    file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
    file_handler.setLevel(config.log_level.upper())
    stream_handler = logging.StreamHandler()
    setup_logging(
        handlers=(file_handler, stream_handler),
        level=getattr(logging, config.log_level.upper()),
    )

    # Build out client object
    client = Client(config)

    # If applicable, build the bot and load plugins
    bot = None
    if args.run_bot or hasattr(config, 'bot'):
        bot_config = BotConfig(config.bot.to_dict()) if hasattr(
            config, 'bot') else BotConfig()
        if not hasattr(bot_config, 'plugins'):
            bot_config.plugins = args.plugin
        else:
            bot_config.plugins += args.plugin

        bot = Bot(client, bot_config)

    if run:
        (bot or client).run_forever()

    return (bot or client)
コード例 #18
0
 def setUp(self):
     self.client = Client(ClientConfig({'config': 'TEST_TOKEN'}))
     self.bot = MockBot(self.client)