Python discord.TextChannel() Examples
The following are 30
code examples of discord.TextChannel().
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
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: mod.py From RemixBot with MIT License | 8 votes |
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.')
Example #2
Source File: help_channels.py From bot with MIT License | 7 votes |
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())
Example #3
Source File: adminUtils.py From avrae with GNU General Public License v3.0 | 6 votes |
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
Example #4
Source File: giftaway.py From FlameCogs with MIT License | 6 votes |
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()
Example #5
Source File: karma.py From rubbergod with GNU General Public License v3.0 | 6 votes |
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
Example #6
Source File: wordstats.py From FlameCogs with MIT License | 6 votes |
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)
Example #7
Source File: reminders.py From bot with MIT License | 6 votes |
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
Example #8
Source File: modmail.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
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)
Example #9
Source File: collectchain.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
def is_blinded(db: Database, channel: discord.TextChannel, author: discord.Member): """ :param db: :type db: :param channel: :type channel: :param author: :type author: :return: :rtype: """ if author.permissions_in(channel).manage_channels: blinded = False else: blinded = bool(await db[db.db_nam].BlindedChains.find_one({'channel_id': channel.id})) return blinded
Example #10
Source File: thread.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
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
Example #11
Source File: quote.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
def message_search(lookup: int, message: discord.Message): """ :param lookup: :type lookup: :param message: :type message: :return: :rtype: """ try: msg = await message.channel.fetch_message(lookup) except discord.NotFound: msg = None if not msg: for channel in message.guild.channels: if isinstance(channel, discord.TextChannel): try: msg = await channel.fetch_message(lookup) break except (discord.Forbidden, discord.NotFound): msg = None return msg
Example #12
Source File: permissions.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
def check_nsfw(self): """ Checks if the command is NSFW and if the place it's called is marked as NSFW. :return: :rtype: """ if isinstance(self.message.channel, discord.TextChannel): if self.cmd.nsfw: if self.message.channel.is_nsfw(): self.nsfw_denied = False else: self.nsfw_denied = True else: self.nsfw_denied = False else: self.nsfw_denied = False
Example #13
Source File: setup_wizzard.py From DHV3 with GNU Affero General Public License v3.0 | 6 votes |
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>"))
Example #14
Source File: help_channels.py From bot with MIT License | 6 votes |
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
Example #15
Source File: silence.py From bot with MIT License | 6 votes |
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
Example #16
Source File: core.py From discord.py with MIT License | 6 votes |
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)
Example #17
Source File: help_channels.py From bot with MIT License | 6 votes |
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)
Example #18
Source File: locale.py From EmoteCollector with GNU Affero General Public License v3.0 | 6 votes |
def set_locale_command(self, context, channel: typing.Optional[discord.TextChannel], locale: Locale): """Set the locale for a channel or yourself. Manage Messages is required to change the locale of a whole channel. If the channel is left blank, this command sets your user locale. """ if channel is None: await self.set_user_locale(context.author.id, locale) elif ( not context.author.guild_permissions.manage_messages or not await self.bot.is_owner(context.author) ): raise commands.MissingPermissions(('manage_messages',)) else: await self.set_channel_locale(context.guild.id, channel.id, locale) await context.try_add_reaction(utils.SUCCESS_EMOJIS[True])
Example #19
Source File: antispam.py From bot with MIT License | 6 votes |
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.")
Example #20
Source File: incident.py From apex-sigma-core with GNU General Public License v3.0 | 5 votes |
def from_obj(self, obj): """ Parses the location data from an object. :param obj: The object from which to get the data from. :type obj: discord.TextChannel or discord.Guild :return: :rtype: """ self.id = obj.id self.name = obj.name if isinstance(obj, discord.TextChannel): self.variant = 'channel' else: self.variant = 'guild'
Example #21
Source File: fetch.py From apex-sigma-core with GNU General Public License v3.0 | 5 votes |
def fetch_channel(self, cid): """ Fetches and caches a user. :param cid: The channel ID. :type cid: int :return: :rtype: None or discord.TextChannel """ result = None data = await self.get_object_doc('channel', cid) if data: gdat = await self.get_object_doc('guild', data['guild_id']) if gdat: result = discord.TextChannel(state=self.state, guild=gdat, data=data) return result
Example #22
Source File: mod.py From RemixBot with MIT License | 5 votes |
def unmute(self, ctx, user: discord.Member): '''Unmute a member in the guild''' 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.')
Example #23
Source File: bot.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def on_guild_channel_delete(self, channel): if channel.guild != self.modmail_guild: return try: audit_logs = self.modmail_guild.audit_logs() entry = await audit_logs.find(lambda a: a.target == channel) mod = entry.user except AttributeError as e: # discord.py broken implementation with discord API # TODO: waiting for dpy logger.warning("Failed to retrieve audit log: %s.", e) return if mod == self.user: return if isinstance(channel, discord.CategoryChannel): if self.main_category == channel: logger.debug("Main category was deleted.") self.config.remove("main_category_id") await self.config.update() return if not isinstance(channel, discord.TextChannel): return if self.log_channel is None or self.log_channel == channel: logger.info("Log channel deleted.") self.config.remove("log_channel_id") await self.config.update() return thread = await self.threads.find(channel=channel) if thread and thread.channel == channel: logger.debug("Manually closed channel %s.", channel.name) await thread.close(closer=mod, silent=True, delete_channel=False)
Example #24
Source File: bot.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def is_blocked( self, author: discord.User, *, channel: discord.TextChannel = None, send_message: bool = False, ) -> typing.Tuple[bool, str]: member = self.guild.get_member(author.id) if member is None: logger.debug("User not in guild, %s.", author.id) else: author = member if str(author.id) in self.blocked_whitelisted_users: if str(author.id) in self.blocked_users: self.blocked_users.pop(str(author.id)) await self.config.update() return False blocked_reason = self.blocked_users.get(str(author.id)) or "" if not self.check_account_age(author) or not self.check_guild_age(author): new_reason = self.blocked_users.get(str(author.id)) if new_reason != blocked_reason: if send_message: await channel.send( embed=discord.Embed( title="Message not sent!", description=new_reason, color=self.error_color, ) ) return True if not self.check_manual_blocked(author): return True await self.config.update() return False
Example #25
Source File: bot.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def log_channel(self) -> typing.Optional[discord.TextChannel]: channel_id = self.config["log_channel_id"] if channel_id is not None: try: channel = self.get_channel(int(channel_id)) if channel is not None: return channel except ValueError: pass logger.debug("LOG_CHANNEL_ID was invalid, removed.") self.config.remove("log_channel_id") if self.main_category is not None: try: channel = self.main_category.channels[0] self.config["log_channel_id"] = channel.id logger.warning( "No log channel set, setting #%s to be the log channel.", channel.name ) return channel except IndexError: pass logger.warning( "No log channel set, set one with `%ssetup` or `%sconfig set log_channel_id <id>`.", self.prefix, self.prefix, ) return None
Example #26
Source File: bot.py From DHV3 with GNU Affero General Public License v3.0 | 5 votes |
def log(self, title: str, message: str, where: Union[CustomContext, discord.TextChannel, discord.Guild, None], level: int): if isinstance(where, CustomContext): footer = f"On {where.channel.id} (#{where.channel.name}), by {where.author.id} ({where.author.name}#{where.author.discriminator})" elif isinstance(where, discord.TextChannel): footer = f"On {where.id} (#{where.name})" elif isinstance(where, discord.Guild): footer = f"On {where.id} (#{where.name})" elif where is None: footer = "" else: footer = "" logger.warning("Unknown where on logging to a channel : " + str(where)) embed = discord.Embed(description=message) embed.title = title embed.set_footer(text=footer) if 0 <= level <= 5: embed.colour = discord.Colour.green() elif 6 <= level <= 10: embed.colour = discord.Colour.greyple() elif 11 <= level <= 20: embed.colour = discord.Colour.orange() elif 21 <= level <= 30: embed.colour = discord.Colour.red() else: embed.colour = discord.Colour.dark_red() await self.send_message(where=self.get_channel(self.log_channel_id), embed=embed, mention=False, can_pm=False)
Example #27
Source File: miscellaneous.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def botpermissions(self, ctx, *, channel: discord.TextChannel = None): channel = channel or ctx.channel member = ctx.guild.me await self.say_permissions(ctx, member, channel)
Example #28
Source File: miscellaneous.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def permissions(self, ctx, member: discord.Member = None, channel: discord.TextChannel = None): channel = channel or ctx.channel if member is None: member = ctx.author await self.say_permissions(ctx, member, channel)
Example #29
Source File: owner.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def invoke(self, ctx, channel: Optional[discord.TextChannel], user: discord.User, *, command: str): msg = copy.copy(ctx.message) channel = channel or ctx.channel msg.channel = channel msg.author = channel.guild.get_member(user.id) or user msg.content = ctx.prefix + command new_ctx = await self.bot.get_context(msg, cls=type(ctx)) await self.bot.invoke(new_ctx)
Example #30
Source File: templates.py From xenon with GNU General Public License v3.0 | 5 votes |
def on_message(self, msg): if not isinstance(msg.channel, discord.TextChannel): return if len(msg.embeds) == 0 or not msg.embeds[0].title: return if msg.channel.id == self.bot.config.template_approval and msg.author.bot: for emoji in self.approval_options.keys(): await msg.add_reaction(emoji)