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


Python discord.TextChannel方法代码示例

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


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

示例1: maybe_delete_messages

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def maybe_delete_messages(self, channel: TextChannel, messages: List[Message]) -> None:
        """Cleans the messages if cleaning is configured."""
        if AntiSpamConfig.clean_offending:
            # If we have more than one message, we can use bulk delete.
            if len(messages) > 1:
                message_ids = [message.id for message in messages]
                self.mod_log.ignore(Event.message_delete, *message_ids)
                await channel.delete_messages(messages)

            # Otherwise, the bulk delete endpoint will throw up.
            # Delete the message directly instead.
            else:
                self.mod_log.ignore(Event.message_delete, messages[0].id)
                try:
                    await messages[0].delete()
                except NotFound:
                    log.info(f"Tried to delete message `{messages[0].id}`, but message could not be found.") 
开发者ID:python-discord,项目名称:bot,代码行数:19,代码来源:antispam.py

示例2: __init__

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def __init__(self, bot: Bot):
        super().__init__()

        self.bot = bot

        # Categories
        self.available_category: discord.CategoryChannel = None
        self.in_use_category: discord.CategoryChannel = None
        self.dormant_category: discord.CategoryChannel = None

        # Queues
        self.channel_queue: asyncio.Queue[discord.TextChannel] = None
        self.name_queue: t.Deque[str] = None

        self.name_positions = self.get_names()
        self.last_notification: t.Optional[datetime] = None

        # Asyncio stuff
        self.queue_tasks: t.List[asyncio.Task] = []
        self.ready = asyncio.Event()
        self.on_message_lock = asyncio.Lock()
        self.init_task = self.bot.loop.create_task(self.init_cog()) 
开发者ID:python-discord,项目名称:bot,代码行数:24,代码来源:help_channels.py

示例3: create_dormant

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def create_dormant(self) -> t.Optional[discord.TextChannel]:
        """
        Create and return a new channel in the Dormant category.

        The new channel will sync its permission overwrites with the category.

        Return None if no more channel names are available.
        """
        log.trace("Getting a name for a new dormant channel.")

        try:
            name = self.name_queue.popleft()
        except IndexError:
            log.debug("No more names available for new dormant channels.")
            return None

        log.debug(f"Creating a new dormant channel named {name}.")
        return await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:help_channels.py

示例4: get_idle_time

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def get_idle_time(cls, channel: discord.TextChannel) -> t.Optional[int]:
        """
        Return the time elapsed, in seconds, since the last message sent in the `channel`.

        Return None if the channel has no messages.
        """
        log.trace(f"Getting the idle time for #{channel} ({channel.id}).")

        msg = await cls.get_last_message(channel)
        if not msg:
            log.debug(f"No idle time available; #{channel} ({channel.id}) has no messages.")
            return None

        idle_time = (datetime.utcnow() - msg.created_at).seconds

        log.trace(f"#{channel} ({channel.id}) has been idle for {idle_time} seconds.")
        return idle_time 
开发者ID:python-discord,项目名称:bot,代码行数:19,代码来源:help_channels.py

示例5: ensure_valid_reminder

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def ensure_valid_reminder(
        self,
        reminder: dict,
        cancel_task: bool = True
    ) -> t.Tuple[bool, discord.User, discord.TextChannel]:
        """Ensure reminder author and channel can be fetched otherwise delete the reminder."""
        user = self.bot.get_user(reminder['author'])
        channel = self.bot.get_channel(reminder['channel_id'])
        is_valid = True
        if not user or not channel:
            is_valid = False
            log.info(
                f"Reminder {reminder['id']} invalid: "
                f"User {reminder['author']}={user}, Channel {reminder['channel_id']}={channel}."
            )
            asyncio.create_task(self._delete_reminder(reminder['id'], cancel_task))

        return is_valid, user, channel 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:reminders.py

示例6: _unsilence

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def _unsilence(self, channel: TextChannel) -> bool:
        """
        Unsilence `channel`.

        Check if `channel` is silenced through a `PermissionOverwrite`,
        if it is unsilence it and remove it from the notifier.
        Return `True` if channel permissions were changed, `False` otherwise.
        """
        current_overwrite = channel.overwrites_for(self._verified_role)
        if current_overwrite.send_messages is False:
            await channel.set_permissions(self._verified_role, **dict(current_overwrite, send_messages=None))
            log.info(f"Unsilenced channel #{channel} ({channel.id}).")
            self.cancel_task(channel.id)
            self.notifier.remove_channel(channel)
            self.muted_channels.discard(channel)
            return True
        log.info(f"Tried to unsilence channel #{channel} ({channel.id}) but the channel was not silenced.")
        return False 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:silence.py

示例7: is_nsfw

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def is_nsfw():
    """A :func:`.check` that checks if the channel is a NSFW channel.

    This check raises a special exception, :exc:`.NSFWChannelRequired`
    that is derived from :exc:`.CheckFailure`.

    .. versionchanged:: 1.1

        Raise :exc:`.NSFWChannelRequired` instead of generic :exc:`.CheckFailure`.
        DM channels will also now pass this check.
    """
    def pred(ctx):
        ch = ctx.channel
        if ctx.guild is None or (isinstance(ch, discord.TextChannel) and ch.is_nsfw()):
            return True
        raise NSFWChannelRequired(ch)
    return check(pred) 
开发者ID:Rapptz,项目名称:discord.py,代码行数:19,代码来源:core.py

示例8: _serv_info

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def _serv_info(self, guild_id):
        guild = self.bot.get_guild(guild_id)
        if not guild:
            channel = self.bot.get_channel(guild_id)
            if not channel:
                return False
            else:
                guild = channel.guild

        try:
            invite = (
                await next(c for c in guild.channels if isinstance(c, discord.TextChannel)).create_invite()).url
        except:
            invite = None

        if invite:
            out = f"{guild.name} ({guild.id}, <{invite}>)"
        else:
            out = f"{guild.name} ({guild.id})"
        out += f"\n{len(guild.members)} members, {sum(m.bot for m in guild.members)} bot"
        return out 
开发者ID:avrae,项目名称:avrae,代码行数:23,代码来源:adminUtils.py

示例9: on_guild_join

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def on_guild_join(self, guild: discord.Guild):
        _ = self.bot._

        for channel in guild.channels:
            if isinstance(channel, discord.TextChannel):
                if channel.permissions_for(guild.me).send_messages:
                    channel_used = channel
                    break

        else:
            return  # Nowhere to speak

        await self.bot.send_message(where=channel_used, message=_("Hello!\n "
                                                                  "Thanks for adding me in there! I'm almost ready to start the game!\n "
                                                                  "Could we please go into the channel where you want the game to be ? "
                                                                  "Please invoke me there by using `dh!setup`"
                                                                  "<:event_GuildAdded_01:439550913112309781>")) 
开发者ID:DuckHunt-discord,项目名称:DHV3,代码行数:19,代码来源:setup_wizzard.py

示例10: freply

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def freply(self, ctx, *, msg: str = ""):
        """
        Reply to a Modmail thread with variables.

        Works just like `{prefix}reply`, however with the addition of three variables:
          - `{{channel}}` - the `discord.TextChannel` object
          - `{{recipient}}` - the `discord.User` object of the recipient
          - `{{author}}` - the `discord.User` object of the author

        Supports attachments and images as well as
        automatically embedding image URLs.
        """
        msg = self.bot.formatter.format(
            msg, channel=ctx.channel, recipient=ctx.thread.recipient, author=ctx.message.author
        )
        ctx.message.content = msg
        async with ctx.typing():
            await ctx.thread.reply(ctx.message) 
开发者ID:kyb3r,项目名称:modmail,代码行数:20,代码来源:modmail.py

示例11: __init__

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def __init__(
        self,
        manager: "ThreadManager",
        recipient: typing.Union[discord.Member, discord.User, int],
        channel: typing.Union[discord.DMChannel, discord.TextChannel] = None,
    ):
        self.manager = manager
        self.bot = manager.bot
        if isinstance(recipient, int):
            self._id = recipient
            self._recipient = None
        else:
            if recipient.bot:
                raise CommandError("Recipient cannot be a bot.")
            self._id = recipient.id
            self._recipient = recipient
        self._channel = channel
        self.genesis_message = None
        self._ready_event = asyncio.Event()
        self.close_task = None
        self.auto_close_task = None 
开发者ID:kyb3r,项目名称:modmail,代码行数:23,代码来源:thread.py

示例12: on_message_without_command

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def on_message_without_command(self, msg):
		"""Passively records all message contents."""
		if not msg.author.bot and isinstance(msg.channel, discord.TextChannel):
			if msg.guild.id not in self.ignore_cache:
				cfg = await self.config.guild(msg.guild).all()
				self.ignore_cache[msg.guild.id] = cfg
			enableGuild = self.ignore_cache[msg.guild.id]['enableGuild']
			disabledChannels = self.ignore_cache[msg.guild.id]['disabledChannels']
			if enableGuild and not msg.channel.id in disabledChannels:
				#Strip any characters besides letters and spaces.
				words = re.sub(r'[^a-z \n]', '', msg.content.lower()).split()
				query = (
					'INSERT INTO member_words (guild_id, user_id, word)'
					'VALUES (?, ?, ?)'
					'ON CONFLICT(guild_id, user_id, word) DO UPDATE SET quantity = quantity + 1;'
				)
				data = ((msg.guild.id, msg.author.id, word) for word in words)
				task = functools.partial(self.safe_write, query, data)
				await self.bot.loop.run_in_executor(self._executor, task) 
开发者ID:Flame442,项目名称:FlameCogs,代码行数:21,代码来源:wordstats.py

示例13: giftat

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def giftat(self, ctx, channel: discord.TextChannel, game_name, *keys):
		"""
		Giftaway a key to a specific channel.
		
		You probably should run this command from a location people can't see to protect the keys.
		Wrap any parameters that require spaces in quotes.
		"""
		try:
			await ctx.message.delete()
		except:
			pass
		if not ctx.guild.me.permissions_in(channel).embed_links:
			return await ctx.send(_('I do not have permission to send embeds in the giftaway channel.'))
		try:
			gift = await Gift.create(self, ctx, [channel], game_name, list(keys))
		except GiftError as e:
			return await ctx.send(e)
		self.gifts.append(gift)
		key, value = gift.to_dict()
		async with self.config.gifts() as gifts:
			gifts[key] = value
		await ctx.tick() 
开发者ID:Flame442,项目名称:FlameCogs,代码行数:24,代码来源:giftaway.py

示例14: mute

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def mute(self, ctx, user: discord.Member, time: int=15):
        '''Mute a member in the guild'''
        secs = time * 60
        for channel in ctx.guild.channels:
            if isinstance(channel, discord.TextChannel):
                await ctx.channel.set_permissions(user, send_messages=False)
            elif isinstance(channel, discord.VoiceChannel):
                await channel.set_permissions(user, connect=False)
        await ctx.send(f"{user.mention} has been muted for {time} minutes.")
        await asyncio.sleep(secs)
        for channel in ctx.guild.channels:
            if isinstance(channel, discord.TextChannel):
                await ctx.channel.set_permissions(user, send_messages=None)
            elif isinstance(channel, discord.VoiceChannel):
                await channel.set_permissions(user, connect=None)
        await ctx.send(f'{user.mention} has been unmuted from the guild.') 
开发者ID:cree-py,项目名称:RemixBot,代码行数:18,代码来源:mod.py

示例15: karma_transfer

# 需要导入模块: import discord [as 别名]
# 或者: from discord import TextChannel [as 别名]
def karma_transfer(self, message: TextChannel):
        input_string = message.content.split()
        if len(input_string) < 4 or len(message.mentions) < 2:
            await message.channel.send(msg.karma_transfer_format)
            return

        try:
            from_user: Member = message.mentions[0]
            to_user: Member = message.mentions[1]

            transfered = self.repo.transfer_karma(from_user, to_user)
            formated_message = utils.fill_message("karma_transfer_complete", from_user=from_user.name,
                                                  to_user=to_user.name, karma=transfered.karma,
                                                  positive=transfered.positive, negative=transfered.negative)

            await self.reply_to_channel(message.channel, formated_message)
        except ValueError:
            await self.reply_to_channel(message.channel, msg.karma_transfer_format)
            return 
开发者ID:Toaster192,项目名称:rubbergod,代码行数:21,代码来源:karma.py


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