def find_target(self, ctx, arg):
"""Returns the ID of the given target"""
if arg.casefold() in ('everyone', 'all'):
return discord.Object(id=0)
try:
return await MemberConverter().convert(ctx, arg)
except BadArgument:
pass
try:
return await RoleConverter().convert(ctx, arg)
except BadArgument:
pass
return None
python类Object()的实例源码
def __init__(self, prefix: str, start_time: int, colour: int, logger,
session_manager: SessionManager, db: MongoClient,
error_log: int, feedback_log: int):
"""
Init the instance of HahaNoUR.
:param prefix: the bot prefix.
:param start_time: the bot start time.
:param colour: the colour used for embeds.
:param logger: the logger.
:param session_manager: the SessionManager instance.
:param db: the MongoDB data controller.
:param error_log: the channel id for error log.
"""
super().__init__(prefix)
self.prefix = prefix
self.colour = colour
self.start_time = start_time
self.logger = logger
self.help_general = None
self.all_help = None
self.db = db
self.session_manager = session_manager
# FIXME remove type casting after library rewrite
self.error_log = Object(str(error_log))
self.feedbag_log = Object(str(feedback_log))
def my_background_task():
client = discord.Client()
await client.wait_until_ready()
channel = discord.Object(id='189472786056478720')
feed = youtube.start()
while not client.is_closed:
update = youtube.update(feed)
if update != "304":
entry = youtube.getLastEntry()
YTEmbed = discord.Embed()
YTEmbed.colour = 0x3498db
YTEmbed.title = "Nouvelle vidéo sur la chaîne de Sakiut ! `" + entry['title'] + "`"
YTEmbed.description = "Vidéo : " + entry['link'] + "\nChaîne : " + entry['channel'] + "\nPosté le : " + entry['published']
YTEmbed.set_thumbnail(url = entry['thumbnail'])
YTEmbed.set_footer(text = "Posté par {0}".format(entry['author']))
await client.send_message(channel, "@everyone", embed = YTEmbed)
feed = youtube.start()
await asyncio.sleep(300)
def check_training(self):
await self.bot.wait_until_ready()
channel = discord.Object(id=overwatchChannelId) # SENDS TO CHANNEL OVERWATCH IN BANANA'S DISCORD
while not self.bot.is_closed:
now = datetime.datetime.now()
if now.weekday() == 0 or now.weekday() == 3:
if now.hour == 20:
role = discord.utils.find(lambda r: r.name == 'overwatch_players',
self.bot.get_server(bananasDiscordId).roles)
message = role.mention + ' Yo mes ptits poulets, oubliez pas le training de ce soir de 21h a 23h, sinon Loulou il va raler !'
await self.bot.send_message(channel, message)
elif now.weekday() == 5:
if now.hour == 15:
role = discord.utils.find(lambda r: r.name == 'overwatch_players',
self.bot.get_server(bananasDiscordId).roles)
message = role.mention + ' Yo mes ptits poulets, oubliez pas le training de cette apres-midi de 16h a 18h, sinon Loulou il va raler !'
await self.bot.send_message(channel, message)
await asyncio.sleep(3600) # task runs every hour
def ban(self, ctx, member: converters.RawMember, delete_days: DeleteDays=2, *, reason=None):
"""
Bans someone.
This command is special in that you may specify an ID to ban, instead of regularly specifying a
member to ban. Banning users outside of the server is called "hackbanning", and is handy for banning
users who are not present in the server.
If you don't want to delete any messages, specify 0 for delete_days. delete_days has a
maximum of 7. By default, 2 days worth of messages are deleted.
"""
try:
reason = reason or 'No reason provided.'
await ctx.guild.ban(member, delete_message_days=delete_days, reason=f'(Banned by {ctx.author}) {reason}')
ctx.bot.dispatch('member_dog_ban', member, ctx.author, reason)
except discord.Forbidden:
await ctx.send("I can't do that.")
except discord.NotFound:
await ctx.send("User not found.")
else:
banned = await ctx.bot.get_user_info(member.id) if isinstance(member, discord.Object) else member
await ctx.send(f'\N{OK HAND SIGN} Banned {describe(banned)}.')
def _remove_time_entry(self, guild, member, session, *, event='mute_complete'):
query = """SELECT *
FROM schedule
WHERE event = $3
AND args_kwargs #>> '{args,0}' = $1
AND args_kwargs #>> '{args,1}' = $2
ORDER BY expires
LIMIT 1;
"""
# We have to go to the lowest level possible, because simply using
# session.cursor WILL NOT work, as it uses str.format to format
# the parameters, which will throw a KeyError due to the {} in the
# JSON operators.
session = session.transaction.acquired_connection
entry = await session.fetchrow(query, str(guild.id), str(member.id), event)
if entry is None:
return None
await self.bot.db_scheduler.remove(discord.Object(id=entry['id']))
return entry
def remove_old(self):
for sid in self.aliases:
to_delete = []
to_add = []
for aliasname, alias in self.aliases[sid].items():
lower = aliasname.lower()
if aliasname != lower:
to_delete.append(aliasname)
to_add.append((lower, alias))
if aliasname != self.first_word(aliasname):
to_delete.append(aliasname)
continue
server = discord.Object(id=sid)
prefix = self.get_prefix(server, alias)
if prefix is not None:
self.aliases[sid][aliasname] = alias[len(prefix):]
for alias in to_delete: # Fixes caps and bad prefixes
del self.aliases[sid][alias]
for alias, command in to_add: # For fixing caps
self.aliases[sid][alias] = command
dataIO.save_json(self.file_path, self.aliases)
def unban(self, ctx, member_id: int):
"""Used to unban a member from this server
Due to the fact that I cannot find a user without being in a server with them
only the ID should be provided
EXAMPLE: !unban 353217589321750912
RESULT: That dude be unbanned"""
# Lets only accept an int for this method, in order to ensure only an ID is provided
# Due to that though, we need to ensure a string is passed as the member's ID
member = discord.Object(id=str(member_id))
try:
await self.bot.unban(ctx.message.server, member)
await self.bot.say("\N{OK HAND SIGN}")
except discord.Forbidden:
await self.bot.say("But I can't, muh permissions >:c")
except discord.HTTPException:
await self.bot.say("Sorry, I failed to unban that user!")
def feeds_delete(self, ctx, *, feed : str):
"""Removes a feed from the channel.
This will also delete the associated role so this
action is irreversible.
"""
channel = ctx.message.channel
server = channel.server
feeds = self.feeds.get(channel.id, {})
feed = feed.lower()
if feed not in feeds:
await self.bot.say('This feed does not exist.')
return
role = feeds.pop(feed)
try:
await self.bot.delete_role(server, discord.Object(id=role))
except discord.HTTPException:
await self.bot.say('\U0001F52B')
else:
await self.feeds.put(channel.id, feeds)
await self.bot.say('\U0001F6AE')
def do_subscription(self, ctx, feed, action):
channel = ctx.message.channel
member = ctx.message.author
feeds = self.feeds.get(channel.id, {})
feed = feed.lower()
if feed not in feeds:
await self.bot.say('This feed does not exist.')
return
role = feeds[feed]
function = getattr(self.bot, action)
try:
await function(member, discord.Object(id=role))
except discord.HTTPException:
# muh rate limit
await asyncio.sleep(10)
await function(member, discord.Object(id=role))
else:
await self.bot.send_message(channel, '\u2705')
def write_to_modlog(self, message, author, server, reason):
self.action_dict['actions_taken'] += 1
if server.id in self.server_index:
config = self.server_index[server.id]
else:
return
if not config[8] or not config[10][0]:
return
if not reason:
reason = "***No Reason Specified***"
content = message.clean_content
else:
content = message.clean_content.replace('\"{}\"'.format(reason), '')
await self.safe_send_message(discord.Object(id=config[8]),
'At `{}` UTC in **<#{}>**, **{}** used the command ```{}```Reason: `{}`'
''.format(datetime.utcnow().strftime("%H:%M:%S on %a %b %d"), message.channel.id,
clean_string(author.name), content, reason), server=server)
def _write_to_modlog(self, autoaction, offender, server, reason, channel=None):
self.action_dict['actions_taken'] += 1
await self.user_index_check(offender)
self.user_dict[offender.id]['actions_taken_against'] += 1
if server.id in self.server_index:
config = self.server_index[server.id]
else:
return
if not config[8] or not config[10][0]:
return
if not reason:
reason = "*No reason was specified*"
if not channel:
await self.safe_send_message(discord.Object(id=config[8]), 'At `{}` UTC, I automatically took action against **{}** due to {}.\n**Action:** __{}__.'
''.format(
datetime.utcnow().strftime("%H:%M:%S on %a %b %d"), clean_string(offender.name), autoaction,
reason))
else:
await self.safe_send_message(discord.Object(id=config[8]),
'At `{}` UTC, I automatically took action against **{}** in <#{}> due to {}. \n**Action:** __{}__'
''.format(datetime.utcnow().strftime("%H:%M:%S on %a %b %d"),
clean_string(offender.name), channel.id, reason, autoaction), server=server)
# TODO: Make this code that is mine, not stuff taken from code written by @Sharpwaves
def cmd_unban(self, message, author, server, leftover_args):
"""
Usage: {command_prefix}unban [id] ["reason"]
Unbans the user(s) from the server, accepts a list of user ids with spaces between each
"""
if await self.has_roles(message.channel, author, server, command='unban'):
reason = None
if not leftover_args:
raise CommandError('Usage: {command_prefix}unban [id] ["reason"]\nForces the ID to be banned from a server')
try:
int(leftover_args[-1])
except:
try:
reason = leftover_args[-1]
del leftover_args[-1]
except TypeError:
raise CommandError('Please use a **USER ID** when using this command and not a name')
for id in leftover_args:
await self.unban(server, discord.Object(id=id))
await self.write_to_modlog(message, author, server, reason)
def cmd_shutdown(self, channel, author, server):
"""
Usage: {command_prefix}forcebackup
Forces a back up of all server configs
"""
if author.id in [self.config.master_id]:
await self.safe_send_message(discord.Object(id='155553608400764928'),
'__**<@{}>**__ shutdown made in *{}* on `{}`'.format(author.id,
channel.name,
server.name
)
)
await self.safe_send_message(channel, '**Powering off :see_no_evil:**')
await self.backup_config(self.server_index)
await self.logout()
return
def ban(self, ctx, member: MemberID, *, reason: ActionReason = None):
"""Bans a member from the server.
You can also ban from ID to ban regardless whether they're
in the server or not.
In order for this to work, the bot must have Ban Member permissions.
To use this command you must have Ban Members permission.
"""
if reason is None:
reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'
await ctx.guild.ban(discord.Object(id=member), reason=reason)
await ctx.send('\N{OK HAND SIGN}')
def massban(self, ctx, reason: ActionReason, *members: MemberID):
"""Mass bans multiple members from the server.
You can also ban from ID to ban regardless whether they're
in the server or not.
Note that unlike the ban command, the reason comes first
and is not optional.
In order for this to work, the bot must have Ban Member permissions.
To use this command you must have Ban Members permission.
"""
for member_id in members:
await ctx.guild.ban(discord.Object(id=member_id), reason=reason)
await ctx.send('\N{OK HAND SIGN}')
def softban(self, ctx, member: MemberID, *, reason: ActionReason = None):
"""Soft bans a member from the server.
A softban is basically banning the member from the server but
then unbanning the member as well. This allows you to essentially
kick the member while removing their messages.
In order for this to work, the bot must have Ban Member permissions.
To use this command you must have Kick Members permissions.
"""
if reason is None:
reason = f'Action done by {ctx.author} (ID: {ctx.author.id})'
obj = discord.Object(id=member)
await ctx.guild.ban(obj, reason=reason)
await ctx.guild.unban(obj, reason=reason)
await ctx.send('\N{OK HAND SIGN}')
def on_tempban_timer_complete(self, timer):
guild_id, mod_id, member_id = timer.args
guild = self.bot.get_guild(guild_id)
if guild is None:
# RIP
return
moderator = guild.get_member(mod_id)
if moderator is None:
try:
moderator = await self.bot.get_user_info(mod_id)
except:
# request failed somehow
moderator = f'Mod ID {mod_id}'
else:
moderator = f'{moderator} (ID: {mod_id})'
else:
moderator = f'{moderator} (ID: {mod_id})'
reason = f'Automatic unban from timer made on {timer.created_at} by {moderator}.'
await guild.unban(discord.Object(id=member_id), reason=reason)
def remove_old(self):
for sid in self.aliases:
to_delete = []
to_add = []
for aliasname, alias in self.aliases[sid].items():
lower = aliasname.lower()
if aliasname != lower:
to_delete.append(aliasname)
to_add.append((lower, alias))
if aliasname != self.first_word(aliasname):
to_delete.append(aliasname)
continue
server = discord.Object(id=sid)
prefix = self.get_prefix(server, alias)
if prefix is not None:
self.aliases[sid][aliasname] = alias[len(prefix):]
for alias in to_delete: # Fixes caps and bad prefixes
del self.aliases[sid][alias]
for alias, command in to_add: # For fixing caps
self.aliases[sid][alias] = command
dataIO.save_json(self.file_path, self.aliases)
def filter(self):
await self.client.wait_until_ready()
# get arrays channels id need to post
discord_channels = []
for server in self.client.servers:
for channel in server.channels:
if channel.name in self.config.get('channels', []):
discord_channels.append(discord.Object(channel.id))
while not self.client.is_closed:
for channel in discord_channels:
await self.client.send_message(channel, message)
await asyncio.sleep(300)
def filter(self):
await self.client.wait_until_ready()
# get arrays channels id need to post
discord_channels = []
for server in self.client.servers:
for channel in server.channels:
if channel.name in self.config.get('channels', []):
discord_channels.append(
discord.Object(channel.id))
while not self.client.is_closed:
for channel in discord_channels:
await self.client.send_message(channel, message)
await asyncio.sleep(300)
def unfollow(ctx):
f = open('%susers/allusers.txt' % path, 'r+')
all = f.read().strip()
if all:
users = all.split(',')
else:
users = []
if ctx.message.author.id in users:
users.remove(ctx.message.author.id)
f.seek(0)
f.truncate()
if users != ['']:
for i in users:
if i:
f.write(i + ',')
else:
pass
os.remove('%susers/user%s.txt' % (path, ctx.message.author.id))
await bot.send_message(ctx.message.channel, 'You have unsubscribed from the reddit notifier feed. Use ``ap:follow`` to resubscribe if you\'d like. **Note: your list has been deleted** so if you subscribe again, you must remake your list.')
await bot.send_message(discord.Object(id=config["log_location"]), 'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content))
else:
await bot.send_message(ctx.message.channel, 'You are already unsubscribed from the notifier.')
f.close()
def off(ctx):
if not isFollowing(ctx.message.author.id):
await bot.send_message(ctx.message.channel, 'Use ``ap:follow`` first to subscribe to the bot. Do ``ap:commands`` for more help')
else:
f = open('%susers/user%s.txt' % (path, ctx.message.author.id), 'r+')
content = f.read()
f.seek(0)
if content.startswith('--disable--off'):
f.write(content)
elif content.startswith('off'):
f.write(content)
elif content.startswith('--disable--'):
f.write('--disable--off' + content[11:])
else:
f.write('off' + content)
f.close()
await bot.send_message(ctx.message.channel, 'The bot will no longer ping you on every message. Do ``ap:ping on`` to reverse this.')
await bot.send_message(discord.Object(id=config["log_location"]),
'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content))
def remove(ctx):
msg = '**Error** Something went wrong. Are you using the command right? Example use: ``ap:remove anime One Punch Man S2``'
try:
toUnfollow = ctx.message.content.split('ap:remove')[1].strip()
status = removeKeyWords(toUnfollow, ctx.message.author.id)
if status == True:
await bot.send_message(ctx.message.channel, 'Successfully removed ``%s`` from ``%s``. View your list with ``ap:list``.' % (toUnfollow.split(' ', 1)[1].strip(), toUnfollow.split(' ', 1)[0].strip()))
await bot.send_message(discord.Object(id=config["log_location"]),
'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content))
elif status == 'blacklist':
await bot.send_message(ctx.message.channel,
'Successfully removed all words from blacklist. View your list with ``ap:list``.')
await bot.send_message(discord.Object(id=config["log_location"]),
'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content))
else:
await bot.send_message(ctx.message.channel, msg)
except Exception as e:
traceback.print_exc()
await bot.send_message(ctx.message.channel, msg)
def edit(ctx):
msg = '**Error** Something went wrong. Are you using the command right? Example use: ``ap:edit anime One Punch Man S2 = opm s2, one punch man s2`` to replace entire entry. Add a ``+`` or ``-`` after ``edit`` to just add or remove some keywords from entry.'
sub = ctx.message.content.split('edit', 1)[1].strip()
if sub:
try:
entry = editEntry(sub, ctx.message.author.id)
if '=' in entry:
await bot.send_message(ctx.message.channel, 'Successfully edited entry. Entry is now: %s. View your list with ``ap:list``.' % entry)
await bot.send_message(discord.Object(id=config["log_location"]),
'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content))
else:
await bot.send_message(ctx.message.channel, '**Could not find the specified entry.**')
await bot.send_message(discord.Object(id=config["log_location"]),
'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content))
except:
await bot.send_message(ctx.message.channel, '**Error** Something went wrong. Are you using the command right? Example uses: ``ap:edit + manga Boku no Hero`` For changing notifications to all threads (``-`` for episode/chapters only) or ``ap:edit manga Boku no Hero = my hero academia, boku no hero academia`` to change the entry values.')
traceback.print_exc()
else:
await bot.send_message(ctx.message.channel, msg)
def _send_message(self, channel_id, message):
await self.client.login(self.token)
self.client.connect()
c = discord.Object(id=channel_id)
await self.client.send_message(c, message)
await self.client.logout()
await self.client.close()
def echoserver(self, ctx, serverName:str, channelName:str, *, content:str):
'''
Echos some content back into another server
'''
# It'll only be the owner sending this so there doesn't need to be any error handling.
server = [i for i in self.sparcli.servers if i.name.lower() == serverName.lower()][0]
if channelName.isdigit():
channel = Object(channelName)
elif channelName.startswith('<#') and channelName.endswith('>'):
channel = Object(channelName[2:-1])
else:
channel = [i for i in server.channels if i.name.lower() == channelName.lower()][0]
await self.sparcli.send_message(channel, content)
def as_object(obj_id: str) -> discord.Object:
""" Creates a basic Discord Object given an ID.
:param obj_id: The ID of the object being created
:type obj_id: str
:return: The new object with the specified ID.
"""
return discord.Object(obj_id)
def newstuff(self):
"""sends a message about a new feature in all servers"""
await self.bot.say("\U0001f44d")
await self.bot.send_message(discord.Object(id='248106639410855936'), "@here, A new WordPress post about my development has been made, check it out at <https://inkxbot.wordpress.com/>")
await self.bot.send_message(discord.Object(id='227514633735372801'), "A new WordPress post about my development has been made, check it out at <https://inkxbot.wordpress.com/>")
await self.bot.send_message(discord.Object(id='258350226279104512'), "A new WordPress post about my development has been made, check it out at <https://inkxbot.wordpress.com/>")
def __init__(self, bot):
self.bot = bot
self.channel = channel = discord.Object(id='189472786056478720')
self.feed = youtube.start()