How to use discord - 10 common examples

To help you get started, we’ve selected a few discord examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DiscordFederation / Erin / tests / fake_plugins / schema / schema_extension.py View on Github external
    @commands.command(name="schema")
    async def broken(self, ctx):
        await ctx.send("Sorry, I'm a broken schema!")
github CraftSpider / TalosBot / tests / dpytest / runner.py View on Github external
import sys
import asyncio
import logging
import discord
import typing

from . import backend as back


class RunnerConfig(typing.NamedTuple):
    client: discord.Client
    guilds: typing.List[discord.Guild]
    channels: typing.List[discord.abc.GuildChannel]
    members: typing.List[discord.Member]


log = logging.getLogger("discord.ext.tests")
cur_config = None
sent_queue = asyncio.queues.Queue()
error_queue = asyncio.queues.Queue()


async def run_all_events():
    if sys.version_info[1] >= 7:
        pending = filter(lambda x: x._coro.__name__ == "_run_event", asyncio.all_tasks())
    else:
        pending = filter(lambda x: x._coro.__name__ == "_run_event", asyncio.Task.all_tasks())
github NotSoSuper / NotSoBot / mods / Wc.py View on Github external
	@commands.group(pass_context=True, name='wc', aliases=['wordcloud', 'wordc'], invoke_without_command=True)
	@commands.cooldown(10, 1)
	async def wc(self, ctx, *urls:str):
		max_messages = 500
		custom = False
		if len(urls) == 1:
			if urls[0].isdigit():
				max_messages = int(urls[0])
		elif len(urls) > 1:
			get_images = await self.get_images(ctx, urls=urls, scale=4000)
			if not get_images:
				return
			custom = True
			image, scale, scale_msg = get_images
			image = await self.bytes_download(image[0])
			if scale:
				max_messages = int(scale)
github shibdib / Firetail / firetail / extensions / tokens / tokens.py View on Github external
    @commands.command(name='token')
    @checks.spam_check()
    async def _token(self, ctx):
        token = ctx.message.content.split(' ', 1)[1]
        auth = base64.b64encode(bytes(':'.join([self.config.tokens['client_id'], self.config.tokens['secret']]),
                                      'utf-8'))
        access_token = await self.bot.esi_data.refresh_access_token(token, auth)
        try:
            verify = await self.bot.esi_data.verify_token(access_token['access_token'])
            character_id = verify['CharacterID']
        except:
            return await ctx.send("ERROR: That is not a valid refresh token.")
        expires = float(access_token['expires_in']) + time.time()
        sql = ''' REPLACE INTO access_tokens(character_id,discord_id,refresh_token,access_token,expires)
                  VALUES(?,?,?,?,?) '''
        values = (character_id, ctx.author.id, token, access_token['access_token'], expires)
        await db.execute_sql(sql, values)
github lu-ci / apex-sigma-core / sigma / modules / owner_controls / information / ouserinformation.py View on Github external
async def ouserinformation(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        lookup = pld.args[0].lower()
        if '#' in lookup:
            uname = lookup.split('#')[0].lower()
            udisc = lookup.split('#')[1]
            target = discord.utils.find(lambda u: u.name.lower() == uname and u.discriminator == udisc, cmd.bot.users)
        else:
            try:
                target = await cmd.bot.get_user(int(lookup))
            except ValueError:
                target = None
        if target:
            user_color = await get_image_colors(user_avatar(target))
            response = discord.Embed(color=user_color)
            response.set_author(name=f'{target.display_name}\'s Information', icon_url=user_avatar(target))
            creation_time = arrow.get(target.created_at).format('DD. MMMM YYYY')
            user_text = f'Username: **{target.name}**#{target.discriminator}'
            user_text += f'\nID: **{target.id}**'
            user_text += f'\nBot User: **{target.bot}**'
            user_text += f'\nCreated: **{creation_time}**'
            presence = [g for g in cmd.bot.guilds if g.get_member(target.id)]
            response.add_field(name='User Info', value=user_text)
github lu-ci / apex-sigma / sigma / plugins / administration / pmredirect.py View on Github external
ev.log.info(f'User {author.name} [{author.id}] sent a private message.')
            embed = discord.Embed(color=0x0099FF)
            if args and not ''.join(args) == '':
                embed.add_field(name='Message',
                                value='```\n' + ' '.join(args) + '\n```', inline=False)
            embed.set_footer(text=f'UserID: {author.id}')
            embed.set_author(name=f'{author.name}#{author.discriminator}', icon_url=user_avatar(author))
            if message.attachments:
                attachment_links = ''
                for attachment in message.attachments:
                    if attachment['url'].split('.')[-1] in ['png', 'jpg', 'jpeg', 'gif']:
                        embed.set_image(url=attachment['url'])
                    else:
                        attachment_links += '\n' + attachment['url']
                embed.add_field(name='Attachments', value=attachment_links, inline=False)
            owner = discord.utils.find(lambda usr: usr.id == permitted_id[0], ev.bot.get_all_members())
            await ev.bot.send_message(owner, None, embed=embed)
github paradox-bot / paradox / settingTypes.py View on Github external
if not ctx.server:
            ctx.cmd_err = (1, "This is not valid outside of a server!")
            return None
        userstr = str(userstr)
        if userstr.lower() in ["none", "0"]:
            return None
        if userstr == ".":
            return ctx.ch.id
        chid = userstr.strip('<#@!>')
        if chid.isdigit():
            def is_ch(ch):
                return ch.id == chid
        else:
            def is_ch(ch):
                return userstr.lower() in ch.name.lower()
        ch = discord.utils.find(is_ch, ctx.server.channels)
        if ch:
            return ch.id
        else:
            ctx.cmd_err = (1, "I can't find the channel `{}` in this server!".format(userstr))
            return None
github aikaterna / aikaterna-cogs / tools / tools.py View on Github external
if role is not None:
            perms = iter(role.permissions)
            perms_we_have = ""
            perms_we_dont = ""
            for x in perms:
                if "True" in str(x):
                    perms_we_have += "{0}\n".format(str(x).split("'")[1])
                else:
                    perms_we_dont += "{0}\n".format(str(x).split("'")[1])
            if perms_we_have == "":
                perms_we_have = "None"
            if perms_we_dont == "":
                perms_we_dont = "None"
            msg = discord.Embed(description="Gathering role stats...", colour=role.color)
            if role.color is None:
                role.color = discord.Colour(value=0x000000)
            loadingmsg = await ctx.send(embed=msg)
            em = discord.Embed(colour=role.colour)
            if caller == "invoke":
                em.add_field(name="Server", value=role.guild.name)
            em.add_field(name="Role Name", value=role.name)
            em.add_field(name="Created", value=self._dynamic_time(role.created_at))
            em.add_field(
                name="Users in Role", value=len([m for m in guild.members if role in m.roles])
            )
            em.add_field(name="ID", value=role.id)
            em.add_field(name="Color", value=role.color)
            em.add_field(name="Position", value=role.position)
            em.add_field(name="Valid Permissons", value="{}".format(perms_we_have))
            em.add_field(name="Invalid Permissons", value="{}".format(perms_we_dont))
            em.set_thumbnail(url=role.guild.icon_url)
        try:
github python-discord / bot / bot / cogs / source.py View on Github external
cog_url = f"{Source.BASE_URL}{module_path}#L{cog_lineno}"

        path_segments = module_path.split("/")
        module_desc = "/".join(
            f"[{segment}]({Source.BASE_URL}{'/'.join(path_segments[:idx])})"
            for idx, segment in enumerate(path_segments, start=1)
        )

        embed = Embed(
            title=f":guild_update: View Source Code",
            description=(
                f"```{constants.Bot.prefix}{command}```\n"
                f"**Cog:** [{cog_name}]({cog_url})\n"
                f"**Module:** {module_desc}\n"
            ),
            colour=Colour.blurple(),
            url=command_url,
        )
        embed.set_footer(
            text=f"{end - start + 1} lines total, (L{start}:L{end})",
        )
        return embed