当前位置: 首页>>代码示例>>Python>>正文


Python discord.ext方法代码示例

本文整理汇总了Python中discord.ext方法的典型用法代码示例。如果您正苦于以下问题:Python discord.ext方法的具体用法?Python discord.ext怎么用?Python discord.ext使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord的用法示例。


在下文中一共展示了discord.ext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: rtfs

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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)) 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:25,代码来源:repl.py

示例2: save_q_files

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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) 
开发者ID:TrustyJAID,项目名称:Trusty-cogs-archive,代码行数:19,代码来源:qposts.py

示例3: badges

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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) 
开发者ID:TrustyJAID,项目名称:Trusty-cogs-archive,代码行数:23,代码来源:badges.py

示例4: message_quote

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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) 
开发者ID:smlbiobot,项目名称:SML-Cogs,代码行数:26,代码来源:message_quote.py

示例5: __init__

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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}') 
开发者ID:python-discord,项目名称:code-jam-5,代码行数:24,代码来源:__init__.py

示例6: get_source

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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) 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:28,代码来源:repl.py

示例7: __init__

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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") 
开发者ID:Xenon-Bot,项目名称:xenon,代码行数:31,代码来源:bot.py

示例8: audioplayer

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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 
开发者ID:mdiller,项目名称:MangoByte,代码行数:39,代码来源:audio.py

示例9: load_words

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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 
开发者ID:mdiller,项目名称:MangoByte,代码行数:14,代码来源:general.py

示例10: disablecommand

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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("✅") 
开发者ID:mdiller,项目名称:MangoByte,代码行数:30,代码来源:admin.py

示例11: fixq

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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"]) 
开发者ID:TrustyJAID,项目名称:Trusty-cogs-archive,代码行数:32,代码来源:qposts.py

示例12: dl_image

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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) 
开发者ID:TrustyJAID,项目名称:Trusty-cogs-archive,代码行数:7,代码来源:badges.py

示例13: on_command_error

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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 
开发者ID:CSSS,项目名称:wall_e,代码行数:32,代码来源:manage_cog.py

示例14: roll

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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) 
开发者ID:Toaster192,项目名称:rubbergod,代码行数:8,代码来源:random.py

示例15: get_context

# 需要导入模块: import discord [as 别名]
# 或者: from discord import ext [as 别名]
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 
开发者ID:EmoteBot,项目名称:EmoteCollector,代码行数:6,代码来源:__init__.py


注:本文中的discord.ext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。