def notify_error(self, channel: discord.TextChannel, text: str):
embed = discord.Embed(title='\N{WARNING SIGN} Feed error', description=text, color=0xff4747)
try:
await channel.send(embed=embed)
except discord.Forbidden:
# wow
pass
python类TextChannel()的实例源码
def on_raw_bulk_message_delete(self, message_ids, channel_id: int):
# add to list of bulk deletes so we don't process message delete events for these messages
self.bulk_deletes.add(message_ids=message_ids)
# resolve the channel that the message was deleted in
channel = self.bot.get_channel(channel_id)
# don't handle non-existent channels or dms
if not channel or not isinstance(channel, discord.TextChannel):
return
# log
await self.log(channel.guild, f'\U0001f6ae {len(message_ids)} message(s) deleted in {channel.mention}')
def on_message_delete(self, msg: discord.Message):
# don't handle message deletion elsewhere
if not isinstance(msg.channel, discord.TextChannel):
return
# do not process bulk message deletes, or message censors (the censor cog does that already)
# TODO: do this but cleanly, maybe paste website?
if await self.bulk_deletes.check_batch(msg.id) or await self.censored_messages.check(message_id=msg.id):
return
# if this channel isn't publicly visible or deletes shouldn't be tracked, bail
if (not await is_publicly_visible(self.bot, msg.channel) or
await self.bot.config_is_set(msg.guild, 'modlog_notrack_deletes')):
return
# if the author was a bot and we aren't configured to allow bots, return
if msg.author.bot and not await self.bot.config_is_set(msg.guild, 'modlog_filter_allow_bot'):
return
# format attachment list
attachments = 'no attachments' if not msg.attachments else f'{len(msg.attachments)} attachment(s): ' + \
', '.join(f'{a.filename}, {filesize(a.size)}' for a in msg.attachments)
content = utils.prevent_codeblock_breakout(utils.truncate(msg.content, 1500))
fmt = (f'\U0001f6ae Message by {describe(msg.author)} deleted in {msg.channel.mention}: ```\n{content}\n``` '
f'({attachments}, {len(msg.embeds)} embed(s)')
await self.log(msg.guild, fmt)
def is_public(self, ctx, channel: discord.TextChannel=None):
"""
Checks if a channel is public.
This command is in the Modlog cog because the modlog does not process message edit and
delete events for private channels.
If you have turned 'log_all_message_events' on, this will always say public.
"""
channel = channel if channel else ctx.channel
public = f'{channel.mention} {{}} public to @\u200beveryone.'
await ctx.send(public.format('is' if await is_publicly_visible(self.bot, channel) else '**is not**'))
def guildinfo(self, ctx):
"""Get loads of info about this guild.
Usage: guildinfo"""
s = ctx.guild
ach = s.channels
chlist = [len(ach), 0, 0]
for i in ach:
if isinstance(i, discord.TextChannel):
chlist[1] += 1
else:
chlist[2] += 1
iurl = s.icon_url
s_reg = str(s.region)
r_embed = discord.Embed(color=random.randint(0, 255**3-1))
if iurl:
thing = {'url': iurl}
else:
thing = {}
r_embed.set_author(name=s.name, **thing, icon_url=(iurl if iurl else ctx.me.avatar_url))
r_embed.set_footer(text=ctx.me.display_name, icon_url=ctx.me.avatar_url)
if iurl:
r_embed.set_image(url=iurl)
r_embed.add_field(name='ID', value=s.id)
r_embed.add_field(name='Members', value=len(s.members))
r_embed.add_field(name='Channels', value=ch_fmt.format(*[str(i) for i in chlist]))
r_embed.add_field(name='Roles', value=len(s.roles))
r_embed.add_field(name='Custom Emojis', value=len(s.emojis))
r_embed.add_field(name='Region (Location)', value=str(s.region).replace('-', ' ').title().replace('Eu ', 'EU ').replace('Us ', 'US ').replace('Vip', 'VIP '))
r_embed.add_field(name='Owner', value=str(s.owner))
r_embed.add_field(name='Default Channel', value=f'<#{s.default_channel.id}>\n(#{s.default_channel.name})' if s.default_channel is not None else 'None (deleted)')
r_embed.add_field(name='Admins Need 2FA', value=('Yes' if s.mfa_level else 'No'))
r_embed.add_field(name='Verification Level', value=v_level_map[str(s.verification_level)])
await ctx.send(embed=r_embed)
def info(self, ctx):
"""Get bot info.
Usage: info"""
ach = self.bot.get_all_channels()
chlist = [0, 0, 0]
for i in ach:
chlist[0] += 1
if isinstance(i, discord.TextChannel):
chlist[1] += 1
else:
chlist[2] += 1
up = self.bot.format_uptime()
ram = self.bot.get_ram()
got_conversion = ram[0]
emb = discord.Embed(color=random.randint(0, 255**3-1))
emb.set_author(name=ctx.me.display_name, url='https://khronodragon.com/', icon_url=ctx.me.avatar_url)
emb.set_footer(text='Made in Python 3.6+ with Discord.py %s' % self.bot.lib_version, icon_url='https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/400px-Python-logo-notext.svg.png')
emb.add_field(name='Guilds', value=len(self.bot.guilds))
emb.add_field(name='Author', value='Dragon5232#1841')
emb.add_field(name='Uptime', value=up)
emb.add_field(name='Local Time', value=time.strftime(absfmt, time.localtime()))
emb.add_field(name='Cogs Loaded', value=len(self.bot.cogs))
emb.add_field(name='Command Calls', value=sum(self.bot.command_calls.values()))
emb.add_field(name='Memory Used', value=(str(round(ram[1], 1)) + ' MB (%s MiB)' % str(round(ram[2], 1))) if got_conversion else 'Couldn\'t fetch')
emb.add_field(name='Members Seen', value=sum(g.member_count for g in self.bot.guilds))
emb.add_field(name='Channels', value=ch_fmt.format(*[str(i) for i in chlist]))
emb.add_field(name='Custom Emojis', value=len(self.bot.emojis))
emb.add_field(name='Commands', value=str(len(self.bot.all_commands)))
emb.add_field(name='ID', value=ctx.me.id)
if self.bot.user.id == 239775420470394897:
emb.add_field(name='Invite Link', value='https://tiny.cc/goldbot')
await ctx.send(home_broadcast, embed=emb)
def nitro_sendto(self, ctx, *, channel: discord.TextChannel):
"""Send a fake Nitro message embed to a channel.
Usage: nitro_sendto [channel]"""
emb = self.get_nitro_embed()
with channel.typing():
await asyncio.sleep(random.uniform(0.25, 1.2), loop=self.loop)
await channel.send(embed=emb)
def __init__(self, subscriber):
if not isinstance(subscriber, (discord.User, discord.Member, discord.TextChannel)):
raise ValueError("Passed subscriber isn't an User nor a TextChannel")
self.subscriber = subscriber
self.id = self.subscriber.id
def _add_command(self, ctx, username: str = None, channel: discord.TextChannel = None):
"""add command"""
username = await self.validate_username(username)
channel = await validate_notification_channel(ctx, channel)
async with ctx.typing():
subscriber = Subscriber(channel or ctx.author)
await self._subscribe_to_streamer(subscriber, username)
await ctx.send(f'{subscriber} subscribed to {username} successfully!')
def _del_command(self, ctx, username: str = None, channel: discord.TextChannel = None):
"""del command"""
username = await self.validate_username(username)
channel = await validate_notification_channel(ctx, channel)
async with ctx.typing():
subscriber = Subscriber(channel or ctx.author)
await self._del_subscription(subscriber, username)
await ctx.send(f'{subscriber} unsubscribed to {username} successfully!')
def _list_command(self, ctx, channel: discord.TextChannel = None):
"""list command"""
channel = await validate_notification_channel(ctx, channel)
subscriber = Subscriber(channel or ctx.author)
async with ctx.typing():
streamers = await self.bot.database.get_subscriptions_from_subscriber(subscriber.id, self.service_name)
embed = self._make_list_embed(streamers, subscriber)
await ctx.send(embed=embed)
def _enable_command(self, ctx, channel: discord.TextChannel = None):
channel = await validate_notification_channel(ctx, channel)
subscriber = Subscriber(channel or ctx.author)
self.disabled_users.discard(subscriber.id)
await ctx.send(f'{subscriber.subscriber} has notifications enabled.')
def on_guild_channel_delete(self, channel: discord.TextChannel):
log.info('Guild channel deleted')
await self._remove_channels_from_database([channel])
def __init__(self, ctx):
permissions_in = ctx.author.permissions_in
_channel_parsers = {
discord.TextChannel: functools.partial(_parse_channel, prefix='#', predicate=lambda c: permissions_in(c).read_messages),
discord.VoiceChannel: functools.partial(_parse_channel, prefix='', predicate=lambda c: permissions_in(c).connect),
}
entries = [
(category, [_channel_parsers[c.__class__](c) for c in entries])
for category, channels in ctx.guild.by_category()
for entries in sliced(channels, 10)
]
super().__init__(ctx, entries, lines_per_page=1)
def info_channel(self, ctx, channel: union(discord.TextChannel, discord.VoiceChannel)=None):
"""Shows info about a voice or text channel."""
if channel is None:
channel = ctx.channel
embed_type = 'text_channel_embed' if isinstance(channel, discord.TextChannel) else 'voice_channel_embed'
channel_embed = getattr(self, embed_type)(channel)
channel_embed.colour = self.bot.colour
await ctx.send(embed=channel_embed)
def stats(self, ctx):
"""Shows some general statistics about the bot.
Do not confuse this with `{prefix}about` which is just the
general info. This is just numbers.
"""
bot = self.bot
command_map = itertools.starmap('{1} {0}'.format, bot.command_counter.most_common())
command_stats = '\n'.join(command_map) or 'No stats yet.'
extension_stats = '\n'.join(f'{len(set(getattr(bot, attr).values()))} {attr}'
for attr in ('cogs', 'extensions'))
with self.process.oneshot():
memory_usage_in_mb = self.process.memory_full_info().uss / 1024**2
cpu_usage = self.process.cpu_percent() / psutil.cpu_count()
uptime_seconds = bot.uptime.total_seconds()
average_messages = bot.message_counter / uptime_seconds
message_field = f'{bot.message_counter} messages\n({average_messages :.2f} messages/sec)'
text, voice = partition(lambda c: isinstance(c, discord.TextChannel), bot.get_all_channels())
presence = (f"{bot.guild_count} Servers\n{ilen(text)} Text Channels\n"
f"{ilen(voice)} Voice Channels\n{bot.user_count} Users")
chiaki_embed = (discord.Embed(description=bot.appinfo.description, colour=self.bot.colour)
.set_author(name=str(ctx.bot.user), icon_url=bot.user.avatar_url)
.add_field(name='Modules', value=extension_stats)
.add_field(name='CPU Usage', value=f'{cpu_usage}%\n{memory_usage_in_mb :.2f}MB')
.add_field(name='Messages', value=message_field)
.add_field(name='Presence', value=presence)
.add_field(name='Commands', value=command_stats)
.add_field(name='Uptime', value=self.bot.str_uptime.replace(', ', '\n'))
)
await ctx.send(embed=chiaki_embed)
def convert(self, ctx, argument):
bot = ctx.bot
match = self._get_id_match(argument) or re.match(r'<#([0-9]+)>$', argument)
result = None
guild = ctx.guild
if match is not None:
return await super().convert(ctx, argument)
else:
if self.case_sensitive:
def check(c):
return isinstance(c, discord.TextChannel) and c.name == argument
else:
# not a mention
lowered = argument.lower()
def check(c):
return isinstance(c, discord.TextChannel) and c.name.lower() == lowered
if guild:
result = list(filter(check, guild.text_channels))
transform = str
else:
result = list(filter(check, bot.get_all_channels()))
transform = '{0} (Server: {0.guild})'
return await ctx.disambiguate(result, transform)
def send_message(self, ctx, channel: discord.TextChannel, *, msg):
"""Sends a message to a particular channel"""
owner = (await self.bot.application_info()).owner
await channel.send(f"Message from {owner}:\n{msg}")
await ctx.send(f"Successfully sent message in {channel}: {msg}")
def on_message(self, message):
#if message.channel.is_private:
if not isinstance(message.channel, discord.TextChannel):
return
if message.author.bot:
return
await self.process_commands(message)
def invite(self, ctx, guild=None):
"""
Creates an invite to a specified server
"""
guild_names = list("{} - ID: {}".format(g.name, g.id) for g in self.bot.guilds)
if guild is None:
guild = await reaction_menu.start_reaction_menu(self.bot, guild_names, ctx.author, ctx.channel, count=1,
timeout=60, per_page=10, header=header,
return_from=self.bot.guilds, allow_none=True)
guild = guild[0]
else:
guild = discord.utils.find(lambda s: s.name == guild or str(s.id) == guild, self.bot.guilds)
if guild is None:
await ctx.send("`Unable to locate guild`")
return
for channel in guild.channels:
if isinstance(channel, discord.TextChannel):
try:
invite = await channel.create_invite()
await ctx.send("`Created an invite to guild, I will DM it to you`")
dm_channel = ctx.author.dm_channel
if dm_channel is None:
dm_channel = await ctx.author.create_dm()
await dm_channel.send(invite.url)
break
except discord.HTTPException:
await ctx.send("`Failed to create invite for guild!`")