Example #1
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

    # 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
Example #2
0
def run_bot():
    from gevent import monkey
    monkey.patch_all()

    #patch_MessageTable()

    parser = argparse.ArgumentParser()
    parser.add_argument('--token', help="discord api auth token", default=None)
    parser.add_argument('--log-level', help='log level', default="INFO")

    if not os.path.exists(CONFIG_FILE):
        print("%s missing, pls fix" % CONFIG_FILE)
        exit()

    config = ClientConfig.from_file(CONFIG_FILE)

    args = parser.parse_args()

    if args.log_level:
        setup_logging(level=getattr(logging, args.log_level.upper()))

    if args.token is not None:
        config.token = args.token

    if not is_valid_token(config.token):
        print("the token '%s' isn't valid" % config.token)
        exit()

    client = Client(config)

    bot_config = BotConfig(config.bot)

    # get plugin files
    # todo: support multilevel nested plugins
    _, _, filenames = next(os.walk("plugins"), (None, None, []))
    filenames.remove("__init__.py")

    # convert plugins from ayylmao.py to plugins.ayylmao
    filenames = ["plugins.%s" % os.path.splitext(p)[0] for p in filenames]

    # remove disabled plugins from plugin array
    filenames = [p for p in filenames if p not in config.disabled_plugins]

    bot_config.plugins = filenames

    if len(bot_config.plugins) > 0:
        print("discovered plugins:")

        for p in bot_config.plugins:
            print(" - %s" % p)
    else:
        print("no plugins found")

    bot = Bot(client, bot_config)

    bot.run_forever()
Example #3
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()

    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)
def setup_bot(args, client, config):
    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_config.commands_require_mention = False

    bot = Bot(client, bot_config)
    return bot, bot_config
def setup_bot(args, client, config):
    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_config.commands_require_mention = False

    bot = Bot(client, bot_config)
    return bot, bot_config
Example #6
0
 def start_disco(self):
     setup_logging(level=logging.DEBUG)
     self.config = ClientConfig.from_file("./secrets/discord.json")
     self.client = Client(self.config)
     self.bot_config = BotConfig(self.config.bot)
     self.bot = Bot(self.client, self.bot_config)
     self.bot.main_process_recv = self.main_process_recv
     return self.bot.client.run()
Example #7
0
def run_shard(config, shard_id, pipe):
    setup_logging(
        level=logging.INFO,
        format='{} [%(levelname)s] %(asctime)s - %(name)s:%(lineno)d - %(message)s'.format(shard_id)
    )

    config.shard_id = shard_id
    client = Client(config)
    bot = Bot(client, BotConfig(config.bot))
    bot.sharder = GIPCProxy(bot, pipe)
    bot.shards = ShardHelper(config.shard_count, bot)
    bot.run_forever()
Example #8
0
    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()
Example #9
0
    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
Example #10
0
    def createBot(self):
        # Create the base configuration object
        config = ClientConfig.from_file(
            '/home/nathan/PYTHON/WORKING-USE-THIS!!!/src-3.0/config/discordconfig.json'
        )

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

        # Build our client object
        self.client = Client(config)

        # If applicable, build the bot and load plugins
        bot_config = BotConfig(config.bot)
        self.bot = Bot(self.client, bot_config)
        #self.bot.add_plugin(TutPlugin, config) # This is how we would add plugins, TugPlugin would be a class

        self.apiClient = self.bot.client.api
        self.startMainBotLoop()

        (self.bot or self.client).run_forever()
Example #11
0
def disco_main():
    """
    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()

    config = ClientConfig.from_file('config.yaml')
    config.token = credentials['discord_login']['beta']
    if args.log_level:
        config.log_level = args.log_level

    setup_logging(level=getattr(logging, config.log_level.upper()))

    bot_config = BotConfig(config.bot)
    bot = ConnectBot(Client(config), bot_config)
    bot.run_forever()
Example #12
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 gevent import monkey

    monkey.patch_all()

    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

    config = ClientConfig.from_file('config.yaml')

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

    setup_logging(level='WARN')

    client = Client(config)

    bot_config = BotConfig(config.bot)

    bot = Bot(client, bot_config)
    from db import ChartingDao
    bot.db = ChartingDao()

    bot.run_forever()
    return bot
Example #13
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()
Example #14
0
from gevent.monkey import patch_all; patch_all()

import logging
from os import environ

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


setup_logging(level=logging.INFO)
config = ClientConfig.from_file("config.json")
config.token = environ['token']
client = Client(config)
bot_config = BotConfig(config.bot)
bot = Bot(client, bot_config)

if __name__ == '__main__':
    bot.run_forever()
Example #15
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)
Example #16
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)