Python discord.ext() Examples

The following are 20 code examples of discord.ext(). 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: repl.py    From Dumb-Cogs with MIT License 6 votes vote down vote up
def rtfs(self, ctx, *, thing: str):
        """tries to show the source file of a thing

        thing may be a non-builtin module, class, method, function, traceback, frame, or code object,
        or if surrounded by single or double quotes,
            a space separated discord.ext.commands call,
            or a period deliminated file/module path as used when importing"""
        msg = ctx.message

        variables = {
            'ctx': ctx,
            'bot': self.bot,
            'message': msg,
            'server': msg.server,
            'channel': msg.channel,
            'author': msg.author
        }

        def call(thing, variables):
            return self.repl_format_source(eval(thing, variables))

        closure = _close(call, thing, variables)
        await self.print_results(ctx, _call_catch_fmt(closure, 0)) 
Example #2
Source File: __init__.py    From code-jam-5 with MIT License 6 votes vote down vote up
def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or('>'),
                         description=description,
                         case_insensitive=True
                         )

        config = Config.load(config_path)

        self.client_id = config.client_id
        self.owner_id = config.owner_id
        self.session = aiohttp.ClientSession(loop=self.loop)
        self.colour = discord.Colour.blurple()
        self.help_command = Help()

        self.db = get_db()

        for ext in extensions:
            try:
                self.load_extension(ext)
            except Exception as e:
                tb.print_exc()
                print(f'Failed to load {ext}: {e}') 
Example #3
Source File: qposts.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def save_q_files(self, post):
        file_id = post["tim"]
        file_ext = post["ext"]
        url = "https://media.8ch.net/file_store/{}{}".format(file_id, file_ext)
        async with self.session.get(url) as resp:
            image = await resp.read()
        with open("data/qposts/files/{}{}".format(file_id, file_ext), "wb") as out:
            out.write(image)
        if "extra_files" in post:
            for file in post["extra_files"]:
                file_id = file["tim"]
                file_ext = file["ext"]
                url = "https://media.8ch.net/file_store/{}{}".format(file_id, file_ext)
                async with self.session.get(url) as resp:
                    image = await resp.read()
                with open("data/qposts/files/{}{}".format(file_id, file_ext), "wb") as out:
                    out.write(image) 
Example #4
Source File: badges.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def badges(self, ctx, *, badge):
        """Creates a variety of badges use [p]listbadges to see what is available"""
        if badge.lower() == "list":
            await self.list_badges(ctx)
            return
        is_badge = False
        for template in self.blank_template:
            if badge.lower() in template.lower():
                badge = template
                is_badge = True
        if not is_badge:
            await self.bot.send_message(ctx.message.channel, "{} is not an available badge!".format(badge))
            return
        user = ctx.message.author
        avatar = user.avatar_url if user.avatar_url != "" else user.default_avatar_url
        ext = "png"
        if "gif" in avatar:
            ext = "gif"
        await self.bot.send_typing(ctx.message.channel)
        await self.create_badge(user, badge)
        await self.bot.send_file(ctx.message.channel, "data/badges/temp/tempbadge." + ext) 
Example #5
Source File: message_quote.py    From SML-Cogs with MIT License 6 votes vote down vote up
def message_quote(self, ctx, *, args):
        """Quote message(s) by ID

        !mq 582794656560054272
        !mq 582794656560054272 #family-chat
        !mq 582794656560054272 582794656560054273 #family-chat
        If channel is omitted, use current channel
        """
        args = args.split(" ")
        last_arg = args[-1]
        from discord.ext.commands.converter import ChannelConverter
        from discord.ext.commands.errors import BadArgument
        try:
            channel = ChannelConverter(ctx, last_arg).convert()
        except BadArgument:
            channel = None
        else:
            args = args[:-1]
        if channel is None:
            channel = ctx.message.channel

        message_ids = args

        await self._show_message(ctx, channel, message_ids) 
Example #6
Source File: steam.py    From discord_bot with MIT License 5 votes vote down vote up
def steam_error(self, error, ctx):
        if isinstance(error, commands.errors.CommandOnCooldown):
            seconds = str(error)[34:]
            await self.bot.say(f':alarm_clock: Cooldown! Versuche es in {seconds} erneut')
        if isinstance(error, discord.ext.commands.errors.CommandInvokeError):
            await self.bot.say(':x: Konnte keine Verbindung zum Steam API aufbauen') 
Example #7
Source File: repl.py    From Dumb-Cogs with MIT License 5 votes vote down vote up
def get_source(self, thing):
        """returns a source object of a thing

        thing may be a non-builtin module, class, method, function, traceback, frame, or code object,
        or a space separated discord.ext.commands call,
        or a period deliminated file/module path as used when importing
        """
        if isinstance(thing, str):
            if '.' in thing:  # import
                modules = thing.split('.')
                def get_last_attr(prev, attrs):
                    try:
                        return prev.callback
                    except AttributeError:
                        if not attrs:
                            return prev
                        return get_last_attr(getattr(prev, attrs.pop(0)),
                                                     attrs)
                thing = get_last_attr(__import__(modules.pop(0)), modules)
            else:  # space delimited command call
                names = thing.split()
                thing = self.bot.commands[names.pop(0)]
                for name in names:
                    thing = thing.commands[name]
                thing = thing.callback
        return Source(thing) 
Example #8
Source File: admin.py    From discord-roombot with GNU General Public License v3.0 5 votes vote down vote up
def cog_command_error(self, ctx, error):
        if type(error) == discord.ext.commands.errors.CheckFailure:
            settings = Settings.get_for(ctx.guild.id)
            await ctx.send(settings.get_text('not_admin')) 
Example #9
Source File: roomhost.py    From discord-roombot with GNU General Public License v3.0 5 votes vote down vote up
def cog_command_error(self, ctx, error):
        s = Settings.get_for(ctx.guild.id)
        if type(error) == discord.ext.commands.errors.CheckFailure:
            await ctx.send(s.get_text('host_command_fail')) 
Example #10
Source File: bot.py    From pollmaster with MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        self.pipe = kwargs.pop('pipe')
        self.cluster_name = kwargs.pop('cluster_name')
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        super().__init__(**kwargs, loop=loop)
        self.websocket = None
        self._last_result = None
        self.ws_task = None
        self.responses = asyncio.Queue()
        self.eval_wait = False
        log = logging.getLogger(f"Cluster#{self.cluster_name}")
        log.setLevel(logging.DEBUG)
        log.handlers = [logging.FileHandler(f'cluster-{self.cluster_name}.log', encoding='utf-8', mode='a')]

        log.info(f'[Cluster#{self.cluster_name}] {kwargs["shard_ids"]}, {kwargs["shard_count"]}')
        self.log = log

        self.owner = None
        self.db = None
        self.session = None
        self.emoji_dict = None
        self.pre = None

        self.remove_command('help')
        self.load_extension("cogs.eval")
        extensions = ['cogs.config', 'cogs.poll_controls', 'cogs.help', 'cogs.db_api', 'cogs.admin']
        for ext in extensions:
            self.load_extension(ext)

        self.message_cache = MessageCache(self)
        self.refresh_blocked = {}
        self.refresh_queue = {}

        self.loop.create_task(self.ensure_ipc())
        self.run(kwargs['token']) 
Example #11
Source File: funcs.py    From NotSoBot with MIT License 5 votes vote down vote up
def random(self, image=False, ext:str=False):
		h = str(uuid.uuid4().hex)
		if image:
			return '{0}.{1}'.format(h, ext) if ext else h+'.png'
		return h 
Example #12
Source File: __init__.py    From EmoteCollector with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_context(self, message, cls=None):
		return await super().get_context(message, cls=cls or utils.context.CustomContext)

	# https://github.com/Rapptz/discord.py/blob/814b03f5a8a6faa33d80495691f1e1cbdce40ce2/discord/ext/commands/core.py#L1338-L1346 
Example #13
Source File: random.py    From rubbergod with GNU General Public License v3.0 5 votes vote down vote up
def roll(self, ctx):
        # TODO: use
        # https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#basic-converters
        # and only pass integers to the function?
        await ctx.send(rng.generate_number(ctx.message))
        await self.check.botroom_check(ctx.message) 
Example #14
Source File: manage_cog.py    From wall_e with GNU General Public License v3.0 5 votes vote down vote up
def on_command_error(self, ctx, error):
        if self.check_test_environment(ctx):
            if isinstance(error, commands.MissingRequiredArgument):
                logger.error('[ManageCog on_command_error()] Missing argument: {0}'.format(error.param))
                e_obj = await imported_embed(
                    ctx,
                    author=self.config.get_config_value('bot_profile', 'BOT_NAME'),
                    avatar=self.config.get_config_value('bot_profile', 'BOT_AVATAR'),
                    description="Missing argument: {}".format(error.param)
                )
                if e_obj is not False:
                    await ctx.send(embed=e_obj)
            else:
                # only prints out an error to the log if the string that was entered doesnt contain just "."
                pattern = r'[^\.]'
                if re.search(pattern, str(error)[9:-14]):
                    # author = ctx.author.nick or ctx.author.name
                    # await ctx.send('Error:\n```Sorry '+author+', seems like the command
                    # \"'+str(error)[9:-14]+'\"" doesn\'t exist :(```')
                    if type(error) is discord.ext.commands.errors.CheckFailure:
                        logger.warning(
                            "[ManageCog on_command_error()] user {} "
                            "probably tried to access a command they arent supposed to".format(ctx.author)
                        )
                    else:
                        traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
                        return

    # this command is used by the TEST guild to create the channel from which this TEST container will process
    # commands 
Example #15
Source File: badges.py    From Trusty-cogs-archive with MIT License 5 votes vote down vote up
def dl_image(self, url, ext="png"):
        async with self.session.get(url) as resp:
            test = await resp.read()
            with open(self.files + "temp/temp." + ext, "wb") as f:
                f.write(test) 
Example #16
Source File: qposts.py    From Trusty-cogs-archive with MIT License 5 votes vote down vote up
def fixq(self, ctx):
        async for message in self.bot.logs_from(ctx.message.channel, limit=1000):
            if message.embeds != []:
                embed = message.embeds[0]
                author = embed["author"]["name"]
                board = embed["footer"]["text"]
                url = embed["author"]["url"].replace("/thestorm/", board)
                embed["author"]["url"] = url
                text = embed["description"]
                # timestamp = embed["timestamp"] "2018-01-13T22:39:31+00:00"
                # print(board)
                post_id = int(url.split("#")[-1])
                timestamp = [post["time"] for post in self.qposts[board.replace("/", "")] if post["no"] == post_id][0]
                qpost = [post for post in self.qposts[board.replace("/", "")] if post["no"] == post_id][0]
                # print(timestamp)
                timestamp = datetime.utcfromtimestamp(timestamp)
                # print(timestamp)
                em = discord.Embed(colour=discord.Colour.red(),
                                   description="{}".format(text),
                                   timestamp=timestamp)
                em.set_author(name=author, url=url)
                em.set_footer(text="{}".format(board))
                if "tim" in qpost:
                    file_id = qpost["tim"]
                    file_ext = qpost["ext"]
                    img_url = "https://media.8ch.net/file_store/{}{}".format(file_id, file_ext)
                    if file_ext in [".png", ".jpg"]:
                        em.set_image(url=img_url)
                await self.bot.edit_message(message, embed=em)
        # print(embed["author"]) 
Example #17
Source File: admin.py    From MangoByte with MIT License 5 votes vote down vote up
def disablecommand(self, ctx, command: str):
		"""Disabled the specified command or command category

		**Examples:**
		`{cmdpfx}disablecommand wiki`
		`{cmdpfx}disablecommand Audio`"""
		guildinfo = botdata.guildinfo(ctx)
		if not guildinfo:
			raise UserError("This command must be called in a guild")

		cmd = self.get_command_or_cog(ctx, command)
		if cmd is None:
			raise UserError("Couldn't find a command or command category by that name")

		secure_cogs = [ "Admin", "Owner" ]
		if isinstance(cmd, discord.ext.commands.Command):
			if guildinfo.is_disabled(cmd.cog_name):
				raise UserError(f"The category this command belongs to ({cmd.cog_name}) is already disabled")
			if cmd.cog_name in secure_cogs:
				raise UserError("You can't disable a command in this category")
		else:
			if cmd.name in secure_cogs:
				raise UserError("You can't disable this category")

		if guildinfo.is_disabled(cmd.name):
			raise UserError("This has already been disabled")
		guildinfo.disable_command(cmd.name)
		await ctx.message.add_reaction("✅") 
Example #18
Source File: general.py    From MangoByte with MIT License 5 votes vote down vote up
def load_words():
	words = {}
	for root, dirs, files in os.walk(settings.resource("words/")):
		for file in files:
			with open(os.path.join(root, file), 'r') as f:
				text = f.read()
			key, ext = os.path.splitext(file)
			words[key] = text.split("\n")
	return words


# fills a template with the words of the type asked for 
Example #19
Source File: audio.py    From MangoByte with MIT License 5 votes vote down vote up
def audioplayer(self, ctx, error_on_none=True):
		# TODO: ACCOUNT FOR WHEN THIS MESSAGE IS A PM
		if isinstance(ctx, discord.ext.commands.Context):
			if ctx.message.guild is None: # This is a private channel, so give it user
				ctx = ctx.message.author
			else:
				ctx = ctx.message.guild

		if isinstance(ctx, discord.User):
			author = ctx
			for audioplayer in self.audioplayers:
				member = audioplayer.guild.get_member(author.id)
				if member and member.voice and audioplayer.voice and audioplayer.voice.channel.id == member.voice.channel.id:
					if botdata.guildinfo(audioplayer.guild).is_banned(member):
						raise AudioPlayerNotFoundError("Nice try, but you're banned in the voice channel that I'm in")
					return audioplayer
			if error_on_none:
				raise AudioPlayerNotFoundError("You're not in any voice channels that I'm in")
			else:
				return None
		elif isinstance(ctx, discord.Guild):
			guild = ctx
		elif isinstance(ctx, discord.abc.GuildChannel):
			guild = ctx.guild
		else:
			raise ValueError(f"Incorrect type '{type(ctx)}' given to audioplayer function")

		for audioplayer in self.audioplayers:
			if audioplayer.guild == guild:
				return audioplayer

		if error_on_none:
			raise AudioPlayerNotFoundError(f"I'm not in a voice channel on this server/guild. Have an admin do `{botdata.command_prefix(ctx)}summon` to put me in one.")
		else:
			return None

	# Connects an audioplayer for the correct guild to the indicated channel 
Example #20
Source File: bot.py    From xenon with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(
            command_prefix=self._prefix_callable,
            shard_count=self.config.shard_count,
            fetch_offline_members=False,
            guild_subscriptions=False,
            shard_ids=[],
            owner_id=self.config.owner_id,
            max_messages=10**4,
            disabled_events=[
                "VOICE_STATE_UPDATE",
                "PRESENCE_UPDATE",
                "TYPING_START",
                "GUILD_EMOJIS_UPDATE"
            ],
            *args, **kwargs
        )

        self.session = ClientSession(loop=self.loop)
        db_connection = AsyncIOMotorClient(
            host=self.config.db_host,
            username=self.config.db_user,
            password=self.config.db_password
        )
        self.db = getattr(db_connection, self.config.identifier)
        for ext in self.config.extensions:
            self.load_extension("cogs." + ext)

        log.info(f"Loaded {len(self.cogs)} cogs")