Python discord.py() Examples

The following are 30 code examples of discord.py(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord , or try the search function .
Example #1
Source File: meta.py    From discordbot.py with MIT License 7 votes vote down vote up
def on_command_error(self, error, ctx):
        ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure,
                   commands.CommandNotFound, commands.UserInputError, discord.HTTPException)
        error = getattr(error, 'original', error)

        if isinstance(error, ignored):
            return

        if ctx.message.server:
            fmt = 'Channel: {0} (ID: {0.id})\nGuild: {1} (ID: {1.id})'
        else:
            fmt = 'Channel: {0} (ID: {0.id})'

        exc = traceback.format_exception(type(error), error, error.__traceback__, chain=False)
        description = '```py\n%s\n```' % ''.join(exc)
        time = datetime.datetime.utcnow()

        name = ctx.command.qualified_name
        author = '{0} (ID: {0.id})'.format(ctx.message.author)
        location = fmt.format(ctx.message.channel, ctx.message.server)

        message = '{0} at {1}: Called by: {2} in {3}. More info: {4}'.format(name, time, author, location, description)

        self.bot.logs['discord'].critical(message) 
Example #2
Source File: eventmixin.py    From Trusty-cogs with MIT License 6 votes vote down vote up
def member_can_run(self, ctx: commands.Context) -> bool:
        """Check if a user can run a command.
        This will take the current context into account, such as the
        server and text channel.
        https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/release/3.0.0/redbot/cogs/permissions/permissions.py
        """
        command = ctx.message.content.replace(ctx.prefix, "")
        com = ctx.bot.get_command(command)
        if com is None:
            return False
        else:
            try:
                testcontext = await ctx.bot.get_context(ctx.message, cls=commands.Context)
                to_check = [*reversed(com.parents)] + [com]
                can = False
                for cmd in to_check:
                    can = await cmd.can_run(testcontext)
                    if can is False:
                        break
            except commands.CheckFailure:
                can = False
        return can 
Example #3
Source File: repl.py    From Dumb-Cogs with MIT License 6 votes vote down vote up
def wait_for_reaction_remove(bot, emoji=None, *, user=None,
                                   timeout=None, message=None, check=None):
    """Waits for a reaction to be removed by a user from a message within a time period.
    Made to act like other discord.py wait_for_* functions but is not fully implemented.

    Because of that, wait_for_reaction_remove(self, emoji: list, user, message, timeout=None)
    is a better representation of this function's def

    returns the actual event or None if timeout
    """
    if not (emoji and message) or isinstance(emoji, str):
        raise NotImplementedError("wait_for_reaction_remove(self, emoji, "
                                  "message, user=None, timeout=None, "
                                  "check=None) is a better representation "
                                  "of this function definition")
    remove_event = ReactionRemoveEvent(emoji, user, check=check)
    _reaction_remove_events[message.id] = remove_event
    done, pending = await asyncio.wait([remove_event.wait()],
                                       timeout=timeout)
    res = _reaction_remove_events.pop(message.id)
    try:
        return done.pop().result() and res
    except:
        return None 
Example #4
Source File: api.py    From Trusty-cogs with MIT License 6 votes vote down vote up
def local_perms(self, guild: discord.Guild, author: discord.Member) -> bool:
        """Check the user is/isn't locally whitelisted/blacklisted.
            https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/release/3.0.0/redbot/core/global_checks.py
        """
        try:
            return await self.bot.allowed_by_whitelist_blacklist(
                author, who_id=author.id, guild_id=guild.id, role_ids=[r.id for r in author.roles]
            )
        except AttributeError:
            if await self.bot.is_owner(author):
                return True
            elif guild is None:
                return True
            guild_settings = self.bot.db.guild(guild)
            local_blacklist = await guild_settings.blacklist()
            local_whitelist = await guild_settings.whitelist()

            _ids = [r.id for r in author.roles if not r.is_default()]
            _ids.append(author.id)
            if local_whitelist:
                return any(i in local_whitelist for i in _ids)

            return not any(i in local_blacklist for i in _ids) 
Example #5
Source File: __main__.py    From discord.py with MIT License 6 votes vote down vote up
def show_version():
    entries = []

    entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info))
    version_info = discord.version_info
    entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info))
    if version_info.releaselevel != 'final':
        pkg = pkg_resources.get_distribution('discord.py')
        if pkg:
            entries.append('    - discord.py pkg_resources: v{0}'.format(pkg.version))

    entries.append('- aiohttp v{0.__version__}'.format(aiohttp))
    entries.append('- websockets v{0.__version__}'.format(websockets))
    uname = platform.uname()
    entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname))
    print('\n'.join(entries)) 
Example #6
Source File: info.py    From Discord-SelfBot with MIT License 6 votes vote down vote up
def about(self, ctx):
        """Infos about the SelfBot."""
        embed = discord.Embed()
        embed.set_author(name="Igneel's SelfBot", url="https://igneeldxd.github.io/Discord-SelfBot/")
        embed.description = "https://igneeldxd.github.io/Discord-SelfBot/\nThis is a Selfbot written by IgneelDxD#6666\nFor support or feedback you can join my [Server](https://discord.gg/DJK8h3n)"
        embed.colour = discord.Color.purple()

        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://api.github.com/repos/IgneelDxD/Discord-SelfBot/commits") as resp:
                result = json.loads(await resp.text())
                form = '[``{0}``](https://github.com/IgneelDxD/Discord-SelfBot/commit/{0}) {1} ({2})'
                com0 = form.format(result[0]['sha'][:7], result[0]['commit']['message'], getAgo(parser.parse(result[0]['commit']['author']['date'], ignoretz=True)))
                com1 = form.format(result[1]['sha'][:7], result[1]['commit']['message'], getAgo(parser.parse(result[1]['commit']['author']['date'], ignoretz=True)))
                embed.add_field(name='Latest Changes', value=f'{com0}\n{com1}')
        embed.set_thumbnail(url="https://i.imgur.com/cD51k3R.png")
        embed.set_footer(text='Made with discord.py | rewrite is the future!', icon_url='https://i.imgur.com/MyEXmz8.png')
        await edit(ctx, embed=embed)

    # User info on Server 
Example #7
Source File: util.py    From DueUtil with GNU General Public License v3.0 6 votes vote down vote up
def botinfo(ctx, **_):
    """
    [CMD_KEY]botinfo

    General information about DueUtil.
    """

    info_embed = discord.Embed(title="DueUtil's Information", type="rich", color=gconf.DUE_COLOUR)
    info_embed.description = "DueUtil is customizable bot to add fun commands, quests and battles to your server."
    info_embed.add_field(name="Created by", value="[MacDue#4453](https://dueutil.tech/)")
    info_embed.add_field(name="Framework",
                         value="[discord.py %s :two_hearts:](http://discordpy.readthedocs.io/en/latest/)"
                               % discord.__version__)
    info_embed.add_field(name="Version", value=gconf.VERSION),
    info_embed.add_field(name="Invite Due!", value="https://dueutil.tech/invite", inline=False)
    info_embed.add_field(name="Support server",
                         value="For help with the bot or a laugh join **https://discord.gg/n4b94VA**!")
    await util.say(ctx.channel, embed=info_embed) 
Example #8
Source File: utils.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def cleanup_code(content: str) -> str:
    """
    Automatically removes code blocks from the code.

    Parameters
    ----------
    content : str
        The content to be cleaned.

    Returns
    -------
    str
        The cleaned content.
    """
    # remove ```py\n```
    if content.startswith("```") and content.endswith("```"):
        return "\n".join(content.split("\n")[1:-1])

    # remove `foo`
    return content.strip("` \n") 
Example #9
Source File: utility.py    From discord_bot with MIT License 5 votes vote down vote up
def source(self, ctx, *, command: str = None):
        '''Zeigt den Quellcode für einen Befehl auf GitHub an

        Beispiel:
        -----------

        :source kawaii
        '''
        source_url = 'https://github.com/Der-Eddy/discord_bot'
        if command is None:
            await ctx.send(source_url)
            return

        obj = self.bot.get_command(command.replace('.', ' '))
        if obj is None:
            return await ctx.send(':x: Konnte den Befehl nicht finden')

        # since we found the command we're looking for, presumably anyway, let's
        # try to access the code itself
        src = obj.callback.__code__
        lines, firstlineno = inspect.getsourcelines(src)
        sourcecode = inspect.getsource(src).replace('```', '')
        if not obj.callback.__module__.startswith('discord'):
            # not a built-in command
            location = os.path.relpath(src.co_filename).replace('\\', '/')
        else:
            location = obj.callback.__module__.replace('.', '/') + '.py'
            source_url = 'https://github.com/Rapptz/discord.py'

        if len(sourcecode) > 1900:
            final_url = '{}/blob/master/{}#L{}-L{}'.format(source_url, location, firstlineno, firstlineno + len(lines) - 1)
        else:
            final_url = '<{}/blob/master/{}#L{}-L{}>\n```Python\n{}```'.format(source_url, location, firstlineno, firstlineno + len(lines) - 1, sourcecode)

        await ctx.send(final_url) 
Example #10
Source File: api.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def check_ignored_channel(self, message: discord.Message) -> bool:
        """
        https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/release/3.0.0/redbot/cogs/mod/mod.py#L1273
        """
        if version_info >= VersionInfo.from_str("3.3.6"):
            ctx = await self.bot.get_context(message)
            return await self.bot.ignored_channel_or_guild(ctx)
        # everything below this can be removed at a later date when support
        # for previous versions are no longer required.
        channel = cast(discord.TextChannel, message.channel)
        guild = channel.guild
        author = cast(discord.Member, message.author)
        mod = self.bot.get_cog("Mod")
        if mod is None:
            return True
        perms = channel.permissions_for(author)
        surpass_ignore = (
            isinstance(channel, discord.abc.PrivateChannel)
            or perms.manage_guild
            or await self.bot.is_owner(author)
            or await self.bot.is_admin(author)
        )
        if surpass_ignore:
            return True
        guild_ignored = await mod.settings.guild(guild).ignored()
        chann_ignored = await mod.settings.channel(channel).ignored()
        return not (guild_ignored or chann_ignored and not perms.manage_channels) 
Example #11
Source File: utility.py    From discord_bot with MIT License 5 votes vote down vote up
def about(self, ctx):
        '''Info über mich'''
        msg = 'Shinobu Oshino gehört wohl zu den mysteriösesten Charakteren in Bakemonogatari. Sie war bis vorletzten Frühling ein hochangesehener, adeliger, skrupelloser Vampir, der weit über 500 Jahre alt ist. Gnadenlos griff sie Menschen an und massakrierte sie nach Belieben. Auch Koyomi Araragi wurde von ihr attackiert und schwer verwundet. Nur durch das Eingreifen des Exorzisten Meme Oshino konnte Kiss-shot Acerola-orion Heart-under-blade, wie sie damals bekannt war, bezwungen werden. Dabei verlor sie jedoch all ihre Erinnerungen und wurde von einer attraktiven, erwachsenen Frau in einen unschuldigen Mädchenkörper verwandelt.\n\n'
        msg += 'Seitdem lebt sie zusammen mit Meme in einem verlassenen Gebäude und wurde von ihm aufgenommen. Er gab ihr auch ihren Namen Shinobu. Das Vampirblut in ihr verlangt immer noch nach Opfern und da sich Koyomi in gewisser Art und Weise schuldig fühlt, stellt er sich regelmäßig als Nahrungsquelle für Shinobu zur Verfügung.\n\n'
        msg += 'Quelle: http://www.anisearch.de/character/6598,shinobu-oshino/\n\n'

        embed = discord.Embed(color=ctx.me.top_role.colour)
        embed.set_footer(text='Dieser Bot ist außerdem free, Open-Source, in Python und mit Hilfe von discord.py geschrieben! https://github.com/Der-Eddy/discord_bot\n')
        embed.set_thumbnail(url=ctx.me.avatar_url)
        embed.add_field(name='**:information_source: Shinobu Oshino (500 Jahre alt)**', value=msg, inline=False)
        await ctx.send(embed=embed) 
Example #12
Source File: utility.py    From discord_bot with MIT License 5 votes vote down vote up
def status(self, ctx):
        '''Infos über den Bot'''
        timeUp = time.time() - self.bot.startTime
        hours = timeUp / 3600
        minutes = (timeUp / 60) % 60
        seconds = timeUp % 60

        admin = self.bot.AppInfo.owner
        users = 0
        channel = 0
        if len(self.bot.commands_used.items()):
            commandsChart = sorted(self.bot.commands_used.items(), key=lambda t: t[1], reverse=False)
            topCommand = commandsChart.pop()
            commandsInfo = '{} (Top-Command: {} x {})'.format(sum(self.bot.commands_used.values()), topCommand[1], topCommand[0])
        else:
            commandsInfo = str(sum(self.bot.commands_used.values()))
        for guild in self.bot.guilds:
            users += len(guild.members)
            channel += len(guild.channels)

        embed = discord.Embed(color=ctx.me.top_role.colour)
        embed.set_footer(text='Dieser Bot ist Open-Source auf GitHub: https://github.com/Der-Eddy/discord_bot')
        embed.set_thumbnail(url=ctx.me.avatar_url)
        embed.add_field(name='Admin', value=admin, inline=False)
        embed.add_field(name='Uptime', value='{0:.0f} Stunden, {1:.0f} Minuten und {2:.0f} Sekunden\n'.format(hours, minutes, seconds), inline=False)
        embed.add_field(name='Beobachtete Benutzer', value=users, inline=True)
        embed.add_field(name='Beobachtete Server', value=len(self.bot.guilds), inline=True)
        embed.add_field(name='Beobachtete Channel', value=channel, inline=True)
        embed.add_field(name='Ausgeführte Commands', value=commandsInfo, inline=True)
        embed.add_field(name='Bot Version', value=self.bot.botVersion, inline=True)
        embed.add_field(name='Discord.py Version', value=discord.__version__, inline=True)
        embed.add_field(name='Python Version', value=platform.python_version(), inline=True)
        # embed.add_field(name='Speicher Auslastung', value=f'{round(memory_usage(-1)[0], 3)} MB', inline=True)
        embed.add_field(name='Betriebssystem', value=f'{platform.system()} {platform.release()} {platform.version()}', inline=False)
        await ctx.send('**:information_source:** Informationen über diesen Bot:', embed=embed) 
Example #13
Source File: bot.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def on_ready(self):
        """Things to run when the bot has initialized and signed in"""
        DOZER_LOGGER.info('Signed in as {}#{} ({})'.format(self.user.name, self.user.discriminator, self.user.id))
        if self.config['is_backup']:
            status = discord.Status.dnd
        else:
            status = discord.Status.online
        game = discord.Game(name='%shelp | %d guilds' % (self.config['prefix'], len(self.guilds)))
        try:
            await self.change_presence(activity=game, status=status)
        except TypeError:
            DOZER_LOGGER.warning("You are running an older version of the discord.py rewrite (with breaking changes)! "
                                 "To upgrade, run `pip install -r requirements.txt --upgrade`") 
Example #14
Source File: run.py    From MusicBot with MIT License 5 votes vote down vote up
def req_check_deps():
    try:
        import discord
        if discord.version_info.major < 1:
            log.critical("This version of MusicBot requires a newer version of discord.py (1.0+). Your version is {0}. Try running update.py.".format(discord.__version__))
            bugger_off()
    except ImportError:
        # if we can't import discord.py, an error will be thrown later down the line anyway
        pass 
Example #15
Source File: info.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def about(self, ctx: NabCtx):
        """Shows basic information about the bot."""
        embed = discord.Embed(description=ctx.bot.description, colour=discord.Colour.blurple())
        embed.set_author(name="NabBot", url="https://github.com/NabDev/NabBot",
                         icon_url="https://github.com/fluidicon.png")
        prefixes = list(config.command_prefix)
        if ctx.guild:
            prefixes = await get_server_property(ctx.pool, ctx.guild.id, "prefixes", prefixes)
        prefixes_str = "\n".join(f"- `{p}`" for p in prefixes)
        embed.add_field(name="Prefixes", value=prefixes_str, inline=False)
        embed.add_field(name="Authors", value="\u2023 [Galarzaa90](https://github.com/Galarzaa90)\n"
                                              "\u2023 [Nezune](https://github.com/Nezune)")
        embed.add_field(name="Created", value="March 30th 2016")
        embed.add_field(name="Version", value=f"v{self.bot.__version__}")
        embed.add_field(name="Platform", value="Python "
                                               "([discord.py](https://github.com/Rapptz/discord.py/tree/rewrite))")
        embed.add_field(name="Servers", value=f"{len(self.bot.guilds):,}")
        embed.add_field(name="Users", value=f"{len(self.bot.users):,}")
        embed.add_field(name="Links", inline=False,
                        value="[Invite NabBot](https://nabbot.xyz/)  |  "
                              "[Support Server](https://support.nabbot.xyz/)  |  "
                              "[Docs](https://docs.nabbot.xyz/)  |  "
                              "[Donate](https://donate.nabbot.xyz/) | "
                              "[Patreon](https://patreon.nabbot.xyz)")
        embed.set_footer(text=f"Uptime | {parse_uptime(self.bot.start_time, True)}")
        await ctx.send(embed=embed) 
Example #16
Source File: HelpPaginator.py    From DJ5n4k3 with MIT License 5 votes vote down vote up
def _command_signature(cmd):
    # this is modified from discord.py source
    # which I wrote myself lmao

    result = [cmd.qualified_name]
    if cmd.usage:
        result.append(cmd.usage)
        return ' '.join(result)

    params = cmd.clean_params
    if not params:
        return ' '.join(result)

    for name, param in params.items():
        if param.default is not param.empty:
            # We don't want None or '' to trigger the [name=value] case and instead it should
            # do [name] since [name=None] or [name=] are not exactly useful for the user.
            should_print = param.default if isinstance(param.default, str) else param.default is not None
            if should_print:
                result.append(f'[{name}={param.default!r}]')
            else:
                result.append(f'[{name}]')
        elif param.kind == param.VAR_POSITIONAL:
            result.append(f'[{name}...]')
        else:
            result.append(f'<{name}>')

    return ' '.join(result) 
Example #17
Source File: extendedmodlog.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def _set_embds(self, ctx: commands.Context, set_to: bool, *events: EventChooser) -> None:
        """
            Set modlog events to use embeds or text

            `set_to` The desired embed setting either on or off.

            `[events...]` must be any of the following options (more than one event can be provided at once):
                `message_edit`
                `message_delete`
                `user_change`
                `role_change`
                `role_create`
                `role_delete`
                `voice_change`
                `user_join`
                `user_left`
                `channel_change`
                `channel_create`
                `channel_delete`
                `guild_change`
                `emoji_change`
                `commands_used`

                **Requires Red 3.3 and discord.py 1.3**
                `invite_created`
                `invite_deleted`
        """
        if len(events) == 0:
            return await ctx.send(_("You must provide which events should be included."))
        if ctx.guild.id not in self.settings:
            self.settings[ctx.guild.id] = inv_settings
        for event in events:
            self.settings[ctx.guild.id][event]["embed"] = set_to
            await self.config.guild(ctx.guild).set_raw(
                event, value=self.settings[ctx.guild.id][event]
            )
        await ctx.send(
            _("{event} embed logs have been set to {set_to}").format(
                event=humanize_list(events), set_to=str(set_to)
            )
        ) 
Example #18
Source File: run.py    From MusicBot with MIT License 5 votes vote down vote up
def req_ensure_env():
    log.info("Ensuring we're in the right environment")

    if os.environ.get('APP_ENV') != 'docker' and not os.path.isdir(b64decode('LmdpdA==').decode('utf-8')):
        log.critical(b64decode('Qm90IHdhc24ndCBpbnN0YWxsZWQgdXNpbmcgR2l0LiBSZWluc3RhbGwgdXNpbmcgaHR0cDovL2JpdC5seS9tdXNpY2JvdGRvY3Mu').decode('utf-8'))
        bugger_off()

    try:
        assert os.path.isdir('config'), 'folder "config" not found'
        assert os.path.isdir('musicbot'), 'folder "musicbot" not found'
        assert os.path.isfile('musicbot/__init__.py'), 'musicbot folder is not a Python module'

        assert importlib.util.find_spec('musicbot'), "musicbot module is not importable"
    except AssertionError as e:
        log.critical("Failed environment check, %s", e)
        bugger_off()

    try:
        os.mkdir('musicbot-test-folder')
    except Exception:
        log.critical("Current working directory does not seem to be writable")
        log.critical("Please move the bot to a folder that is writable")
        bugger_off()
    finally:
        rmtree('musicbot-test-folder', True)

    if sys.platform.startswith('win'):
        log.info("Adding local bins/ folder to path")
        os.environ['PATH'] += ';' + os.path.abspath('bin/')
        sys.path.append(os.path.abspath('bin/')) # might as well 
Example #19
Source File: playlist.py    From Wavelink with MIT License 5 votes vote down vote up
def start_nodes(self):
        await self.bot.wait_until_ready()

        # Initiate our nodes. For this example we will use one server.
        # Region should be a discord.py guild.region e.g sydney or us_central (Though this is not technically required)
        node = await self.bot.wavelink.initiate_node(host='x.x.x.x',
                                                     port=2333,
                                                     rest_uri='http://x.x.x.x:2333',
                                                     password='youshallnotpass',
                                                     identifier='TEST',
                                                     region='us_central')

        # Set our node hook callback
        node.set_hook(self.on_event_hook) 
Example #20
Source File: main.py    From discord_bot with MIT License 5 votes vote down vote up
def _randomGame():
    #Check games.py to change the list of "games" to be played
    while True:
        guildCount = len(bot.guilds)
        memberCount = len(list(bot.get_all_members()))
        randomGame = random.choice(loadconfig.__games__)
        await bot.change_presence(activity=discord.Activity(type=randomGame[0], name=randomGame[1].format(guilds = guildCount, members = memberCount)))
        await asyncio.sleep(loadconfig.__gamesTimer__) 
Example #21
Source File: main.py    From discord_bot with MIT License 5 votes vote down vote up
def on_error(event, *args, **kwargs):
    if bot.dev:
        traceback.print_exc()
    else:
        embed = discord.Embed(title=':x: Event Error', colour=0xe74c3c) #Red
        embed.add_field(name='Event', value=event)
        embed.description = '```py\n%s\n```' % traceback.format_exc()
        embed.timestamp = datetime.datetime.utcnow()
        try:
            await bot.AppInfo.owner.send(embed=embed)
        except:
            pass 
Example #22
Source File: basic.py    From Wavelink with MIT License 5 votes vote down vote up
def start_nodes(self):
        await self.bot.wait_until_ready()

        # Initiate our nodes. For this example we will use one server.
        # Region should be a discord.py guild.region e.g sydney or us_central (Though this is not technically required)
        await self.bot.wavelink.initiate_node(host='0.0.0.0',
                                              port=2333,
                                              rest_uri='http://0.0.0.0:2333',
                                              password='youshallnotpass',
                                              identifier='TEST',
                                              region='us_central') 
Example #23
Source File: starboard.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def colour_starboard(
        self, ctx: commands.Context, starboard: StarboardExists, colour: Union[discord.Colour, str]
    ) -> None:
        """
            Change the default colour for a starboard

            `<name>` is the name of the starboard to toggle
            `<colour>` The colour to use for the starboard embed
            This can be a hexcode or integer for colour or `author/member/user` to use
            the original posters colour or `bot` to use the bots colour.
            Colour also accepts names from [discord.py](https://discordpy.readthedocs.io/en/latest/api.html#colour)
        """
        guild = ctx.guild
        if isinstance(colour, str):
            colour = colour.lower()
            if colour not in ["user", "member", "author", "bot"]:
                return await ctx.send(_("The provided colour option is not valid."))
            else:
                starboard.colour = colour
        else:
            self.starboards[ctx.guild.id][starboard.name].colour = colour.value
        await self._save_starboards(guild)
        msg = _("Starboard `{name}` colour set to `{colour}`.").format(
            name=starboard.name, colour=starboard.colour
        )
        await ctx.send(msg) 
Example #24
Source File: dev.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def get_syntax_error(e):
        """Format a syntax error to send to the user.

        Returns a string representation of the error formatted as a codeblock.
        """
        if e.text is None:
            return box("{0.__class__.__name__}: {0}".format(e), lang="py")
        return box("{0.text}{1:>{0.offset}}\n{2}: {0}".format(e, "^", type(e).__name__), lang="py") 
Example #25
Source File: dev.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def cleanup_code(content):
        """Automatically removes code blocks from the code."""
        # remove ```py\n```
        if content.startswith("```") and content.endswith("```"):
            return START_CODE_BLOCK_RE.sub("", content)[:-3]

        # remove `foo`
        return content.strip("` \n") 
Example #26
Source File: react_roles.py    From ZeCogsV3 with GNU General Public License v3.0 5 votes vote down vote up
def maybe_update_guild(self, guild: discord.Guild):
        # ctx.guild.chunked is innaccurate, discord.py#1638
        if not guild.unavailable and guild.large:
            if not guild.chunked or any(m.joined_at is None for m in guild.members):
                await self.bot.request_offline_members(guild) 
Example #27
Source File: birthdays.py    From ZeCogsV3 with GNU General Public License v3.0 5 votes vote down vote up
def maybe_update_guild(self, guild: discord.Guild):
        # ctx.guild.chunked is innaccurate, discord.py#1638
        if not guild.unavailable and guild.large:
            if not guild.chunked or any(m.joined_at is None for m in guild.members):
                await self.bot.request_offline_members(guild) 
Example #28
Source File: music.py    From Lavalink.py with MIT License 5 votes vote down vote up
def track_hook(self, event):
        if isinstance(event, lavalink.events.QueueEndEvent):
            # When this track_hook receives a "QueueEndEvent" from lavalink.py
            # it indicates that there are no tracks left in the player's queue.
            # To save on resources, we can tell the bot to disconnect from the voicechannel.
            guild_id = int(event.player.guild_id)
            await self.connect_to(guild_id, None) 
Example #29
Source File: repl.py    From Dumb-Cogs with MIT License 5 votes vote down vote up
def repl_format_source(self, thing):
        """returns get_source formatted to be used in repl

        rtfs originated as this alias:
        debug (lambda cmd, bot=bot: (lambda f, out: out[0] if len(out) == 1 else (f(f,out[1:5] + (['{} more pages remaining..\njust tell them to read the actual source file man.'.format(len(out)-5)] if len(out) > 5 else [])) or out[0]))((lambda self, more: None if not more else bot.loop.create_task(bot.say('``'+'`py\n'+more.pop(0)+'``'+'`')).add_done_callback(self(self, more))), list(pagify((lambda ic, fc, pg: (lambda fcs: ic.getsourcefile(fc).split('/')[-1]+'\nline: {}'.format(fcs[1])+'``'+'`'+'\n'+'``'+'`py\n'+''.join(fcs[0]))(ic.getsourcelines(fc)))(__import__('inspect'), (cmd if not isinstance(cmd, str) else (lambda f, ms: f(f, __import__(ms.pop(0)), ms))((lambda f, prev, ms: getattr(prev, 'callback') if hasattr(prev, 'callback') else prev if not ms else f(f, getattr(prev, ms.pop(0)), ms)), cmd.split('.')) if '.' in cmd else (lambda end, cmds: end(end, cmds, bot.commands[cmds.pop(0)]).callback)((lambda end, names, cmd: cmd if not names else end(end, names, cmd.commands[names.pop(0)])), cmd.split()) ), __import__('cogs').utils.chat_formatting.pagify), delims=['\n', ' '], escape=False, shorten_by=12)) ))
        """
        source = self.get_source(thing)
        msg =  source.filename.split('/')[-1] + '\n'
        msg += 'line: {}'.format(source.line_number)
        msg += '``'+'`\n`'+'``py\n'  # codeblock break
        msg += source.source
        return msg 
Example #30
Source File: info.py    From rewrite with GNU General Public License v3.0 5 votes vote down vote up
def help(self, ctx):
        embed = discord.Embed(title="Himebot - The only music bot you'll ever need",
                              description="For extra support, join [Hime's support server](https://discord.gg/BCAF7rH)",
                              colour=COLOR)
        embed.set_thumbnail(url=self.bot.user.avatar_url)
        embed.add_field(name="Commands",
                        value="Hime's complete commands list could be"
                              " found over at [Hime's website](https://himebot.xyz/features_and_commands.html)")
        embed.add_field(name="Getting Started",
                        value=f"To get started using the Hime, join a voice channel and then use the play command: "
                              f"`{self.bot.bot_settings.prefix}play [song name]` the bot will then join the channel "
                              f"and play the requested song!")
        embed.set_footer(text=f"Created by init0#8366, flamekong#0009 & repyh#2900 using discord.py@v1.0 Rewrite")
        await ctx.send(embed=embed)