def code_clear(self, settings, server, user, number):
userid = [subdict for subdict in settings["Pending"]
if number in settings["Pending"][subdict]]
if userid:
mobj = server.get_member(userid[0])
await self.bot.say("Do you want to clear this pending item for {}?".format(mobj.name))
response = await self.bot.wait_for_message(timeout=15, author=user)
if response is None:
msg = "Timeout response, cancelling clear command."
elif response.content.title() == "No":
msg = "Cancelling clear command."
elif response.content.title() == "Yes":
settings["Pending"][mobj.id].pop(number, None)
msg = "Pending item {}, cleared for user {}".format(number, mobj.name)
else:
msg = "Incorrect response, cancelling clear command."
else:
msg = "The confirmation code provided could not be found."
await self.bot.say(msg)
python类command()的实例源码
def _xferlimit_setcasino(self, ctx, limit: int):
"""This is the limit of chips a player can transfer at one time.
Remember, that without a cooldown, a player can still use this command
over and over. This is just to prevent a transfer of outrageous amounts.
"""
author = ctx.message.author
settings = super().check_server_settings(author.server)
if limit > 0:
settings["System Config"]["Transfer Limit"] = limit
msg = _("{} set transfer limit to {}.").format(author.name, limit)
logger.info("SETTINGS CHANGED {}({}) {}".format(author.name, author.id, msg))
super().save_system()
else:
msg = _("Limit must be higher than 0.")
await self.bot.say(msg)
def recheckrole(self, ctx, *, user : discord.Member = None):
"""Re-iterate through all members and assign the proper roles based on their xp (admin only)."""
author = ctx.message.author
server = ctx.message.server
channel = ctx.message.channel
isAdmin = author.permissions_in(channel).administrator
# Only allow admins to change server stats
if not isAdmin:
await self.bot.send_message(channel, 'You do not have sufficient privileges to access this command.')
return
if not user:
user = author
# Now we check for promotions
if await CheckRoles.checkroles(user, channel, self.settings, self.bot):
await self.bot.send_message(channel, 'Done checking roles.\n\n*{}* was updated.'.format(DisplayName.name(user)))
else:
await self.bot.send_message(channel, 'Done checking roles.\n\n*{}* was not updated.'.format(DisplayName.name(user)))
def on_command_error(self, error, ctx):
ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure,
commands.CommandNotFound, commands.UserInputError, discord.HTTPException)
error = getattr(error, 'original', error)
if isinstance(error, ignored):
return
if ctx.message.server:
fmt = 'Channel: {0} (ID: {0.id})\nGuild: {1} (ID: {1.id})'
else:
fmt = 'Channel: {0} (ID: {0.id})'
exc = traceback.format_exception(type(error), error, error.__traceback__, chain=False)
description = '```py\n%s\n```' % ''.join(exc)
time = datetime.datetime.utcnow()
name = ctx.command.qualified_name
author = '{0} (ID: {0.id})'.format(ctx.message.author)
location = fmt.format(ctx.message.channel, ctx.message.server)
message = '{0} at {1}: Called by: {2} in {3}. More info: {4}'.format(name, time, author, location, description)
self.bot.logs['discord'].critical(message)
def notify_handler(self, settings, ctx, itemname, user, confirmation):
role = settings["Config"]["Shop Role"]
if "Role" not in settings["Users"][user.id]["Inventory"][itemname]:
if settings["Config"]["Shop Notify"] and role is not None:
msg = ("{} was added to the pending list by {}.\nConfirmation#: {}.\nUser ID: "
"{}".format(itemname, user.name, confirmation, user.id))
names = self.role_check(role, ctx)
destinations = [m for m in ctx.message.server.members if m.name in names]
for destination in destinations:
await self.bot.send_message(destination, msg)
await self.bot.say("```{} has been added to pending list. Your confirmation number is "
"{}.\nTo check the status of your pending items, use the command "
"{}pending check```".format(itemname, confirmation, ctx.prefix))
else:
await self.bot.say("{} just received the {} role!".format(user.name, itemname))
quantity = 1
self.user_remove_item(settings, user, itemname, quantity)
def blackjack(self, ctx, bet: int):
"""Modified Blackjack."""
# Declare variables for the game.
user = ctx.message.author
settings = super().check_server_settings(user.server)
# Run a logic check to determine if the user can play the game
check = self.game_checks(settings, ctx.prefix, user, bet, "Blackjack", 1, [1])
if check:
msg = check
else: # Run the game when the checks return None
super().withdraw_chips(user, bet)
settings["Players"][user.id]["Played"]["Blackjack"] += 1
deck = main_deck[:] # Make a copy of the deck so we can remove cards that are drawn
dhand = self.dealer(deck)
ph, dh, amt = await self.blackjack_game(dhand, user, bet, deck)
msg = self.blackjack_results(settings, user, amt, ph, dh)
# Send a message telling the user the outcome of this command
await self.bot.say(msg)
def gofish_start(self, ctx, *players : str):
'''WIP'''
self.gofish_channel = ctx.message.channel
if ctx.message.server:
for member in ctx.message.server.members:
if member.name in players:
self.gofish_players.append(member)
break
else:
await self.bot.embed_reply(":no_entry: Please use that command in a server")
pass
gofish.start(len(players))
gofish_players_string = ""
for player in self.gofish_players:
gofish_players_string += player.name + " and "
await self.bot.embed_reply("{} has started a game of Go Fish between {}!".format(message.author.display_name, gofish_players_string[:-5]))
def __init__(self, bot):
self.bot = bot
# Add commands as random subcommands
for name, command in inspect.getmembers(self):
if isinstance(command, commands.Command) and command.parent is None and name != "random":
self.bot.add_command(command)
self.random.add_command(command)
# Add fact subcommands as subcommands of corresponding commands
for command, parent in ((self.fact_cat, self.cat), (self.fact_date, self.date), (self.fact_number, self.number)):
utilities.add_as_subcommand(self, command, parent, "fact")
# Add random subcommands as subcommands of corresponding commands
self.random_subcommands = ((self.color, "Resources.color"), (self.giphy, "Resources.giphy"), (self.map, "Resources.map"), (self.streetview, "Resources.streetview"), (self.uesp, "Search.uesp"), (self.wikipedia, "Search.wikipedia"), (self.xkcd, "Resources.xkcd"))
for command, parent_name in self.random_subcommands:
utilities.add_as_subcommand(self, command, parent_name, "random")
# Import jokes
self.jokes = []
try:
with open("data/jokes.csv", newline = "") as jokes_file:
jokes_reader = csv.reader(jokes_file)
for row in jokes_reader:
self.jokes.append(row[0])
except FileNotFoundError:
pass
def discriminator(self, ctx, *, name : str = ""):
'''
Get a discriminator
Your own or someone else's discriminator
'''
if not name:
await self.bot.embed_reply("Your discriminator: #" + ctx.message.author.discriminator)
return
if not ctx.message.server:
await self.bot.embed_reply(":no_entry: Please use that command in a server")
return
flag = True
for member in ctx.message.server.members:
if member.name == name:
embed = discord.Embed(description = name + "'s discriminator: #" + member.discriminator, color = clients.bot_color)
avatar = member.default_avatar_url if not member.avatar else member.avatar_url
embed.set_author(name = str(member), icon_url = avatar)
await self.bot.reply("", embed = embed)
flag = False
if flag and name:
await self.bot.embed_reply(name + " was not found on this server")
def setwelcome(self, ctx, *, message = None):
"""Sets the welcome message for your server (bot-admin only). [[user]] = user name, [[atuser]] = user mention, [[server]] = server name"""
isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
if not isAdmin:
checkAdmin = self.settings.getServerStat(ctx.message.server, "AdminArray")
for role in ctx.message.author.roles:
for aRole in checkAdmin:
# Get the role that corresponds to the id
if aRole['ID'] == role.id:
isAdmin = True
# Only allow admins to change server stats
if not isAdmin:
await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
return
if message == None:
self.settings.setServerStat(ctx.message.server, "Welcome", None)
await self.bot.send_message(ctx.message.channel, 'Welcome message removed!')
return
self.settings.setServerStat(ctx.message.server, "Welcome", message)
await self.bot.send_message(ctx.message.channel, 'Welcome message updated!\n\nHere\'s a preview:')
await self._welcome(ctx.message.author, ctx.message.server, ctx.message.channel)
def setgoodbye(self, ctx, *, message = None):
"""Sets the goodbye message for your server (bot-admin only). [[user]] = user name, [[atuser]] = user mention, [[server]] = server name"""
isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
if not isAdmin:
checkAdmin = self.settings.getServerStat(ctx.message.server, "AdminArray")
for role in ctx.message.author.roles:
for aRole in checkAdmin:
# Get the role that corresponds to the id
if aRole['ID'] == role.id:
isAdmin = True
# Only allow admins to change server stats
if not isAdmin:
await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
return
if message == None:
self.settings.setServerStat(ctx.message.server, "Goodbye", None)
await self.bot.send_message(ctx.message.channel, 'Goodbye message removed!')
return
self.settings.setServerStat(ctx.message.server, "Goodbye", message)
await self.bot.send_message(ctx.message.channel, 'Goodbye message updated!\n\nHere\'s a preview:')
await self._goodbye(ctx.message.author, ctx.message.server, ctx.message.channel)
def setrules(self, ctx, *, rules : str = None):
"""Set the server's rules (admin only)."""
isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
# Only allow admins to change server stats
if not isAdmin:
await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
return
if rules == None:
rules = ""
self.settings.setServerStat(ctx.message.server, "Rules", rules)
msg = 'Rules now set to:\n{}'.format(rules)
await self.bot.send_message(ctx.message.channel, msg)
def setsstat(self, ctx, stat : str = None, value : str = None):
"""Sets a server stat (admin only)."""
author = ctx.message.author
server = ctx.message.server
channel = ctx.message.channel
isAdmin = author.permissions_in(ctx.message.channel).administrator
# Only allow admins to change server stats
if not isAdmin:
await self.bot.send_message(channel, 'You do not have sufficient privileges to access this command.')
return
if stat == None or value == None:
msg = 'Usage: `{}setsstat Stat Value`'.format(ctx.prefix)
await self.bot.send_message(channel, msg)
return
self.setServerStat(server, stat, value)
msg = '**{}** set to *{}!*'.format(stat, value)
await self.bot.send_message(channel, msg)
def recheckroles(self, ctx):
"""Re-iterate through all members and assign the proper roles based on their xp (admin only)."""
author = ctx.message.author
server = ctx.message.server
channel = ctx.message.channel
isAdmin = author.permissions_in(channel).administrator
# Only allow admins to change server stats
if not isAdmin:
await self.bot.send_message(channel, 'You do not have sufficient privileges to access this command.')
return
changeCount = 0
for member in server.members:
# Now we check for promotions
if await CheckRoles.checkroles(member, channel, self.settings, self.bot, True):
changeCount += 1
if changeCount == 1:
await self.bot.send_message(channel, 'Done checking roles.\n\n*1 user* updated.')
else:
await self.bot.send_message(channel, 'Done checking roles.\n\n*{} users* updated.'.format(changeCount))
def setchatchannel(self, ctx, *, channel : discord.Channel = None):
"""Sets the channel for bot chatter."""
isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
# Only allow admins to change server stats
if not isAdmin:
await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
return
if channel == None:
self.settings.setServerStat(ctx.message.server, "ChatChannel", "")
msg = 'Chat channel removed - must use the `{}chat [message]` command to chat.'.format(ctx.prefix)
await self.bot.send_message(ctx.message.channel, msg)
return
# If we made it this far - then we can add it
self.settings.setServerStat(ctx.message.server, "ChatChannel", channel.id)
msg = 'Chat channel set to **{}**.'.format(channel.name)
await self.bot.send_message(ctx.message.channel, msg)
def setbotparts(self, ctx, *, parts : str = None):
"""Set the bot's parts - can be a url, formatted text, or nothing to clear."""
isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
# Only allow admins to change server stats
if not isAdmin:
await self.bot.send_message(ctx.message.channel, 'You do not have sufficient privileges to access this command.')
return
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.server
if not parts:
parts = ""
self.settings.setUserStat(self.bot.user, server, "Parts", parts)
msg = '*{}\'s* parts have been set to:\n{}'.format(DisplayName.serverNick(self.bot.user, server), parts)
await self.bot.send_message(channel, msg)
def addcommand(self, ctx, *, command):
"""Restricts all co-owners from using [command] """
confirm = await self._confirm_owner(ctx)
if not confirm:
return
AliasCog = self.bot.get_cog('Alias')
if AliasCog:
alias_loaded = False
else:
alias_loaded = True
server = ctx.message.server
t = True if self.bot.get_command(command) else False
if not t and alias_loaded:
t = True if command in AliasCog.aliases[server.id] else False
if t and command not in self.settings["RESTRICTED"]:
await self.bot.say("**All owners will be restricted from using**: {}".format(command))
self.settings["RESTRICTED"].append(command)
dataIO.save_json(self.path, self.settings)
elif command in self.settings["RESTRICTED"]:
await self.bot.say("{} is already a restricted command".format(command))
else:
await self.bot.say("{} is not a valid command.".format(command))
def get_command_signature(self, prefix, cmd):
"""Create a user friendly command signature"""
result = []
params = cmd.clean_params
parent = cmd.full_parent_name
name = prefix + cmd.name if not parent else prefix + parent + ' ' + cmd.name
result.append(name)
# Format arguments to display which are required and which are optional
if len(params) > 0:
for name, param in params.items():
if param.default is not param.empty:
result.append('[{}]'.format(name))
elif param.kind == param.VAR_POSITIONAL:
result.append('[{}...]'.format(name))
else:
result.append('<{}>'.format(name))
return(' '.join(result))
def on_guild_join(self, guild):
"""Send welcome message to the server owner"""
message = ("Greetings! My name is **{}**, and my sole responsibility is to help you and "
"your group kick ass in Destiny 2! You're receiving this message because you "
"or one of your trusted associates has added me to **{}**.\n\n"
"**Command Prefix**\n\n"
"My default prefix is **!**, but you can also just mention me with **@{}**. "
"If another bot is already using the **!** prefix, you can choose a different prefix "
"for your server with **!settings setprefix <new_prefix>** (don't include the brackets).\n\n"
"For a list of all available commands, use the **!help** command. If you want more "
"information on a command, use **!help <command_name>**.\n\n"
"If you have any feedback, you can use my **!feedback** command to send "
"a message to my developer! If you want to request a feature, report a bug, "
"stay up to date with new features, or just want some extra help, check out the official "
"{} Support server! (https://discord.gg/GXCFpkr)"
).format(self.bot.user.name, guild.name, self.bot.user.name,
self.bot.user.name, self.bot.user.name)
await guild.owner.send(message)
def spam(self, ctx, user : discord.Member, spamtext, number : int=0):
"""Spams x times, default is 4."""
if user.id == "96987941519237120":
await self.bot.say("Hell nah, I ain't spamming him.")
return
if user.id == settings.owner:
await self.bot.say("Hell nah, I ain't spamming him. If you want to spam my owner use the `suggest` command!")
return
if number >> 8:
await self.bot.say("Hell nah, not past 8 for fck sakes.")
return
if number == 0:
number = 4
counter = 0
while counter < number:
try:
await self.bot.send_message(user, "{}, sent by **{}**".format(spamtext, ctx.message.author))
except discord.Forbidden:
await self.bot.say("{} blocked me :sob:".format(user.mention))
return
counter = counter + 1
if counter == 1:
await self.bot.say("Hehe, {} got spammed {} time!".format(user.mention, counter))
else:
await self.bot.say("Hehe, {} got spammed {} time!".format(user.mention, counter))
def nostalgia(self, ctx, date: date = None, *, channel: discord.TextChannel = None):
"""Pins an old message from a specific date.
If a date is not given, then pins first message from the channel.
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.channel
if date is None:
date = channel.created_at
async for m in ctx.history(after=date, limit=1):
try:
await m.pin()
except:
await ctx.send('\N{THUMBS DOWN SIGN} Could not pin message.')
def on_member_join(self, member):
"""Automatically assign roles if guild has a role set through `newrole` command."""
if not member.guild.me.guild_permissions.manage_roles:
return
async with self.bot.db_pool.acquire() as con:
role_id = await con.fetchval('''
SELECT role_id FROM newrole WHERE guild_id = $1
''', member.guild.id)
if role_id is None:
return
role = discord.utils.get(member.guild.roles, id=role_id)
if role is None:
async with con.transaction():
await con.execute('''
DELETE FROM newrole WHERE guild_id = $1
''', member.guild.id)
return
await member.add_roles(role, reason='New Member')
def rquote(self, ctx):
"""From a list of random quotes, it says one."""
quotes = [
'YOU THOUGHT THIS COMMENT WOULD MENTION [name] BUT IT WAS I, DIO!',
'Even [name] didn\'t understand the usage of this command, However, [name] knew the truth! This command existed in order to be fun! The quotes that fueled the fun made this command exist! This command makes appear a random quote! he said.',
'DID YOU QUOTE THIS TOO, [name]!? TELL ME!?\nWhat are you even asking? i settled this quote and you walked right into it!',
'Even a bastard like me spot true evil when it sees it, true evil are those who use the weak for their own gain! Especially a innocent woman! And that is exactly what you\'ve done, isnt it [name]?!, thats why... I\'ll judge you myself!',
'What is a [name]? A miserable little pile of secrets. But enough talk.',
'Thank you [name]! But our Princess is in another castle!',
'This is your fault. I\'m going to kill you. And all the [name] is gone. You don\'t even care, do you?',
'The right man in the wrong place can make all the difference in the [name].',
'I am the great mighty [name], and Im going to throw my shit at you.',
'Why, that\'s the second biggest [name] head I\'ve ever seen!',
'Look behind you, a three headed [name]!',
'In the year 200x a super robot named [name] was created.',
'[name] has been kidnapped by ninjas. Are you a bad enough dude to rescue the president?',
'You were almost a [name] sandwich!',
'All your [name] are belong to us.']
i = random.randrange(len(quotes))
quote = quotes[i]
x = random.randrange(len(ctx.message.server.members))
user = list(ctx.message.server.members)[x]
fquote = quote.replace('[name]', user.name)
await self.bot.say(fquote)
def timer(self, ctx):
""" Controls the channel's timer. Do '!help timer' for sub-commands.
None of the sub-commands will really work without using `setup`
first.
"""
if ctx.invoked_subcommand is None:
sect = ctx.message.content.split(' ')
if len(sect) < 2 or sect[1] is None:
log = "{} invoked an incomplete timer command."
send = "Timers are allowed here. Now what?"
else:
log = "{} invoked an invalid timer command."
send = "Invalid timer sub-command."
else:
return
lib.log(log.format(lib.get_author_name(ctx)),
channel_id=lib.get_channel_id(ctx))
await self.bot.say(send, delete_after=self.bot.ans_lifespan)
def kill(self, ctx):
"""Attempt to kill people. Has a chance of failing. Also, you may only kill one user at a time, so this command does not (and will never) have multi mention support.
**Usage:** `g_kill <user>`
**Permission:** User"""
killmsg = ["**"+ctx.message.mentions[0].display_name+"** was stabbed by **"+ctx.message.author.display_name+"**", "You tried to kill **"+ctx.message.mentions[0].display_name+"**, but you got caught by the police :<", "**"+ctx.message.mentions[0].display_name+"** disintegrated.", "While trying to kill **"+ctx.message.mentions[0].display_name+"**, **"+ctx.message.author.display_name+"** accidentally killed themselves.", "**"+ctx.message.mentions[0].display_name+"** drowned.", "Hahahaha nice try. You just tried to kill a cop. You're in jail now.", "While trying to kill **"+ctx.message.mentions[0].display_name+"**, you accidentally pinged b1nzy. Ouch.", "You pushed **"+ctx.message.mentions[0].display_name+"** into a river with crocodiles.", "You made **"+ctx.message.mentions[0].display_name+"** listen to KidzBop, so they bled out of their ears and died.", "Meh. I don't feel like helping a murder today. Try again.", "**"+ctx.message.mentions[0].display_name+"** was thrown into a pit of snakes.", "**"+ctx.message.author.display_name+"** threw **"+ctx.message.mentions[0].display_name+"** into a pit of snakes, but fell in as well.", "**"+ctx.message.mentions[0].display_name+"** was given the death sentence after **"+ctx.message.author.display_name+"** framed them for murder.", "**"+ctx.message.mentions[0].display_name+"** was forced to use Kotlin by **"+ctx.message.author.display_name+"**, so they died.", "**"+ctx.message.author.display_name+"** tried to kill someone, but found their way into Mantaro Hub and gave into the memes.", "**"+ctx.message.mentions[0].display_name+"** was killed by a sentient robot... Why are you looking at me? I didn't do it...", "**"+ctx.message.author.display_name+"** tried to kill someone and got away from the police. However, the FBI jailed them.", "You don't have a weapon. Oops. Was I supposed to bring it? I think I was...", "When **"+ctx.message.author.display_name+"** tried to kill **"+ctx.message.mentions[0].display_name+"**, they were disappointed to find they were already dead.", "**"+ctx.message.mentions[0].display_name+"** took an arrow to the knee! Well, actually it was a gunshot. And it was actually to the heart."]
var = int(random.random() * len(killmsg))
if len(ctx.message.mentions) == 0:
await ctx.send(":x: You must mention a user!")
elif len(ctx.message.mentions) > 0:
if ctx.message.mentions[0].id == ctx.message.author.id:
await ctx.send("Don't kill yourself! I love you!")
elif ctx.message.mentions[0].id == ctx.message.guild.me.id:
await ctx.send("You tried to kill me, but you realised I'm a bot. So I killed you instead.")
else:
await ctx.send(killmsg[var])
else:
await ctx.send("An unexpected error occurred. Please report this to Desiree#3658 on the support guild, link found in g!about.") # just in case. You never know shrug
def __init__(self, bot):
self.bot = bot
#self.loop = AbstractEventLoop.run_in_executor()
"""def get_cards(self):
#You can change for fitting your language deDE, enUS, esES, esMX,
#frFR, itIT, jaJP, koKR, plPL, ptBR, ruRU, thTH, zhCN, zhTW
response = requests.get('https://api.hearthstonejson.com/v1/12574/enUS/cards.collectible.json')#, 'https://api.hearthstonejson.com/v1/13619/enUS/cards.collectible.json', 'https://api.hearthstonejson.com/v1/15181/enUS/cards.collectible.json', 'https://api.hearthstonejson.com/v1/15300/enUS/cards.collectible.json')#
data = response.json()
return data
@commands.command()
async def hearthcard(self, args):
data = get_cards()
cardname = data['"name": 'args]
attack = data['"attack": ']
if data["type": "MINION"] == True:
await self.bot.say('**{0}** \n' +
"""
def concern(self, ctx):
"""MEMES?"""
await ctx.send("https://i.imgur.com/cWXBb5g.png")
## Ill finish this later
## @commands.cooldown(rate=1, per=10.0, type=commands.BucketType.channel)
## @commands.command()
## async def dongroder(self, ctx, variant=""):
## """MEMES?!?
## This meme has multiple variants : piter, swotch.
## If no variant is specified, it will defautlt to piter."""
## if variant == "piter":
## await ctx.send(
## "I'm so sorry, I was a fucking retard for saying words that would get me in touble and anger lots of people who are transgender or who are dating a transgender person. " +
## "I didn't think before I spoke a word so it just came out as something totally wrong, I don't hate anybody who is transgender, just the community. I like Aurora, just not the trans community. I'm sorry for all of this. All I'm asking for is a apology is all. I should have been thinking before I spoke."
## )
## elif variant == "swotch":
## await ctx.send(
## "I'm so sorry, I was a fucking retard for saying words that would get me in touble and anger lots of people who are bees or who are dating a bee. I didn't think before I spoke a word so it just came out as something totally wrong, I don't hate anybody who is a bee, just the hive. " +
## "I like bees, just not the beehive. I'm sorry for all of this. All I'm asking for is a apology is all. I should have been thinking before I spoke."
## )
def clear(self, ctx: commands.Context, number: int, member: discord.Member = None) -> None:
"""
Purges messages from the channel
:param ctx: The message context
:param number: The number of messages to purge
:param member: The member whose messages will be cleared
"""
if number < 1:
await command_error(ctx, "You must attempt to purge at least 1 message!")
return
def predicate(msg: discord.Message) -> bool:
return msg == ctx.message or member is None or msg.author == member
if number <= 100:
# Add 1 to limit to include command message, subtract 1 from the return to not count it.
msgs = await self.bot.purge_from(ctx.message.channel, limit=number + 1, check=predicate)
send(self.bot, '{} message{} cleared.'.format(len(msgs) - 1, "s" if len(msgs) - 1 != 1 else ""),
ctx.message.channel, True)
else:
await command_error(ctx, 'Cannot delete more than 100 messages at a time.')
def help(self, ctx, *cmds: str):
"""Help command.
* command_or_cog - The name of a command or cog.
"""
if not cmds:
commands_list = []
for command in ctx.bot.commands:
if command.hidden:
continue
try:
can_run = await command.can_run(ctx)
except Exception:
continue
if can_run:
commands_list.append(command.name)
commands_list.sort()
help_text = f'```{", ".join(commands_list)}```'
help_text += f"\nRun **help command** for more details on a command."
help_text = "**List of commands:**\n" + help_text
await ctx.send(help_text)
else:
# This is awful, haha
await ctx.bot.all_commands["old_help"].callback(ctx, *cmds)
def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
command = command.split(" ")
process = subprocess.Popen(command,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
output, errors = process.communicate(timeout=8)
output = output.split("\n")
process.terminate()
except subprocess.TimeoutExpired:
process.kill()
output = ["Command timed out. x.x"]
paginator = commands.Paginator(prefix="```bash")
for line in output:
paginator.add_line(line)
for page in paginator.pages:
await ctx.send(page)