diff --git a/.biblio.yaml b/.biblio.yaml new file mode 100644 index 0000000..28d1406 --- /dev/null +++ b/.biblio.yaml @@ -0,0 +1,8 @@ +name: Disco + +rules: + disco/*.py: + parser: numpy + +outputs: + - {type: markdown, path: docs/api/, title: 'Disco Documentation'} diff --git a/.gitignore b/.gitignore index 1346a5f..8b3cba2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,13 @@ build/ dist/ disco*.egg-info/ -docs/_build storage.db storage.json *.dca +.eggs/ + +# Documentation stuff +docs/api/ +docs/_build +_book/ +node_modules/ diff --git a/README.md b/README.md index ae77c31..e876299 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,6 @@ Using the default bot configuration, we can now run this script like so: `python -m disco.cli --token="MY_DISCORD_TOKEN" --run-bot --plugin simpleplugin` -And commands can be triggered by mentioning the bot (configued by the BotConfig.command\_require\_mention flag): +And commands can be triggered by mentioning the bot (configured by the BotConfig.command\_require\_mention flag): ![](http://i.imgur.com/Vw6T8bi.png) diff --git a/disco/__init__.py b/disco/__init__.py index c3f2301..636ac44 100644 --- a/disco/__init__.py +++ b/disco/__init__.py @@ -1 +1 @@ -VERSION = '0.0.8' +VERSION = '0.0.10' diff --git a/disco/api/client.py b/disco/api/client.py index 26fdc1d..0be4a60 100644 --- a/disco/api/client.py +++ b/disco/api/client.py @@ -167,8 +167,11 @@ class APIClient(LoggingClass): def channels_messages_delete_bulk(self, channel, messages): self.http(Routes.CHANNELS_MESSAGES_DELETE_BULK, dict(channel=channel), json={'messages': messages}) - def channels_messages_reactions_get(self, channel, message, emoji): - r = self.http(Routes.CHANNELS_MESSAGES_REACTIONS_GET, dict(channel=channel, message=message, emoji=emoji)) + def channels_messages_reactions_get(self, channel, message, emoji, after=None, limit=100): + r = self.http( + Routes.CHANNELS_MESSAGES_REACTIONS_GET, + dict(channel=channel, message=message, emoji=emoji), + params={'after': after, 'limit': limit}) return User.create_map(self.client, r.json()) def channels_messages_reactions_create(self, channel, message, emoji): diff --git a/disco/api/http.py b/disco/api/http.py index fb85015..13864a2 100644 --- a/disco/api/http.py +++ b/disco/api/http.py @@ -22,8 +22,9 @@ HTTPMethod = Enum( def to_bytes(obj): - if isinstance(obj, six.text_type): - return obj.encode('utf-8') + if six.PY2: + if isinstance(obj, six.text_type): + return obj.encode('utf-8') return obj @@ -148,6 +149,7 @@ class APIException(Exception): self.code = 0 self.msg = 'Request Failed ({})'.format(response.status_code) + self.errors = {} if self.retries: self.msg += " after {} retries".format(self.retries) @@ -158,7 +160,8 @@ class APIException(Exception): if 'code' in data: self.code = data['code'] - self.msg = data['message'] + self.errors = data.get('errors', {}) + self.msg = '{} ({} - {})'.format(data['message'], self.code, self.errors) elif len(data) == 1: key, value = list(data.items())[0] self.msg = 'Request Failed: {}: {}'.format(key, ', '.join(value)) diff --git a/disco/bot/bot.py b/disco/bot/bot.py index 18260b9..b88d6f1 100644 --- a/disco/bot/bot.py +++ b/disco/bot/bot.py @@ -210,7 +210,7 @@ class Bot(LoggingClass): # abbreviations that don't conflict with eachother. possible = {} for group in groups: - for index in range(len(group)): + for index in range(1, len(group)): current = group[:index] if current in possible: possible[current] = None @@ -275,7 +275,7 @@ class Bot(LoggingClass): mention_rules.get('role', False) and any(mention_roles), msg.channel.is_dm )): - raise StopIteration + return if mention_direct: if msg.guild: @@ -296,12 +296,12 @@ class Bot(LoggingClass): content = content.lstrip() if prefix and not content.startswith(prefix): - raise StopIteration + return else: content = content[len(prefix):] if not self.command_matches_re or not self.command_matches_re.match(content): - raise StopIteration + return for command in self.commands: match = command.compiled_regex.match(content) @@ -390,13 +390,13 @@ class Bot(LoggingClass): self.last_message_cache[msg.channel_id] = (msg, triggered) - def add_plugin(self, cls, config=None, ctx=None): + def add_plugin(self, inst, config=None, ctx=None): """ Adds and loads a plugin, based on its class. Parameters ---------- - cls : subclass of :class:`disco.bot.plugin.Plugin` + inst : subclass (or instance therein) of `disco.bot.plugin.Plugin` Plugin class to initialize and load. config : Optional The configuration to load the plugin with. @@ -404,18 +404,21 @@ class Bot(LoggingClass): Context (previous state) to pass the plugin. Usually used along w/ unload. """ - if cls.__name__ in self.plugins: - self.log.warning('Attempted to add already added plugin %s', cls.__name__) - raise Exception('Cannot add already added plugin: {}'.format(cls.__name__)) + if inspect.isclass(inst): + if not config: + if callable(self.config.plugin_config_provider): + config = self.config.plugin_config_provider(inst) + else: + config = self.load_plugin_config(inst) - if not config: - if callable(self.config.plugin_config_provider): - config = self.config.plugin_config_provider(cls) - else: - config = self.load_plugin_config(cls) + inst = inst(self, config) + + if inst.__class__.__name__ in self.plugins: + self.log.warning('Attempted to add already added plugin %s', inst.__class__.__name__) + raise Exception('Cannot add already added plugin: {}'.format(inst.__class__.__name__)) - self.ctx['plugin'] = self.plugins[cls.__name__] = cls(self, config) - self.plugins[cls.__name__].load(ctx or {}) + self.ctx['plugin'] = self.plugins[inst.__class__.__name__] = inst + self.plugins[inst.__class__.__name__].load(ctx or {}) self.recompute() self.ctx.drop() @@ -481,7 +484,7 @@ class Bot(LoggingClass): data = {} if name in self.config.plugin_config: - data = self.config.plugin_config[name] + data.update(self.config.plugin_config[name]) if os.path.exists(path): with open(path, 'r') as f: diff --git a/disco/bot/command.py b/disco/bot/command.py index c06e30f..58a19f4 100644 --- a/disco/bot/command.py +++ b/disco/bot/command.py @@ -1,4 +1,5 @@ import re +import argparse from holster.enum import Enum @@ -7,6 +8,7 @@ from disco.util.functional import cached_property ARGS_REGEX = '(?: ((?:\n|.)*)$|$)' ARGS_UNGROUPED_REGEX = '(?: (?:\n|.)*$|$)' +SPLIT_SPACES_NO_QUOTE = re.compile(r'["|\']([^"\']+)["|\']|(\S+)') USER_MENTION_RE = re.compile('<@!?([0-9]+)>') ROLE_MENTION_RE = re.compile('<@&([0-9]+)>') @@ -21,6 +23,11 @@ CommandLevels = Enum( ) +class PluginArgumentParser(argparse.ArgumentParser): + def error(self, message): + raise CommandError(message) + + class CommandEvent(object): """ An event which is created when a command is triggered. Contains information @@ -138,6 +145,7 @@ class Command(object): self.oob = False self.context = {} self.metadata = {} + self.parser = None self.update(*args, **kwargs) @@ -151,7 +159,7 @@ class Command(object): def get_docstring(self): return (self.func.__doc__ or '').format(**self.context) - def update(self, args=None, level=None, aliases=None, group=None, is_regex=None, oob=False, context=None, **kwargs): + def update(self, args=None, level=None, aliases=None, group=None, is_regex=None, oob=False, context=None, parser=False, **kwargs): self.triggers += aliases or [] def resolve_role(ctx, rid): @@ -175,13 +183,14 @@ class Command(object): def resolve_guild(ctx, gid): return ctx.msg.client.state.guilds.get(gid) - self.raw_args = args - self.args = ArgumentSet.from_string(args or '', { - 'user': self.mention_type([resolve_user], USER_MENTION_RE, user=True), - 'role': self.mention_type([resolve_role], ROLE_MENTION_RE), - 'channel': self.mention_type([resolve_channel], CHANNEL_MENTION_RE, allow_plain=True), - 'guild': self.mention_type([resolve_guild]), - }) + if args: + self.raw_args = args + self.args = ArgumentSet.from_string(args, { + 'user': self.mention_type([resolve_user], USER_MENTION_RE, user=True), + 'role': self.mention_type([resolve_role], ROLE_MENTION_RE), + 'channel': self.mention_type([resolve_channel], CHANNEL_MENTION_RE, allow_plain=True), + 'guild': self.mention_type([resolve_guild]), + }) self.level = level self.group = group @@ -190,6 +199,9 @@ class Command(object): self.context = context or {} self.metadata = kwargs + if parser: + self.parser = PluginArgumentParser(prog=self.name, add_help=False) + @staticmethod def mention_type(getters, reg=None, user=False, allow_plain=False): def _f(ctx, raw): @@ -235,7 +247,8 @@ class Command(object): group = '' if self.group: if self.group in self.plugin.bot.group_abbrev: - group = '{}(?:\w+)? '.format(self.plugin.bot.group_abbrev.get(self.group)) + rest = self.plugin.bot.group_abbrev[self.group] + group = '{}(?:{}) '.format(rest, ''.join(c + u'?' for c in self.group[len(rest):])) else: group = self.group + ' ' return ('^{}({})' if grouped else '^{}(?:{})').format( @@ -253,20 +266,27 @@ class Command(object): bool Whether this command was successful """ - if len(event.args) < self.args.required_length: - raise CommandError(u'Command {} requires {} arguments (`{}`) passed {}'.format( - event.name, - self.args.required_length, - self.raw_args, - len(event.args) - )) - - try: - parsed_args = self.args.parse(event.args, ctx=event) - except ArgumentError as e: - raise CommandError(e.message) + parsed_kwargs = {} + + if self.args: + if len(event.args) < self.args.required_length: + raise CommandError(u'Command {} requires {} arguments (`{}`) passed {}'.format( + event.name, + self.args.required_length, + self.raw_args, + len(event.args) + )) + + try: + parsed_kwargs = self.args.parse(event.args, ctx=event) + except ArgumentError as e: + raise CommandError(e.message) + elif self.parser: + event.parser = self.parser + parsed_kwargs['args'] = self.parser.parse_args( + [i[0] or i[1] for i in SPLIT_SPACES_NO_QUOTE.findall(' '.join(event.args))]) kwargs = {} kwargs.update(self.context) - kwargs.update(parsed_args) + kwargs.update(parsed_kwargs) return self.plugin.dispatch('command', self, event, **kwargs) diff --git a/disco/bot/plugin.py b/disco/bot/plugin.py index 088f4da..155e581 100644 --- a/disco/bot/plugin.py +++ b/disco/bot/plugin.py @@ -12,11 +12,7 @@ from disco.util.logging import LoggingClass from disco.bot.command import Command, CommandError -class PluginDeco(object): - """ - A utility mixin which provides various function decorators that a plugin - author can use to create bound event/command handlers. - """ +class BasePluginDeco(object): Prio = Priority # TODO: dont smash class methods @@ -70,6 +66,7 @@ class PluginDeco(object): """ Creates a new command attached to the function. """ + return cls.add_meta_deco({ 'type': 'command', 'args': args, @@ -123,6 +120,25 @@ class PluginDeco(object): 'kwargs': kwargs, }) + @classmethod + def add_argument(cls, *args, **kwargs): + """ + Adds an argument to the argument parser. + """ + return cls.add_meta_deco({ + 'type': 'parser.add_argument', + 'args': args, + 'kwargs': kwargs, + }) + + +class PluginDeco(BasePluginDeco): + """ + A utility mixin which provides various function decorators that a plugin + author can use to create bound event/command handlers. + """ + parser = BasePluginDeco + class Plugin(LoggingClass, PluginDeco): """ @@ -191,7 +207,7 @@ class Plugin(LoggingClass, PluginDeco): self._post = {'command': [], 'listener': []} for member in self.meta_funcs: - for meta in member.meta: + for meta in reversed(member.meta): self.bind_meta(member, meta) def bind_meta(self, member, meta): @@ -205,6 +221,14 @@ class Plugin(LoggingClass, PluginDeco): elif meta['type'].startswith('pre_') or meta['type'].startswith('post_'): when, typ = meta['type'].split('_', 1) self.register_trigger(typ, when, member) + elif meta['type'].startswith('parser.'): + for command in self.commands: + if command.func == member: + getattr(command.parser, meta['type'].split('.', 1)[-1])( + *meta['args'], + **meta['kwargs']) + else: + raise Exception('unhandled meta type {}'.format(meta)) def handle_exception(self, greenlet, event): pass diff --git a/disco/cli.py b/disco/cli.py index 10aa9f3..df04313 100644 --- a/disco/cli.py +++ b/disco/cli.py @@ -24,6 +24,7 @@ parser.add_argument('--manhole-bind', help='host:port for the manhole to bind to parser.add_argument('--encoder', help='encoder for gateway data', default=None) parser.add_argument('--run-bot', help='run a disco bot on this client', action='store_true', default=False) parser.add_argument('--plugin', help='load plugins into the bot', nargs='*', default=[]) +parser.add_argument('--log-level', help='log level', default='info') def disco_main(run=False): @@ -62,7 +63,7 @@ def disco_main(run=False): return # TODO: make configurable - setup_logging(level=logging.INFO) + setup_logging(level=getattr(logging, args.log_level.upper())) client = Client(config) diff --git a/disco/gateway/events.py b/disco/gateway/events.py index f2da195..99b5c03 100644 --- a/disco/gateway/events.py +++ b/disco/gateway/events.py @@ -64,9 +64,12 @@ class GatewayEvent(six.with_metaclass(GatewayEventMeta, Model)): return cls(obj, client) def __getattr__(self, name): - if hasattr(self, '_proxy'): - return getattr(getattr(self, self._proxy), name) - return object.__getattribute__(self, name) + try: + _proxy = object.__getattribute__(self, '_proxy') + except AttributeError: + return object.__getattribute__(self, name) + + return getattr(getattr(self, _proxy), name) def debug(func=None, match=None): diff --git a/disco/state.py b/disco/state.py index 848665b..49a63e0 100644 --- a/disco/state.py +++ b/disco/state.py @@ -286,8 +286,11 @@ class State(object): for member in event.members: member.guild_id = guild.id guild.members[member.id] = member + if member.id not in self.users: self.users[member.id] = member.user + else: + member.user = self.users[member.id] def on_guild_role_create(self, event): if event.guild_id not in self.guilds: diff --git a/disco/types/base.py b/disco/types/base.py index d396762..f219b9b 100644 --- a/disco/types/base.py +++ b/disco/types/base.py @@ -209,18 +209,6 @@ def text(obj): return str(obj) -def binary(obj): - if obj is None: - return None - - if six.PY2: - if isinstance(obj, str): - return obj.decode('utf-8') - return unicode(obj) - else: - return bytes(obj, 'utf-8') - - def with_equality(field): class T(object): def __eq__(self, other): diff --git a/disco/types/channel.py b/disco/types/channel.py index 1b99f8b..a8d7936 100644 --- a/disco/types/channel.py +++ b/disco/types/channel.py @@ -59,7 +59,7 @@ class PermissionOverwrite(ChannelSubType): channel_id = Field(snowflake) @classmethod - def create(cls, channel, entity, allow=0, deny=0): + def create_for_channel(cls, channel, entity, allow=0, deny=0): from disco.types.guild import Role ptype = PermissionOverwriteType.ROLE if isinstance(entity, Role) else PermissionOverwriteType.MEMBER @@ -200,37 +200,57 @@ class Channel(SlottedModel, Permissible): @property def messages(self): """ - a default :class:`MessageIterator` for the channel. + A default `MessageIterator` for the channel, can be used to quickly and + easily iterate over the channels entire message history. For more control, + use `Channel.messages_iter`. """ return self.messages_iter() @cached_property def guild(self): """ - Guild this channel belongs to (if relevant). + Guild this channel belongs to (or None if not applicable). """ return self.client.state.guilds.get(self.guild_id) def messages_iter(self, **kwargs): """ - Creates a new :class:`MessageIterator` for the channel with the given - keyword arguments. + Creates a new `MessageIterator` for the channel with the given keyword + arguments. """ return MessageIterator(self.client, self, **kwargs) def get_message(self, message): + """ + Attempts to fetch and return a `Message` from the message object + or id. + + Returns + ------- + `Message` + The fetched message + """ return self.client.api.channels_messages_get(self.id, to_snowflake(message)) def get_invites(self): """ Returns ------- - list(:class:`disco.types.invite.Invite`) - All invites for this channel. + list(`Invite`) + Returns a list of all invites for this channel. """ return self.client.api.channels_invites_list(self.id) def create_invite(self, *args, **kwargs): + """ + Attempts to create a new invite with the given arguments. For more + information see `Invite.create_for_channel`. + + Returns + ------- + `Invite` + """ + from disco.types.invite import Invite return Invite.create_for_channel(self, *args, **kwargs) @@ -238,39 +258,62 @@ class Channel(SlottedModel, Permissible): """ Returns ------- - list(:class:`disco.types.message.Message`) - All pinned messages for this channel. + list(`Message`) + Returns a list of all pinned messages for this channel. """ return self.client.api.channels_pins_list(self.id) def create_pin(self, message): + """ + Pins the given message to the channel. + + Params + ------ + message : `Message`|snowflake + The message or message ID to pin. + """ self.client.api.channels_pins_create(self.id, to_snowflake(message)) def delete_pin(self, message): + """ + Unpins the given message from the channel. + + Params + ------ + message : `Message`|snowflake + The message or message ID to pin. + """ self.client.api.channels_pins_delete(self.id, to_snowflake(message)) def get_webhooks(self): + """ + Returns + ------- + list(`Webhook`) + Returns a list of all webhooks for this channel. + """ return self.client.api.channels_webhooks_list(self.id) - def create_webhook(self, name=None, avatar=None): - return self.client.api.channels_webhooks_create(self.id, name, avatar) + def create_webhook(self, *args, **kwargs): + """ + Creates a webhook for this channel. See `APIClient.channels_webhooks_create` + for more information. - def send_message(self, *args, **kwargs): + Returns + ------- + `Webhook` + The created webhook. """ - Send a message in this channel. + return self.client.api.channels_webhooks_create(self.id, *args, **kwargs) - Parameters - ---------- - content : str - The message contents to send. - nonce : Optional[snowflake] - The nonce to attach to the message. - tts : Optional[bool] - Whether this is a TTS message. + def send_message(self, *args, **kwargs): + """ + Send a message to this channel. See `APIClient.channels_messages_create` + for more information. Returns ------- - :class:`disco.types.message.Message` + `disco.types.message.Message` The created message. """ return self.client.api.channels_messages_create(self.id, *args, **kwargs) @@ -285,7 +328,11 @@ class Channel(SlottedModel, Permissible): return vc def create_overwrite(self, *args, **kwargs): - return PermissionOverwrite.create(self, *args, **kwargs) + """ + Creates a `PermissionOverwrite` for this channel. See + `PermissionOverwrite.create_for_channel` for more information. + """ + return PermissionOverwrite.create_for_channel(self, *args, **kwargs) def delete_message(self, message): """ @@ -293,7 +340,7 @@ class Channel(SlottedModel, Permissible): Args ---- - message : snowflake|:class:`disco.types.message.Message` + message : snowflake|`Message` The message to delete. """ self.client.api.channels_messages_delete(self.id, to_snowflake(message)) @@ -306,7 +353,7 @@ class Channel(SlottedModel, Permissible): Args ---- - messages : list[snowflake|:class:`disco.types.message.Message`] + messages : list(snowflake|`Message`) List of messages (or message ids) to delete. All messages must originate from this channel. """ @@ -385,7 +432,7 @@ class MessageIterator(object): limit=self.chunk_size) if not len(self._buffer): - raise StopIteration + return self.after = None self.before = None diff --git a/disco/types/guild.py b/disco/types/guild.py index 6f27faa..857bf5c 100644 --- a/disco/types/guild.py +++ b/disco/types/guild.py @@ -7,7 +7,7 @@ from disco.api.http import APIException from disco.util.snowflake import to_snowflake from disco.util.functional import cached_property from disco.types.base import ( - SlottedModel, Field, ListField, AutoDictField, DictField, snowflake, text, binary, enum, datetime + SlottedModel, Field, ListField, AutoDictField, DictField, snowflake, text, enum, datetime ) from disco.types.user import User from disco.types.voice import VoiceState @@ -21,6 +21,7 @@ VerificationLevel = Enum( LOW=1, MEDIUM=2, HIGH=3, + EXTREME=4, ) ExplicitContentFilterLevel = Enum( @@ -269,9 +270,9 @@ class Guild(SlottedModel, Permissible): name : str Guild's name. icon : str - Guild's icon (as PNG binary data). + Guild's icon hash splash : str - Guild's splash image (as PNG binary data). + Guild's splash image hash region : str Voice region. afk_timeout : int @@ -300,9 +301,9 @@ class Guild(SlottedModel, Permissible): afk_channel_id = Field(snowflake) embed_channel_id = Field(snowflake) name = Field(text) - icon = Field(binary) - splash = Field(binary) - region = Field(str) + icon = Field(text) + splash = Field(text) + region = Field(text) afk_timeout = Field(int) embed_enabled = Field(bool) verification_level = Field(enum(VerificationLevel)) @@ -350,7 +351,8 @@ class Guild(SlottedModel, Permissible): value = PermissionValue(self.roles.get(self.id).permissions) - for role in map(self.roles.get, member.roles): + # Iterate over all roles the user has (plus the @everyone role) + for role in map(self.roles.get, member.roles + [self.id]): value += role.permissions return value @@ -449,6 +451,25 @@ class Guild(SlottedModel, Permissible): def get_emojis(self): return self.client.api.guilds_emojis_list(self.id) + def get_icon_url(self, fmt='webp', size=1024): + if not self.icon: + return '' + + return 'https://cdn.discordapp.com/icons/{}/{}.{}?size={}'.format(self.id, self.icon, fmt, size) + + def get_splash_url(self, fmt='webp', size=1024): + if not self.splash: + return '' + + return 'https://cdn.discordapp.com/splashes/{}/{}.{}?size={}'.format(self.id, self.splash, fmt, size) + + @property + def icon_url(self): + return self.get_icon_url() + + @property + def splash_url(self): + return self.get_splash_url() AuditLogActionTypes = Enum( GUILD_UPDATE=1, diff --git a/disco/types/message.py b/disco/types/message.py index 0d1f219..07b44af 100644 --- a/disco/types/message.py +++ b/disco/types/message.py @@ -10,6 +10,7 @@ from disco.types.base import ( SlottedModel, Field, ListField, AutoDictField, snowflake, text, datetime, enum ) +from disco.util.paginator import Paginator from disco.util.snowflake import to_snowflake from disco.util.functional import cached_property from disco.types.user import User @@ -300,20 +301,25 @@ class Message(SlottedModel): """ return self.client.api.channels_messages_delete(self.channel_id, self.id) - def get_reactors(self, emoji): + def get_reactors(self, emoji, *args, **kwargs): """ - Returns an list of users who reacted to this message with the given emoji. + Returns an iterator which paginates the reactors for the given emoji. Returns ------- - list(:class:`User`) - The users who reacted. + Paginator(`User`) + An iterator which handles pagination of reactors. """ - return self.client.api.channels_messages_reactions_get( + if isinstance(emoji, Emoji): + emoji = emoji.to_string() + + return Paginator( + self.client.api.channels_messages_reactions_get, self.channel_id, self.id, - emoji - ) + emoji, + *args, + **kwargs) def create_reaction(self, emoji): warnings.warn( @@ -322,8 +328,17 @@ class Message(SlottedModel): return self.add_reaction(emoji) def add_reaction(self, emoji): + """ + Adds a reaction to the message. + + Parameters + ---------- + emoji : Emoji|str + An emoji or string representing an emoji + """ if isinstance(emoji, Emoji): emoji = emoji.to_string() + self.client.api.channels_messages_reactions_create( self.channel_id, self.id, diff --git a/disco/types/user.py b/disco/types/user.py index 2777c5e..d6e5938 100644 --- a/disco/types/user.py +++ b/disco/types/user.py @@ -1,6 +1,6 @@ from holster.enum import Enum -from disco.types.base import SlottedModel, Field, snowflake, text, binary, with_equality, with_hash +from disco.types.base import SlottedModel, Field, snowflake, text, with_equality, with_hash DefaultAvatars = Enum( BLURPLE=0, @@ -14,11 +14,11 @@ DefaultAvatars = Enum( class User(SlottedModel, with_equality('id'), with_hash('id')): id = Field(snowflake) username = Field(text) - avatar = Field(binary) - discriminator = Field(str) + avatar = Field(text) + discriminator = Field(text) bot = Field(bool, default=False) verified = Field(bool) - email = Field(str) + email = Field(text) presence = Field(None) diff --git a/disco/util/functional.py b/disco/util/functional.py index 5050842..d52d4e9 100644 --- a/disco/util/functional.py +++ b/disco/util/functional.py @@ -17,7 +17,7 @@ def take(seq, count): for _ in range(count): i = next(seq, NO_MORE_SENTINEL) if i is NO_MORE_SENTINEL: - raise StopIteration + return yield i diff --git a/disco/util/paginator.py b/disco/util/paginator.py new file mode 100644 index 0000000..715f8d9 --- /dev/null +++ b/disco/util/paginator.py @@ -0,0 +1,43 @@ +import operator + + +class Paginator(object): + """ + Implements a class which provides paginated iteration over an endpoint. + """ + def __init__(self, func, *args, **kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + + self._key = kwargs.pop('key', operator.attrgetter('id')) + self._bulk = kwargs.pop('bulk', False) + self._after = kwargs.pop('after', None) + self._buffer = [] + + def fill(self): + self.kwargs['after'] = self._after + result = self.func(*self.args, **self.kwargs) + + if not len(result): + return + + self._buffer.extend(result) + self._after = self._key(result[-1]) + + def next(self): + return self.__next__() + + def __iter__(self): + return self + + def __next__(self): + if not len(self._buffer): + self.fill() + + if self._bulk: + res = self._buffer + self._buffer = [] + return res + else: + return self._buffer.pop() diff --git a/disco/voice/client.py b/disco/voice/client.py index 6f2eae3..e747d02 100644 --- a/disco/voice/client.py +++ b/disco/voice/client.py @@ -153,7 +153,11 @@ class VoiceClient(LoggingClass): self.ws = None self.heartbeat_task = None + def __repr__(self): + return u''.format(self.channel) + def set_state(self, state): + self.log.debug('[%s] state %s -> %s', self, self.state, state) prev_state = self.state self.state = state self.state_emitter.emit(state, prev_state) @@ -170,25 +174,30 @@ class VoiceClient(LoggingClass): }) def send(self, op, data): + self.log.debug('[%s] sending OP %s (data = %s)', self, op, data) self.ws.send(self.encoder.encode({ 'op': op.value, 'd': data, }), self.encoder.OPCODE) def on_voice_ready(self, data): + self.log.info('[%s] Recived Voice READY payload, attempting to negotiate voice connection w/ remote', self) self.set_state(VoiceState.CONNECTING) self.ssrc = data['ssrc'] self.port = data['port'] self.heartbeat_task = gevent.spawn(self.heartbeat, data['heartbeat_interval']) + self.log.debug('[%s] Attempting IP discovery over UDP to %s:%s', self, self.endpoint, self.port) self.udp = UDPVoiceClient(self) ip, port = self.udp.connect(self.endpoint, self.port) if not ip: + self.log.error('Failed to discover our IP, perhaps a NAT or firewall is fucking us') self.disconnect() return + self.log.debug('[%s] IP discovery completed (ip = %s, port = %s), sending SELECT_PROTOCOL', self, ip, port) self.send(VoiceOPCode.SELECT_PROTOCOL, { 'protocol': 'udp', 'data': { @@ -199,6 +208,7 @@ class VoiceClient(LoggingClass): }) def on_voice_sdp(self, sdp): + self.log.info('[%s] Recieved session description, connection completed', self) # Create a secret box for encryption/decryption self.secret_box = nacl.secret.SecretBox(bytes(bytearray(sdp['secret_key']))) @@ -216,6 +226,8 @@ class VoiceClient(LoggingClass): if self.token and self.token != data.token: return + self.log.info('[%s] Recieved VOICE_SERVER_UPDATE (state = %s)', self, self.state) + self.token = data.token self.set_state(VoiceState.AUTHENTICATING) @@ -236,7 +248,7 @@ class VoiceClient(LoggingClass): def on_error(self, err): # TODO: raise an exception here - self.log.warning('Voice websocket error: {}'.format(err)) + self.log.error('[%s] Voice websocket error: %s', self, err) def on_open(self): self.send(VoiceOPCode.IDENTIFY, { @@ -247,13 +259,14 @@ class VoiceClient(LoggingClass): }) def on_close(self, code, error): - self.log.warning('Voice websocket disconnected (%s, %s)', code, error) + self.log.warning('[%s] Voice websocket disconnected (%s, %s)', self, code, error) if self.state == VoiceState.CONNECTED: self.log.info('Attempting voice reconnection') self.connect() def connect(self, timeout=5, mute=False, deaf=False): + self.log.debug('[%s] Attempting connection', self) self.set_state(VoiceState.AWAITING_ENDPOINT) self.update_listener = self.client.events.on('VoiceServerUpdate', self.on_voice_server_update) @@ -269,6 +282,7 @@ class VoiceClient(LoggingClass): raise VoiceException('Failed to connect to voice', self) def disconnect(self): + self.log.debug('[%s] disconnect called', self) self.set_state(VoiceState.DISCONNECTED) if self.heartbeat_task: diff --git a/disco/voice/opus.py b/disco/voice/opus.py index 246dbed..b33cff8 100644 --- a/disco/voice/opus.py +++ b/disco/voice/opus.py @@ -1,3 +1,4 @@ +import six import sys import array import ctypes @@ -142,7 +143,10 @@ class OpusEncoder(BaseOpus): raise Exception('Failed to encode: {}'.format(ret)) # TODO: py3 - return array.array('b', data[:ret]).tostring() + if six.PY3: + return array.array('b', data[:ret]).tobytes() + else: + return array.array('b', data[:ret]).tostring() class OpusDecoder(BaseOpus): diff --git a/disco/voice/playable.py b/disco/voice/playable.py index 55d80fa..35fbf8b 100644 --- a/disco/voice/playable.py +++ b/disco/voice/playable.py @@ -183,7 +183,7 @@ class YoutubeDLInput(FFmpegInput): if 'entries' not in info: yield cls(ie_info=info, *args, **kwargs) - raise StopIteration + return for item in info['entries']: yield cls(ie_info=item, *args, **kwargs) diff --git a/docs/.DS_Store b/docs/.DS_Store new file mode 100644 index 0000000..1c08184 Binary files /dev/null and b/docs/.DS_Store differ diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index 64019fa..0000000 --- a/docs/Makefile +++ /dev/null @@ -1,225 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " applehelp to make an Apple Help Book" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " epub3 to make an epub3" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " xml to make Docutils-native XML files" - @echo " pseudoxml to make pseudoxml-XML files for display purposes" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - @echo " coverage to run coverage check of the documentation (if enabled)" - @echo " dummy to check syntax errors of document sources" - -.PHONY: clean -clean: - rm -rf $(BUILDDIR)/* - -.PHONY: html -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -.PHONY: dirhtml -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -.PHONY: singlehtml -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -.PHONY: pickle -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -.PHONY: json -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -.PHONY: htmlhelp -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -.PHONY: qthelp -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/disco.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/disco.qhc" - -.PHONY: applehelp -applehelp: - $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp - @echo - @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." - @echo "N.B. You won't be able to view it unless you put it in" \ - "~/Library/Documentation/Help or install it in your application" \ - "bundle." - -.PHONY: devhelp -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/disco" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/disco" - @echo "# devhelp" - -.PHONY: epub -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -.PHONY: epub3 -epub3: - $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 - @echo - @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." - -.PHONY: latex -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -.PHONY: latexpdf -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -.PHONY: latexpdfja -latexpdfja: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through platex and dvipdfmx..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -.PHONY: text -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -.PHONY: man -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -.PHONY: texinfo -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -.PHONY: info -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -.PHONY: gettext -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -.PHONY: changes -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -.PHONY: linkcheck -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -.PHONY: doctest -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." - -.PHONY: coverage -coverage: - $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage - @echo "Testing of coverage in the sources finished, look at the " \ - "results in $(BUILDDIR)/coverage/python.txt." - -.PHONY: xml -xml: - $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml - @echo - @echo "Build finished. The XML files are in $(BUILDDIR)/xml." - -.PHONY: pseudoxml -pseudoxml: - $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml - @echo - @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." - -.PHONY: dummy -dummy: - $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy - @echo - @echo "Build finished. Dummy builder generates no files." diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..85b3184 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,14 @@ +# Disco + +Disco is a simple, clean and extendable library for the [Discord API](https://dis.gd/docs). Disco is built and aimed at developers looking to quickly start building bots that can be grown and extended to live on thousands of servers, and have immense functionality. To facilitate this, Disco provides a clean and simple interface which gets out of the way, but never sacrifices functionality. Disco is actively used by the staff at Discord to help us build and test Discord. + +## Stability + +Disco is still a relatively young library, and as such it bears the "alpha" tag. For the most part, this means that while the general API and functionality may change or vary from version to version, the core concepts and features shouldn't diverge much. A benefit of this comes in the form of bleeding edge features and support for the latest Discord version. + +## Highlights + +* Expressive, Idiomatic, and Functional - the API interface stays out of our way, while giving you the required power +* Performant and Efficient - allowing you to build bots that operate on many thousands of servers, without manual sharding +* Modular and Extendable - take only the bits you need to build what you want, while being able to add or remove functionality by installing packages +* Python 2.x/3.x Support - build integrations with the version of Python you need to diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md new file mode 100644 index 0000000..0bd40c7 --- /dev/null +++ b/docs/SUMMARY.md @@ -0,0 +1,62 @@ +# Summary + +* [Introduction](README.md) +* [Installation and Setup](installation.md) +* [Bot Tutorial](bot_tutorial/intro.md) + * [Creating and Running a Bot](bot_tutorial/first_steps.md) + * [Plugins](bot_tutorial/building_block_plugins.md) + * [Commands](bot_tutorial/building_block_commands.md) + * [Listeners](bot_tutorial/building_block_listeners.md) + * [Message Embeds](bot_tutorial/message_embeds.md) + * [Advanced](bot_tutorial/advanced.md) +* API Docs + * [disco.client](api/disco_client.md) + * [disco.state](api/disco_state.md) + * [disco.cli](api/disco_cli.md) + * Bot + * [disco.bot.bot](api/disco_bot_bot.md) + * [disco.bot.plugin](api/disco_bot_plugin.md) + * [disco.bot.command](api/disco_bot_command.md) + * [disco.bot.storage](api/disco_bot_storage.md) + * [disco.bot.parser](api/disco_bot_parser.md) + * API + * [disco.api.client](api/disco_api_client.md) + * [disco.api.http](api/disco_api_http.md) + * [disco.api.ratelimit](api/disco_api_ratelimit.md) + * Gateway + * [disco.gateway.client](api/disco_gateway_client.md) + * [disco.gateway.events](api/disco_gateway_events.md) + * [disco.gateway.packets](api/disco_gateway_packets.md) + * [disco.gateway.sharder](api/disco_gateway_sharder.md) + * [disco.gateway.ipc](api/disco_gateway_ipc.md) + * Types + * [disco.types.base](api/disco_types_base.md) + * [disco.types.channel](api/disco_types_channel.md) + * [disco.types.guild](api/disco_types_guild.md) + * [disco.types.invite](api/disco_types_invite.md) + * [disco.types.message](api/disco_types_message.md) + * [disco.types.permissions](api/disco_types_permissions.md) + * [disco.types.user](api/disco_types_user.md) + * [disco.types.voice](api/disco_types_voice.md) + * [disco.types.webhook](api/disco_types_webhook.md) + * Util + * [disco.util](api/disco_util.md) + * [disco.util.backdoor](api/disco_util_backdoor.md) + * [disco.util.chains](api/disco_util_chains.md) + * [disco.util.config](api/disco_util_config.md) + * [disco.util.functional](api/disco_util_functional.md) + * [disco.util.hashmap](api/disco_util_hashmap.md) + * [disco.util.limiter](api/disco_util_limiter.md) + * [disco.util.logging](api/disco_util_logging.md) + * [disco.util.sanitize](api/disco_util_sanitize.md) + * [disco.util.snowflake](api/disco_util_snowflake.md) + * [disco.util.token](api/disco_util_token.md) + * [disco.util.websocket](api/disco_util_websocket.md) + * Voice + * [disco.voice.client](api/disco_voice_client.md) + * [disco.voice.opus](api/disco_voice_opus.md) + * [disco.voice.packets](api/disco_voice_packets.md) + * [disco.voice.playable](api/disco_voice_playable.md) + * [disco.voice.player](api/disco_voice_player.md) + + diff --git a/docs/api.rst b/docs/api.rst deleted file mode 100644 index c090248..0000000 --- a/docs/api.rst +++ /dev/null @@ -1,150 +0,0 @@ -.. currentmodule:: disco - -API Reference -============= - -Version Information -------------------- -disco exports a top-level variable that can be used to introspect the current -version information for the installed package. - -.. data:: VERSION - - A string representation of the current version, in standard semantic - versioning format. E.g. ``'5.4.3-rc.2'`` - - -Client ------------- - -.. autoclass:: disco.client.Client - :members: - - -State ------ - -.. automodule:: disco.state - :members: - - -CLI ---- - -.. automodule:: disco.cli - :members: - - -Types ------ - -Channel -~~~~~~~ - -.. automodule:: disco.types.channel - :members: - -Guild -~~~~~ - -.. automodule:: disco.types.guild - :members: - -Message -~~~~~~~ - -.. automodule:: disco.types.message - :members: - -User -~~~~ - -.. automodule:: disco.types.user - :members: - -Voice -~~~~~ - -.. automodule:: disco.types.voice - :members: - -Invite -~~~~~~ - -.. automodule:: disco.types.invite - :members: - -Permissions -~~~~~~~~~~~ - -.. automodule:: disco.types.permissions - :members: - - -Bot Toolkit ------------ - -.. automodule:: disco.bot.bot - :members: - -Plugins -~~~~~~~ - -.. automodule:: disco.bot.plugin - :members: - -Commands -~~~~~~~~ - -.. automodule:: disco.bot.command - :members: - -Command Argument Parser -~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: disco.bot.parser - :members: - - -Gateway API ------------ - -GatewayClient -~~~~~~~~~~~~~ - -.. autoclass:: disco.gateway.client.GatewayClient - :members: - -Gateway Events -~~~~~~~~~~~~~~ - -.. automodule:: disco.gateway.events - :members: - - -REST API --------- - -APIClient -~~~~~~~~~ - -.. autoclass:: disco.api.client.APIClient - :members: - :undoc-members: - -HTTP Utilities -~~~~~~~~~~~~~~ -.. autoclass:: disco.api.http.APIException - :members: - -.. autoclass:: disco.api.http.HTTPClient - :members: - -Ratelimit Utilities -~~~~~~~~~~~~~~~~~~~ - -.. autoclass:: disco.api.ratelimit.RouteState - :members: - -.. autoclass:: disco.api.ratelimit.RateLimiter - :members: diff --git a/docs/book.json b/docs/book.json new file mode 100644 index 0000000..b6afda5 --- /dev/null +++ b/docs/book.json @@ -0,0 +1,10 @@ +{ + "title": "Disco", + "plugins": ["prism", "-highlight", "hints"], + "pluginsConfig": { + "anchorjs": { + "placement": "left", + "visible": "always" + } + } +} diff --git a/docs/bot_tutorial/advanced.md b/docs/bot_tutorial/advanced.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/bot_tutorial/building_block_commands.md b/docs/bot_tutorial/building_block_commands.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/bot_tutorial/building_block_listeners.md b/docs/bot_tutorial/building_block_listeners.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/bot_tutorial/building_block_plugins.md b/docs/bot_tutorial/building_block_plugins.md new file mode 100644 index 0000000..eaf449c --- /dev/null +++ b/docs/bot_tutorial/building_block_plugins.md @@ -0,0 +1,52 @@ +# Plugins + +Plugins are Disco are a core abstraction which attempt to encapsulate the functionality of your bot into contained modules. To boil it down, commands related to one another, or listeners that control the same functionality should be within the same Plugin. Although it's possible to call and pass data between Plugins, you should generally attempt to avoid it. + +## Plugin Lifecycle + +### Loading + +Plugins are loaded when the Bot is initially created, and when this happens the `Plugin.load` function is called. If the plugin is being reloaded, the call to this function will contain a dictionary of data returned by the previous `unload` call. Using this, you can pass data between loaded instances of your plugin to help aid in seamless reloads. Often plugins will require some level of configuration and setup before running, and this code can be inserted within an overridden version of the load function, as such: + +```python +class ExamplePlugin(Plugin): + def load(self, ctx): + super(ExamplePlugin, self).load(ctx) + setup_database() + self.data = ctx.get('data', {}) +``` + +The load function of a plugin is guaranteed to only be called once for the instance, when reloading a new instance of the plugin will be created. + +### Unloading + +Plugins are unloaded in multiple scenarios (shutdown, before a reload, or during an unload), and when this happens the `Plugin.unload` function is called. This function is passed one argument containing a dictionary, which (if the plugin wants) can be filled with information that a future iteration (in the case we're reloading) of the plugin can use to maintain state. Plugins may want to call or save data before being unloaded, and in this case they can override the unload function: + +```python +class ExamplePlugin(Plugin): + def unload(self, ctx): + ctx['data'] = self.data + super(ExamplePlugin, self).unload(ctx) +``` + +During the unload sequence all greenlets which the plugin owns (e.g. greenlets for command or listener callbacks, any spawned with `Plugin.spawn`) are terminated. In the case where command callbacks should continue execution past the unload point (e.g. in the case where a plugin reloads itself), you should pass `oob=True` to the `Plugin.command` decorator. + +## Configuration + +Disco supports a framework for dynamically passing configuration to plugins. By default, configuration files live within the `config/` directory, and are named after the plugin, e.g. `ExamplePlugin` would be configured via `config/example.json`. Adding support for configuration within your plugin can be done via a decorator: + +```python +from disco.bot import Plugin, PluginConfig + +class ExamplePluginConfig(PluginConfig): + var1 = "test" + var2 = True + + +@Plugin.with_config(ExamplePluginConfig) +class ExamplePlugin(Plugin): + def load(self, ctx): + super(ExamplePlugin, self).load(ctx) + assert self.config.var1 == "test" + assert self.config.var2 +``` diff --git a/docs/bot_tutorial/first_steps.md b/docs/bot_tutorial/first_steps.md new file mode 100644 index 0000000..0b4b540 --- /dev/null +++ b/docs/bot_tutorial/first_steps.md @@ -0,0 +1,60 @@ +# Bot Tutorial + +Disco provides a built-in set of tools for building and running Discord bots which can be used to quickly and easily create integrations. Within this tutorial you'll be shown how to install Disco, write plugins, and run bots. This tutorial assumes you've already followed the [Installation Steps](../installation.md). + +## Creating a Bot + +The first step to creating bots is to actually register them on Discord itself. To do this, you'll need to be logged into your Discord account on the browser and then navigate to [My Apps](https://discordapp.com/developers/applications/me). Here you'll have the option to create a new application, and once created you can add a bot user (by clicking "Create a Bot User") to your application. Finally, you'll want to keep track of the bot user token which can be shown by clicking the "click to reveal" link next to the token field. + +Once you have a Discord bot account, you can then setup your workspace. For now we'll just need a folder (perhaps called `disco-tutorial`) with a few files in it: + +``` +disco-tutorial/ + config.yaml + plugins/ + __init__.py + tutorial.py +``` + +{% hint style='tip' %} +The \_\_init\_\_.py file is required for Python to find your plugin, but it can remain empty. +{% endhint %} + + +Within the config file, paste the following template configuration and modify the token key to contain the token you obtained above: + +```yaml +token: 'MY_BOT_TOKEN_HERE' + +bot: + plugins: + - plugins.tutorial +``` + +Now, within the python file (`tutorial.py`), lets write some code: + + +```python +from disco.bot import Plugin + + +class TutorialPlugin(Plugin): + @Plugin.command('ping') + def command_ping(self, event): + event.msg.reply('Pong!') +``` + +And finally, we're ready to start and test the bot. We can do this by executing the following command from within our project directory: + + +```sh +python -m disco.cli --config config.yaml +``` + +If all is successful, you can then test your bot by mentioning it with the command, like so: + +``` +@tutorial#1234 ping +``` + +At this point, you've achieved the creation and setup of a very simple bot. Now lets work on understanding and working with more Disco features. diff --git a/docs/bot_tutorial/message_embeds.md b/docs/bot_tutorial/message_embeds.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/build.sh b/docs/build.sh index b7613d2..2e5fa45 100755 --- a/docs/build.sh +++ b/docs/build.sh @@ -1,12 +1,20 @@ #!/bin/bash -rm -rf _build -make html - -pushd _build/html -git init -git config user.name 'Autodoc' -git config user.email '<>' -git add . -git commit -m "Autogenerated documentation" -git push --force --quiet "https://${GH_TOKEN}@github.com/b1naryth1ef/disco" master:gh-pages +echo "Building Autogenerated API Docs" +pushd .. +python -m biblio.cli ../disco/.biblio.yaml popd + +echo "Running Gitbook Build" +gitbook build + +if [ ! -z "${GH_TOKEN:-}" ]; then + echo "Deploying to Github Pages" + pushd _book/ + git init + git config user.name "AutoDoc" + git config user.email "<>" + git add . + git commit -m "Generated Documentation" + git push --force --quiet "https://${GH_TOKEN}@github.com/b1naryth1ef/disco" master:gh-pages + popd +fi diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index 4af5f21..0000000 --- a/docs/conf.py +++ /dev/null @@ -1,343 +0,0 @@ -# -*- coding: utf-8 -*- -# -# disco documentation build configuration file, created by -# sphinx-quickstart on Tue Oct 4 22:15:06 2016. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -import os -import sys -sys.path.insert(0, os.path.abspath('../')) - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.coverage', - 'sphinx.ext.viewcode', - 'sphinx.ext.napoleon' -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] -source_suffix = '.rst' - -# The encoding of source files. -# -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'disco' -copyright = u'2016, Andrei Zbikowski' -author = u'Andrei Zbikowski' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = u'0.0.1' -# The full version, including alpha/beta/rc tags. -release = u'0.0.1' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# -# today = '' -# -# Else, today_fmt is used as the format for a strftime call. -# -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = False - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = 'sphinx_rtd_theme' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# -# html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. -# " v documentation" by default. -# -# html_title = u'disco v0.0.1' - -# A shorter title for the navigation bar. Default is the same as html_title. -# -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# -# html_logo = None - -# The name of an image file (relative to this directory) to use as a favicon of -# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# -# html_extra_path = [] - -# If not None, a 'Last updated on:' timestamp is inserted at every page -# bottom, using the given strftime format. -# The empty string is equivalent to '%b %d, %Y'. -# -# html_last_updated_fmt = None - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# -# html_additional_pages = {} - -# If false, no module index is generated. -# -# html_domain_indices = True - -# If false, no index is generated. -# -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' -# -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# 'ja' uses this config value. -# 'zh' user can custom change `jieba` dictionary path. -# -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = 'discodoc' - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (master_doc, 'disco.tex', u'disco Documentation', - u'Andrei Zbikowski', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# -# latex_use_parts = False - -# If true, show page references after internal links. -# -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# -# latex_appendices = [] - -# It false, will not define \strong, \code, itleref, \crossref ... but only -# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added -# packages. -# -# latex_keep_old_macro_names = True - -# If false, no module index is generated. -# -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'disco', u'disco Documentation', - [author], 1) -] - -# If true, show URL addresses after external links. -# -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - (master_doc, 'disco', u'disco Documentation', - author, 'disco', 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -# -# texinfo_appendices = [] - -# If false, no module index is generated. -# -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# -# texinfo_no_detailmenu = False diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index 7cacf0d..0000000 --- a/docs/index.rst +++ /dev/null @@ -1,28 +0,0 @@ -disco -================================= - -Disco is a simple and extendable library for the `Discord API `_. - -* Expressive, functional interface that gets out of the way -* Built for high-performance and efficiency -* Configurable and modular, take the bits you need -* Full support for Python 2.x/3.x -* Evented networking and IO using Gevent - -Contents: ---------- - -.. toctree:: - :maxdepth: 2 - - tutorial - api - utilities - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` - diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..70de528 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,27 @@ +# Installation and Setup + +{% hint style='tip' %} +If you are a new Python developer, or are unsure what pip even is, try starting [here](https://packaging.python.org/installing/). +{% endhint %} + +The easiest way to install the base version of Disco is through Python's [pip](https://pip.pypa.io/en/stable/) utility. To simply install the most minimal version of Disco, simply run: + +```sh +pip install disco-py +``` + +## Optional Dependencies + +Disco provides a set of optional dependencies which add various bits of functionality or performance changes when installed. These can all be installed in a similar fashion to Disco; + +```sh +pip install disco[performance] +``` + +| Name | Explanation | Versions | +|------|-------------|----------| +| voice | Adds functionality required to connect and use voice | Both | +| music | Adds the ability to stream and play music from various third party sites | Both | +| performance | Adds a faster JSON parser (ujson) and an ETF encoding parser | 2.x Only | +| sharding | Adds a library which is required to enable auto-sharding | 2.x Only | +| docs | Adds a library required to build this documentation | Both | diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index e1e5914..0000000 --- a/docs/make.bat +++ /dev/null @@ -1,281 +0,0 @@ -@ECHO OFF - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set BUILDDIR=_build -set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . -set I18NSPHINXOPTS=%SPHINXOPTS% . -if NOT "%PAPER%" == "" ( - set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% - set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% -) - -if "%1" == "" goto help - -if "%1" == "help" ( - :help - echo.Please use `make ^` where ^ is one of - echo. html to make standalone HTML files - echo. dirhtml to make HTML files named index.html in directories - echo. singlehtml to make a single large HTML file - echo. pickle to make pickle files - echo. json to make JSON files - echo. htmlhelp to make HTML files and a HTML help project - echo. qthelp to make HTML files and a qthelp project - echo. devhelp to make HTML files and a Devhelp project - echo. epub to make an epub - echo. epub3 to make an epub3 - echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter - echo. text to make text files - echo. man to make manual pages - echo. texinfo to make Texinfo files - echo. gettext to make PO message catalogs - echo. changes to make an overview over all changed/added/deprecated items - echo. xml to make Docutils-native XML files - echo. pseudoxml to make pseudoxml-XML files for display purposes - echo. linkcheck to check all external links for integrity - echo. doctest to run all doctests embedded in the documentation if enabled - echo. coverage to run coverage check of the documentation if enabled - echo. dummy to check syntax errors of document sources - goto end -) - -if "%1" == "clean" ( - for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i - del /q /s %BUILDDIR%\* - goto end -) - - -REM Check if sphinx-build is available and fallback to Python version if any -%SPHINXBUILD% 1>NUL 2>NUL -if errorlevel 9009 goto sphinx_python -goto sphinx_ok - -:sphinx_python - -set SPHINXBUILD=python -m sphinx.__init__ -%SPHINXBUILD% 2> nul -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -:sphinx_ok - - -if "%1" == "html" ( - %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/html. - goto end -) - -if "%1" == "dirhtml" ( - %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. - goto end -) - -if "%1" == "singlehtml" ( - %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. - goto end -) - -if "%1" == "pickle" ( - %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the pickle files. - goto end -) - -if "%1" == "json" ( - %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the JSON files. - goto end -) - -if "%1" == "htmlhelp" ( - %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run HTML Help Workshop with the ^ -.hhp project file in %BUILDDIR%/htmlhelp. - goto end -) - -if "%1" == "qthelp" ( - %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run "qcollectiongenerator" with the ^ -.qhcp project file in %BUILDDIR%/qthelp, like this: - echo.^> qcollectiongenerator %BUILDDIR%\qthelp\disco.qhcp - echo.To view the help file: - echo.^> assistant -collectionFile %BUILDDIR%\qthelp\disco.ghc - goto end -) - -if "%1" == "devhelp" ( - %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. - goto end -) - -if "%1" == "epub" ( - %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub file is in %BUILDDIR%/epub. - goto end -) - -if "%1" == "epub3" ( - %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. - goto end -) - -if "%1" == "latex" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdf" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf - cd %~dp0 - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdfja" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf-ja - cd %~dp0 - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "text" ( - %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The text files are in %BUILDDIR%/text. - goto end -) - -if "%1" == "man" ( - %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The manual pages are in %BUILDDIR%/man. - goto end -) - -if "%1" == "texinfo" ( - %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. - goto end -) - -if "%1" == "gettext" ( - %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The message catalogs are in %BUILDDIR%/locale. - goto end -) - -if "%1" == "changes" ( - %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes - if errorlevel 1 exit /b 1 - echo. - echo.The overview file is in %BUILDDIR%/changes. - goto end -) - -if "%1" == "linkcheck" ( - %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck - if errorlevel 1 exit /b 1 - echo. - echo.Link check complete; look for any errors in the above output ^ -or in %BUILDDIR%/linkcheck/output.txt. - goto end -) - -if "%1" == "doctest" ( - %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest - if errorlevel 1 exit /b 1 - echo. - echo.Testing of doctests in the sources finished, look at the ^ -results in %BUILDDIR%/doctest/output.txt. - goto end -) - -if "%1" == "coverage" ( - %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage - if errorlevel 1 exit /b 1 - echo. - echo.Testing of coverage in the sources finished, look at the ^ -results in %BUILDDIR%/coverage/python.txt. - goto end -) - -if "%1" == "xml" ( - %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The XML files are in %BUILDDIR%/xml. - goto end -) - -if "%1" == "pseudoxml" ( - %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. - goto end -) - -if "%1" == "dummy" ( - %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. Dummy builder generates no files. - goto end -) - -:end diff --git a/docs/tutorial.rst b/docs/tutorial.rst deleted file mode 100644 index 4aed0ba..0000000 --- a/docs/tutorial.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. currentmodule:: disco - -Tutorial -======== - diff --git a/docs/utilities.rst b/docs/utilities.rst deleted file mode 100644 index 70fdd0b..0000000 --- a/docs/utilities.rst +++ /dev/null @@ -1,27 +0,0 @@ -.. currentmodule:: disco - -Utilities -========= - -This section details information about various utilities provided in the disco -package, which aid the development and runtime management of disco clients/bots. -Generally these utilties are situational, and can be enabled depending on -various scenarious developers and users may find themselves in. - -Manhole -------- - -The manhole utilty is a backdoor server that allows opening a interactive REPL -while the client is running. This can be very useful for attaching and -inspecting runtime state, without distribing the normal client operations. To -enable the backdoor, simply set the -:attr:`disco.client.ClientConfig.manhole_enable` setting, and tweak -:attr:`disco.client.ClientConfig.manhole_bind` settings based on the connection -parameters you'd like. - -It's recommended you connect to the manhole via ``rlwrap`` and ``netcat``, which -will give a proper TTY-like readline experience. For example: - -.. sourcecode:: bash - - rlwrap netcat localhost 8484 diff --git a/examples/basic_plugin.py b/examples/basic_plugin.py index 40b01d6..27e8d35 100644 --- a/examples/basic_plugin.py +++ b/examples/basic_plugin.py @@ -24,7 +24,7 @@ class BasicPlugin(Plugin): c.delete(reason='TEST REASONS2') @Plugin.command('echo', '') - def on_test_command(self, event, content): + def on_echo_command(self, event, content): event.msg.reply(content) @Plugin.command('spam', ' ') @@ -78,3 +78,11 @@ class BasicPlugin(Plugin): event.msg.reply('```\n{}\n```'.format( '\n'.join(parts) )) + + @Plugin.command('test', parser=True) + @Plugin.parser.add_argument('-a', '--asdf', help='wow') + @Plugin.parser.add_argument('--help', action='store_true') + def on_test(self, event, args): + if args.help: + return event.msg.reply(event.parser.format_help()) + event.msg.reply(args.asdf) diff --git a/requirements.txt b/requirements.txt index a0de4f3..e10e806 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ gevent==1.2.1 -holster==1.0.14 +holster==1.0.15 inflection==0.3.1 requests==2.13.0 six==1.10.0 websocket-client==0.40.0 +pyyaml==3.12 diff --git a/setup.py b/setup.py index 2b2a0f1..0fb1232 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,10 @@ with open('README.md') as f: extras_require = { 'voice': ['pynacl==1.1.2'], - 'performance': ['erlpack==0.3.2'], + 'music': ['youtube_dl==2017.4.26'], + 'performance': ['erlpack==0.3.2', 'ujson==1.35'], + 'sharding': ['gipc==0.6.0'], + 'docs': ['biblio==0.0.2'], } setup( diff --git a/tests/test_bot.py b/tests/test_bot.py index 566de0a..fafc875 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -5,6 +5,10 @@ from disco.bot.bot import Bot from disco.bot.command import Command +class Object(object): + pass + + class MockBot(Bot): @property def commands(self): @@ -27,6 +31,10 @@ class TestBot(TestCase): 'copez': 'cope', }) + self.assertDictEqual(self.bot.compute_group_abbrev(['test']), { + 'test': 't', + }) + def test_command_abbreivation_conflicting(self): groups = ['cat', 'cap', 'caz', 'cas'] result = self.bot.compute_group_abbrev(groups) @@ -45,3 +53,19 @@ class TestBot(TestCase): match = self.bot._commands[0].compiled_regex.match('test0 123 456') self.assertEqual(match.group(1).strip(), 'test0') self.assertEqual(match.group(2).strip(), '123 456') + + def test_command_grouping_greadyness(self): + plugin = Object() + plugin.bot = self.bot + + self.bot._commands = [ + Command(plugin, None, 'a', group='test'), + Command(plugin, None, 'b', group='test') + ] + + self.bot.recompute() + self.assertNotEqual(self.bot.command_matches_re.match('test a'), None) + self.assertNotEqual(self.bot.command_matches_re.match('te a'), None) + self.assertNotEqual(self.bot.command_matches_re.match('t b'), None) + self.assertEqual(self.bot.command_matches_re.match('testing b'), None) + self.assertEqual(self.bot.command_matches_re.match('testlmao a'), None) diff --git a/tests/test_user.py b/tests/test_user.py new file mode 100644 index 0000000..89eaca6 --- /dev/null +++ b/tests/test_user.py @@ -0,0 +1,22 @@ +from unittest import TestCase + +from disco.types.user import User, DefaultAvatars + + +class TestChannel(TestCase): + def test_user_avatar(self): + u = User( + id=12345, + username='test123', + avatar='1234567890abcdefghijkl', + discriminator='1234', + bot=False) + + self.assertEqual( + u.avatar_url, 'https://cdn.discordapp.com/avatars/12345/1234567890abcdefghijkl.webp?size=1024' + ) + + def test_user_default_avatar(self): + u = User(id=123456, discriminator='1234') + self.assertEqual(u.default_avatar, DefaultAvatars.RED) + self.assertEqual(u.avatar_url, 'https://cdn.discordapp.com/embed/avatars/4.png')