def channel(self, ctx, channel: discord.Channel, status: str):
"""Sets whether or not the channel will be
locked down if a lockdown is turned on
Options for status are on or off"""
server = ctx.message.server
new_status = None
if status.lower() != "on" and status.lower() != "off":
await self.bot.say("Invalid status specified!")
return
else:
if status.lower() == "on":
new_status = True
else:
new_status = False
if server.id not in self.settings:
self.settings[server.id] = {}
if "channels" not in self.settings[server.id]:
self.settings[server.id]["channels"] = {}
if channel.id not in self.settings[server.id]["channels"]:
self.settings[server.id]["channels"][channel.id] = None
self.settings[server.id]["channels"][channel.id] = new_status
dataIO.save_json("data/lockdown/settings.json", self.settings)
await self.bot.say("New status for {} set!".format(channel.mention))
python类Channel()的实例源码
def deletenewschannel(self, ctx, channel: discord.Channel):
"""Removes news functionality for a channel"""
server = ctx.message.server
if server.id not in self.settings:
await self.bot.say("Nothing available for this server!")
return
if channel.id not in self.settings[server.id]:
await self.bot.say("News functionality isn't set up for that channel!")
return
role = [r for r in ctx.message.server.roles if r.id == self.settings[server.id][channel.id]["role_id"]][0]
try:
await self.bot.delete_role(server, role)
except discord.Forbidden:
await self.bot.say("I cannot delete roles!")
return
except discord.HTTPException:
await self.bot.say("Something went wrong!")
return
else:
await self.bot.say("Role removed!")
self.settings[server.id].pop(channel.id, None)
dataIO.save_json("data/newsannouncer/settings.json", self.settings)
def trackmentions(self, ctx, status: str, channel: discord.Channel=None):
"""Toggles mention tracking for the specified channel.
Defaults to the current channel."""
if not channel:
channel = ctx.message.channel
author = ctx.message.author
if author.id not in self.settings:
self.settings[author.id] = {}
if channel.id not in self.settings[author.id]:
self.settings[author.id][channel.id] = None
if status.lower() == "on" or status.lower() == "off":
self.settings[author.id][channel.id] = True if status.lower() == "on" else False
dataIO.save_json("data/mentiontracker/settings.json", self.settings)
await self.bot.say("Mention tracker toggled!")
else:
await self.bot.say("Invalid status specified!")
def listwords(self, ctx: commands.Context, channel: discord.Channel=None):
"""List all words for the specified channel
Optional parameters:
- channel: the channel to show words for (defaults to the current channel)"""
author = ctx.message.author
if not channel:
channel = ctx.message.channel
if author.id not in self.settings or\
"words" not in self.settings[author.id] or\
channel.id not in self.settings[author.id]["words"] or\
not self.settings[author.id]["words"][channel.id]:
await self.bot.say("You haven't set any words to be tracked!")
else:
head = "Tracked words for {}#{} in #{}".format(author.name, author.discriminator, channel.name)
msg = ""
for word in self.settings[author.id]["words"][channel.id]:
msg += "{}\n".format(word)
await self.bot.say(box(msg, lang=head))
def notifications(self, ctx, channel: discord.Channel):
"""This command is used to set a channel as the server's 'notifications' channel
Any notifications (like someone going live on Twitch, or Picarto) will go to that channel
EXAMPLE: !alerts #alerts
RESULT: No more alerts spammed in #general!"""
if str(channel.type) != "text":
await self.bot.say("The notifications channel must be a text channel!")
return
key = ctx.message.server.id
entry = {'server_id': key,
'notification_channel': channel.id}
if not await utils.update_content('server_settings', entry, key):
await utils.add_content('server_settings', entry)
await self.bot.say("I have just changed this server's 'notifications' channel"
"\nAll notifications will now go to `{}`".format(channel))
def join_channel(self, channel: Channel):
if channel.server != self.server:
raise ValueError("Attempted to join a channel on a different server.")
if self.voice is not None:
if self.voice.channel.id == channel.id:
logger.info("Tried to join a channel that we are already on. Ignoring.")
return
logger.info("Moving channel.")
await self.voice.move_to(channel)
self.find_voice_client()
return
try:
self.voice = await client.join_voice_channel(channel)
except:
self.find_voice_client()
logger.info("Joined channel %s, voice client: %s", channel.name, self.voice)
def channel(self, ctx, channel : discord.Channel=None):
"""Sets the channel to send the welcome message
If channel isn't specified, the server's default channel will be used"""
server = ctx.message.server
if channel is None:
channel = ctx.message.server.default_channel
if not server.get_member(self.bot.user.id
).permissions_in(channel).send_messages:
await self.bot.say("I do not have permissions to send "
"messages to {0.mention}".format(channel))
return
self.settings[server.id]["CHANNEL"] = channel.id
dataIO.save_json(settings_path, self.settings)
channel = self.get_welcome_channel(server)
await self.bot.send_message(channel, "I will now send welcome "
"messages to {0.mention}".format(channel))
await self.send_testing_msg(ctx)
def blacklist_add(self, ctx, value:str, *, obj:MultiMention):
if isinstance(obj, discord.Server):
kwargs = dict(server_id=int(obj.id))
elif isinstance(obj, discord.Channel):
kwargs = dict(channel_id=int(obj.id))
elif isinstance(obj, discord.Role):
kwargs = dict(role_id=int(obj.id))
elif isinstance(obj, discord.Member):
kwargs = dict(user_id=int(obj.id))
with self.bot.db_scope() as session:
blacklist_obj = session.query(sql.Blacklist).filter_by(**kwargs, data=value).first()
if blacklist_obj is not None:
await self.bot.say(f"{obj.__class__.__name__} **{str(obj)}** has already been blacklisted for `{value}`")
return
else:
blacklist_obj = sql.Blacklist(**kwargs, data=value)
session.add(blacklist_obj)
await self.bot.say(f"Blacklisted {obj.__class__.__name__} **{str(obj)}** for `{value}`")
def blacklist_remove(self, ctx, value:str, *, obj:MultiMention):
if isinstance(obj, discord.Server):
kwargs = dict(server_id=int(obj.id))
elif isinstance(obj, discord.Channel):
kwargs = dict(channel_id=int(obj.id))
elif isinstance(obj, discord.Role):
kwargs = dict(role_id=int(obj.id))
elif isinstance(obj, discord.Member):
kwargs = dict(user_id=int(obj.id))
with self.bot.db_scope() as session:
blacklist_obj = session.query(sql.Blacklist).filter_by(**kwargs, data=value).first()
if blacklist_obj is None:
await self.bot.say(f"{obj.__class__.__name__} **{str(obj)}** is not blacklisted for `{value}`")
return
else:
session.delete(blacklist_obj)
await self.bot.say(f"Removed {obj.__class__.__name__} **{str(obj)}** from blacklist for `{value}`")
def blacklist_search(self, ctx, *, obj:MultiMention):
if isinstance(obj, discord.Server):
kwargs = dict(server_id=int(obj.id))
elif isinstance(obj, discord.Channel):
kwargs = dict(channel_id=int(obj.id))
elif isinstance(obj, discord.Role):
kwargs = dict(role_id=int(obj.id))
elif isinstance(obj, discord.Member):
kwargs = dict(user_id=int(obj.id))
with self.bot.db_scope() as session:
blacklist_objs = session.query(sql.Blacklist).filter_by(**kwargs).all()
if len(blacklist_objs) > 0:
result_text = f"```md\n# {obj.__class__.__name__} {str(obj)} is blacklisted for\n" + "\n".join(f"- {b_obj.data}" for b_obj in blacklist_objs) + "\n```"
else:
result_text = f"```md\n# {obj.__class__.__name__} {str(obj)} is not blacklisted\n```"
await self.bot.say(result_text)
def channel_cmd(self, ctx, *, channel : discord.Channel = None):
"""Ignores a specific channel from being processed.
If no channel is specified, the current channel is ignored.
If a channel is ignored then the bot does not process commands in that
channel until it is unignored.
"""
if channel is None:
channel = ctx.message.channel
ignored = self.config.get('ignored', [])
if channel.id in ignored:
await self.bot.say('That channel is already ignored.')
return
ignored.append(channel.id)
await self.config.put('ignored', ignored)
await self.bot.say('**Done!** The channel is ignored.')
def unignore(self, ctx, *channels: discord.Channel):
"""Unignores channels from being processed.
If no channels are specified, it unignores the current channel.
To use this command you must have the Manage Channels permission or have the
Bot Admin role.
"""
if len(channels) == 0:
channels = (ctx.message.channel,)
# a set is the proper data type for the ignore list
# however, JSON only supports arrays and objects not sets.
ignored = self.config.get('ignored', [])
for channel in channels:
try:
ignored.remove(channel.id)
except ValueError:
pass
await self.config.put('ignored', ignored)
await self.bot.say('**Done!** The channels are unignored.')
def pinmsgdate(self, ctx, date: date, *, channel: discord.Channel = None):
"""Pins an old message from a specific date.
If a channel is not given, then pins from the channel the
command was ran on.
The format of the date must be either YYYY-MM-DD or YYYY/MM/DD.
"""
if channel is None:
channel = ctx.message.channel
async for m in self.bot.logs_from(channel, after=date, limit=1):
try:
await self.bot.pin_message(m)
except:
await self.bot.say('**Error!** Could not pin message.')
else:
await self.bot.say('**Done!** Successfully pinned message.')
def channel(self, ctx, channel: discord.Channel=None):
"""Sets the channel to send the update announcement
If channel isn't specified, the server's default channel will be used"""
server = ctx.message.server
if channel is None:
channel = ctx.message.server.default_channel
if not server.get_member(self.bot.user.id
).permissions_in(channel).send_messages:
await self.bot.say("I do not have permissions to send "
"messages to {0.mention}".format(channel))
return
self.settings[server.id]["CHANNEL"] = channel.id
dataIO.save_json('data/guildwars2/settings.json', self.settings)
channel = self.get_announcement_channel(server)
await self.bot.send_message(channel, "I will now send build announcement "
"messages to {0.mention}".format(channel))
def _channel(self, ctx: commands.Context,
channel: discord.Channel=None):
"""Change le channel où doit être envoyé les messages d'activation de trigger.
Par défaut le présent."""
await self.bot.type()
server = ctx.message.server
if not channel:
channel = server.default_channel
if not self.speak_permissions(server, channel):
await self.bot.say(
"Je n'ai pas les permissions d'envoyer de message sur {0.mention}.".format(channel))
return
self.settings[server.id]["channel"] = channel.id
dataIO.save_json(self.settings_path, self.settings)
channel = self.get_welcome_channel(server)
await self.bot.send_message(channel,"{0.mention}, " + "Je vais maintenant envoyer les messages d'annonce" + "sur {1.mention}.".format(ctx.message.author, channel))
def on_message_delete(self, message):
server = message.server
member = message.author
channel = message.channel
timestamp = datetime.utcnow()
if await self._ignore(server, member=member, channel=channel):
if await self._validate_event(server) and member.id != self.bot.user.id:
embed = discord.Embed(color=self.red)
avatar = member.avatar_url if member.avatar else member.default_avatar_url
embed.set_author(name='Message removed', icon_url=avatar)
embed.add_field(name='**Member**', value='{0.display_name}#{0.discriminator} ({0.id})'.format(member))
embed.add_field(name='**Channel**', value=message.channel.name)
embed.add_field(name='**Message timestamp**', value=message.timestamp.strftime('%Y-%m-%d %H:%M:%S'))
embed.add_field(name='**Removal timestamp**', value=timestamp.strftime('%Y-%m-%d %H:%M:%S'))
if message.content:
embed.add_field(name='**Message**', value=message.content, inline=False)
if message.attachments:
for attachment in message.attachments:
embed.add_field(name='**Attachment**', value='[{filename}]({url})'.format(**attachment), inline=True)
await self._send_message_to_channel(server, embed=embed)
def on_message_edit(self, before, after):
server = after.server
member = after.author
channel = after.channel
timestamp = datetime.utcnow()
if not channel.is_private:
if await self._ignore(server, member=member, channel=channel):
if await self._validate_event(server) and member.id != self.bot.user.id and before.clean_content != after.clean_content:
embed = discord.Embed(color=self.blue)
avatar = member.avatar_url if member.avatar else member.default_avatar_url
embed.set_author(name='Message changed'.format(member), icon_url=avatar)
embed.add_field(name='**Member**', value='{0.display_name}#{0.discriminator}\n({0.id})'.format(member))
embed.add_field(name='**Channel**', value=before.channel.name)
embed.add_field(name='**Message timestamp**', value=before.timestamp.strftime('%Y-%m-%d %H:%M:%S'))
embed.add_field(name='**Edit timestamp**', value=timestamp.strftime('%Y-%m-%d %H:%M:%S'))
embed.add_field(name='**Before**', value=before.content, inline=False)
embed.add_field(name='**After**', value=after.content, inline=False)
await self._send_message_to_channel(server, embed=embed)
def _ignore(self, context, channel: discord.Channel):
"""[channel]"""
data = dataIO.load_json(self.ignore_file)
current_server = context.message.server.id
current_channel = channel.id
if current_server not in data:
data[current_server] = []
if current_channel not in data[current_server]:
data[current_server].append(current_channel)
message = 'Ignoring {}'.format(channel.mention)
else:
data[current_server].remove(current_channel)
message = 'Unignoring {}'.format(channel.mention)
dataIO.save_json(self.ignore_file, data)
await self.bot.say('*{}*'.format(message))
def modlog(self, ctx, channel : discord.Channel=None):
"""Sets a channel as mod log
Leaving the channel parameter empty will deactivate it"""
server = ctx.message.server
if channel:
self.settings[server.id]["mod-log"] = channel.id
await self.bot.say("Mod events will be sent to {}"
"".format(channel.mention))
else:
if self.settings[server.id]["mod-log"] is None:
await send_cmd_help(ctx)
return
self.settings[server.id]["mod-log"] = None
await self.bot.say("Mod log deactivated.")
dataIO.save_json("data/mod/settings.json", self.settings)
def ignore_channel(self, ctx, channel: discord.Channel=None):
"""Ignores channel
Defaults to current one"""
current_ch = ctx.message.channel
if not channel:
if current_ch.id not in self.ignore_list["CHANNELS"]:
self.ignore_list["CHANNELS"].append(current_ch.id)
dataIO.save_json("data/mod/ignorelist.json", self.ignore_list)
await self.bot.say("Channel added to ignore list.")
else:
await self.bot.say("Channel already in ignore list.")
else:
if channel.id not in self.ignore_list["CHANNELS"]:
self.ignore_list["CHANNELS"].append(channel.id)
dataIO.save_json("data/mod/ignorelist.json", self.ignore_list)
await self.bot.say("Channel added to ignore list.")
else:
await self.bot.say("Channel already in ignore list.")