def is_admin_or_superior(self, obj):
if isinstance(obj, discord.Message):
user = obj.author
elif isinstance(obj, discord.Member):
user = obj
elif isinstance(obj, discord.Role):
pass
else:
raise TypeError('Only messages, members or roles may be passed')
server = obj.server
admin_role = settings.get_server_admin(server)
if isinstance(obj, discord.Role):
return obj.name == admin_role
if user.id == settings.owner:
return True
elif discord.utils.get(user.roles, name=admin_role):
return True
else:
return False
python类Role()的实例源码
def is_mod_or_superior(self, obj):
if isinstance(obj, discord.Message):
user = obj.author
elif isinstance(obj, discord.Member):
user = obj
elif isinstance(obj, discord.Role):
pass
else:
raise TypeError('Only messages, members or roles may be passed')
server = obj.server
admin_role = settings.get_server_admin(server)
mod_role = settings.get_server_mod(server)
if isinstance(obj, discord.Role):
return obj.name in [admin_role, mod_role]
if user.id == settings.owner:
return True
elif discord.utils.get(user.roles, name=admin_role):
return True
elif discord.utils.get(user.roles, name=mod_role):
return True
else:
return False
def uniquegroup(self, ctx, role: discord.Role, groupid: int):
"""Set a role to a unique group ID,
This means that a user cannot have more then one role from the same group.
Any role sharing the same ID will be considered a group.
GroupID 0 will not be considered unique and can share other roles."""
server = ctx.message.server
if role.id not in self.settings_dict[server.id]['roles']:
await self.bot.say('This role ins\'t in the buyrole list')
elif groupid < 0:
await self.bot.say('The group ID cannot be negative.')
else:
# Set the uniquegroup ID here, logic will remain in a subfunction of buyrole
self.settings_dict[server.id]['roles'][role.id]['uniquegroup'] = groupid
self.save_json()
if groupid == 0:
await self.bot.say('Unique Group ID set. {} isn\'t considered unique.'.format(role.name))
else:
await self.bot.say('Unique Group ID set. {} will now be unique in group ID {}'.format(role.name, groupid))
def _create_list(self, server): # A credit to calebj#7377 for helping me out here.
"""Creates the role list for a server"""
if 'colour' not in self.settings_dict[server.id]: # Backwards compatibility. *Sigh*
colour = 0x72198b
else:
colour = self.settings_dict[server.id]['colour']
embed = discord.Embed(description='**Role list:**', colour=colour)
for roleid, roledata in self.settings_dict[server.id]['roles'].items():
role = discord.utils.get(server.roles, id=roleid)
if not role:
continue
if roledata['uniquegroup'] > 0:
embed.add_field(name='%s (Unique, ID #%s)' % (role.name, roledata['uniquegroup']), value=self._price_string(roledata['price'], True))
else:
embed.add_field(name=role.name, value=self._price_string(roledata['price'], True))
return embed
def roleinfo(self, ctx, *, role: discord.Role):
"""Displays information about a role."""
rd = InfoBuilder([
('Name', role.name),
('ID', role.id),
('Members', sum(1 for member in role.guild.members if role in member.roles)),
('Created', role.created_at),
('Managed', role.managed),
('Position', role.position),
('Permissions', role.permissions.value),
('Color', "#{:06x}".format(role.color.value)),
('Hoist', role.hoist),
('Mentionable', role.mentionable)
])
await ctx.send(rd.code_block())
def add_(self, ctx, role: Role):
"""
Adds a role.
Available Roles List:
- ping
- battlenet
If the argument given is not a valid role in the guild, it will safely ignore it.
If the argument is a valid role in the guild and is not in the available roles list, it will flag it as invalid.
"""
whitelisted_roles = [
utils.get(ctx.guild.roles, name="ping"),
utils.get(ctx.guild.roles, name="battlenet")
]
if role in whitelisted_roles:
await ctx.author.add_roles(role, reason="Used role command")
await ctx.send(f"Added `{role}` to {ctx.author.mention}.")
else:
await ctx.send(
f"""
`{role}` is not a valid role!
Do `{ctx.prefix}help role add` for more information. {ctx.author.mention}
"""
)
def remove_(self, ctx, role: Role):
"""
Removes a role.
Available Roles List:
- ping
- battlenet
If the argument given is not a valid role in the guild, it will safely ignore it.
If the argument is a valid role in the guild and is not in the available roles list, it will flag it as invalid.
"""
whitelisted_roles = [
utils.get(ctx.guild.roles, name="ping"),
utils.get(ctx.guild.roles, name="battlenet")
]
if role in whitelisted_roles:
await ctx.author.remove_roles(role, reason="Used role command")
await ctx.send(f"Removed `{role}` from {ctx.author.mention}.")
else:
await ctx.send(
f"""
`{role}` is not a valid role!
Do `{ctx.prefix}help role remove` for more information. {ctx.author.mention}
"""
)
def uniquegroup(self, ctx, role: discord.Role, groupid: int):
"""Set a role to a unique group ID,
This means that a user cannot have more then one role from the same group.
Any role sharing the same ID will be considered a group.
GroupID 0 will not be considered unique and can share other roles."""
server = ctx.message.server
if role.id not in self.settings_dict[server.id]['roles']:
await self.bot.say('This role ins\'t in the buyrole list')
elif groupid < 0:
await self.bot.say('The group ID cannot be negative.')
else:
# Set the uniquegroup ID here, logic will remain in a subfunction of buyrole
self.settings_dict[server.id]['roles'][role.id]['uniquegroup'] = groupid
self.save_json()
if groupid == 0:
await self.bot.say('Unique Group ID set. {} isn\'t considered unique.'.format(role.name))
else:
await self.bot.say('Unique Group ID set. {} will now be unique in group ID {}'.format(role.name, groupid))
def _create_list(self, server): # A credit to calebj#7377 for helping me out here.
"""Creates the role list for a server"""
if 'colour' not in self.settings_dict[server.id]: # Backwards compatibility. *Sigh*
colour = 0x72198b
else:
colour = self.settings_dict[server.id]['colour']
embed = discord.Embed(description='**Role list:**', colour=colour)
for roleid, roledata in self.settings_dict[server.id]['roles'].items():
role = discord.utils.get(server.roles, id=roleid)
if not role:
continue
if roledata['uniquegroup'] > 0:
embed.add_field(name='%s (Unique, ID #%s)' % (role.name, roledata['uniquegroup']), value=self._price_string(roledata['price'], True))
else:
embed.add_field(name=role.name, value=self._price_string(roledata['price'], True))
return embed
def _mdm(self, ctx: commands.Context,
role: discord.Role, *, message: str):
"""Sends a DM to all Members with the given Role.
Allows for the following customizations:
{0} is the member being messaged.
{1} is the role they are being message through.
{2} is the person sending the message.
"""
server = ctx.message.server
sender = ctx.message.author
try:
await self.bot.delete_message(ctx.message)
except:
pass
dm_these = self._get_users_with_role(server, role)
for user in dm_these:
try:
await self.bot.send_message(user,
message.format(user, role, sender))
except (discord.Forbidden, discord.HTTPException):
continue
def _status_lottery(self, ctx):
"""Check if a lottery is active"""
author = ctx.message.author
settings = self.check_server_settings(author.server)
if settings["Config"]["Active"]:
ld = settings["Config"]["Current Loadout"]
timer = settings["Loadouts"][ld]["Timer"]
if timer == 0:
remaining = "no time limit"
else:
counter = settings["Config"]["Tracker"]
seconds = timer - (datetime.utcnow() - parser.parse(counter)).seconds
remaining = "{} remaining".format(self.time_formatter(seconds))
winners = settings["Loadouts"][ld]["Winners"]
entry_limit = settings["Loadouts"][ld]["Limit"]
dos = settings["Loadouts"][ld]["DOS"]
role_req = settings["Loadouts"][ld]["Role"]
prize = settings["Loadouts"][ld]["Prize"]
footer = "There are currently {} users in the lottery.".format(len(settings["Players"]))
if author.id in settings["Players"]:
desc = "You are currently in the lottery."
else:
desc = "You have **not** entered into this lottery yet."
embed = discord.Embed(title="Loadout {}".format(ld), description=desc, color=0x50bdfe)
embed.set_author(name="Lottery System 3.0")
embed.add_field(name="Prize", value=prize, inline=True)
embed.add_field(name="Possible Winners", value=winners, inline=True)
embed.add_field(name="Role", value=role_req, inline=True)
embed.add_field(name="Limit", value=entry_limit, inline=True)
embed.add_field(name="Time Remaining", value=remaining, inline=True)
embed.add_field(name="Days on Server Required", value=dos, inline=True)
embed.set_footer(text=footer)
await self.bot.say(embed=embed)
else:
await self.bot.say("There aren't any lotteries running on this server right now.")
def _view_lottery(self, ctx, loadout: int):
"""View the parameters set for a loadout"""
if loadout not in [0, 1, 2, 3, 4, 5]:
return await self.bot.say("Invalid loadout. Must be 0-5.")
server = ctx.message.server
settings = self.check_server_settings(server)
loadout = str(loadout)
if not self.slot_checker(settings, loadout):
return await self.bot.say("The selected loadout is empty.")
timer = settings["Loadouts"][loadout]["Timer"]
if timer == 0:
time_fmt = "no time limit"
else:
time_fmt = self.time_formatter(timer)
winners = settings["Loadouts"][loadout]["Winners"]
entry_limit = settings["Loadouts"][loadout]["Limit"]
dos = settings["Loadouts"][loadout]["DOS"]
role_req = settings["Loadouts"][loadout]["Role"]
prize = settings["Loadouts"][loadout]["Prize"]
start_msg = settings["Loadouts"][loadout]["Start Message"]
end_msg = settings["Loadouts"][loadout]["End Message"]
embed = discord.Embed(title="Loadout {}".format(loadout), color=0x50bdfe)
embed.add_field(name="Prize", value=prize, inline=True)
embed.add_field(name="Number of Winners", value=winners, inline=True)
embed.add_field(name="Role", value=role_req, inline=True)
embed.add_field(name="Entry Limit", value=entry_limit, inline=True)
embed.add_field(name="Timer", value=time_fmt, inline=True)
embed.add_field(name="Days on Server Required", value=dos, inline=True)
embed.add_field(name="Start Message", value=start_msg, inline=True)
embed.add_field(name="End Message", value=end_msg, inline=True)
await self.bot.say(embed=embed)
def _addrole_shop(self, ctx, quantity: int, cost: int, role: discord.Role):
"""Add a role token to shop list. Requires buyrole from refactored cogs"""
server = ctx.message.server
settings = self.check_server_settings(server)
shop_name = settings["Config"]["Shop Name"]
if 'Buyrole' not in self.bot.cogs:
msg = ("This feature requires the buyrole cog from the Refactored Cogs repo.\n"
"Load buyrole to use this function.")
else:
self.shop_item_add(settings, role, cost, quantity, role=True)
item_count = len(settings["Shop List"])
msg = ("```{} {} have been added to {} shop.\n{} item(s) available for purchase in the "
"store.```".format(quantity, role.name, shop_name, item_count))
await self.bot.say(msg)
def _role_sethop(self, ctx, *, rolename: str):
"""Set the server role that will receive pending notifications"""
server = ctx.message.server
settings = self.check_server_settings(server)
server_roles = [x.name for x in server.roles]
if rolename in server_roles:
settings["Config"]["Shop Role"] = rolename
dataIO.save_json(self.file_path, self.system)
msg = ("Notify role set to {}. Server users assigned this role will be notifed when "
"an item is redeemed.".format(rolename))
else:
role_output = ", ".join(server_roles).replace("@everyone,", "")
msg = ("{} is not a role on your server. The current roles on your server are:\n"
"```{}```".format(rolename, role_output))
await self.bot.say(msg)
def user_add_item(self, settings, user, quantity, itemname):
user_path = settings["Users"][user.id]["Inventory"]
if itemname in settings["Users"][user.id]["Inventory"]:
user_path[itemname]["Item Quantity"] += quantity
else:
user_path[itemname] = {"Item Name": itemname, "Item Quantity": quantity}
if "Role" in settings["Shop List"][itemname]:
user_path[itemname]["Role"] = settings["Shop List"][itemname]["Role"]
dataIO.save_json(self.file_path, self.system)
def setkillrole(self, ctx, role : discord.Role = None):
"""Sets the required role ID to add/remove hacks (admin only)."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.server
# Check if we're suppressing @here and @everyone mentions
if self.settings.getServerStat(ctx.message.server, "SuppressMentions").lower() == "yes":
suppress = True
else:
suppress = False
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 role == None:
self.settings.setServerStat(server, "RequiredKillRole", "")
msg = 'Kill/resurrect now *admin-only*.'
await self.bot.send_message(channel, msg)
return
if type(role) is str:
try:
role = discord.utils.get(server.roles, name=role)
except:
print("That role does not exist")
return
# If we made it this far - then we can add it
self.settings.setServerStat(server, "RequiredKillRole", role.id)
msg = 'Role required for kill/resurrect set to **{}**.'.format(role.name)
# Check for suppress
if suppress:
msg = Nullify.clean(msg)
await self.bot.send_message(channel, msg)
def killrole(self, ctx):
"""Lists the required role to kill/resurrect the bot."""
# Check if we're suppressing @here and @everyone mentions
if self.settings.getServerStat(ctx.message.server, "SuppressMentions").lower() == "yes":
suppress = True
else:
suppress = False
role = self.settings.getServerStat(ctx.message.server, "RequiredKillRole")
if role == None or role == "":
msg = '**Only Admins** can kill/ressurect the bot.'.format(ctx)
await self.bot.say(msg)
else:
# Role is set - let's get its name
found = False
for arole in ctx.message.server.roles:
if arole.id == role:
found = True
msg = 'You need to be a/an **{}** to kill/ressurect the bot.'.format(arole.name)
if not found:
msg = 'There is no role that matches id: `{}` - consider updating this setting.'.format(role)
# Check for suppress
if suppress:
msg = Nullify.clean(msg)
await self.bot.send_message(ctx.message.channel, msg)
def add(self, ctx, name, *, role:discord.Role):
"""Adds a role to the list of giveme's, if the name contains spaces put it in quotes (").
Example:
[p]giveme add "role name" role_mention OR
[p]giveme add "role name" name of the role"""
if not ctx.message.server.me.permissions_in(ctx.message.channel).manage_roles:
await self.bot.say("I do not have the manage roles permission here, I cannot assign roles to people untill I do.")
else:
if ctx.message.server.id not in self.settings:
self.settings[ctx.message.server.id] = {'givemes': {}}
self.settings[ctx.message.server.id]['givemes'][name] = role.id
self.save_settings()
await self.bot.say("Giveme has been added.")
def autorole(self, ctx):
"""Manage autorole settings."""
if ctx.message.server.id not in self.settings:
self.settings[ctx.message.server.id] = {'role': None, 'toggled': False}
self.save_settings()
if not ctx.invoked_subcommand:
role = discord.utils.get(ctx.message.server.roles, id=self.settings[ctx.message.server.id]['role'])
if role == None:
role = "DELETED"
else:
role = role.name
await self.bot.send_cmd_help(ctx)
await self.bot.say("```Role: {}\nEnabled: {}```".format(role, self.settings[ctx.message.server.id]['toggled']))
def setrole(self, ctx, *, role:discord.Role):
"""Set the role the bot should assign on join, the highest role that the bot has should be higher than this one."""
self.settings[ctx.message.server.id]['role'] = role.id
self.save_settings()
await self.bot.say("Role has been set.")