Python discord.Role() Examples
The following are 30
code examples of discord.Role().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
discord
, or try the search function
.
Example #1
Source File: duel.py From calebj-cogs with GNU General Public License v3.0 | 6 votes |
def protect_common(self, obj, protect=True): if not isinstance(obj, (discord.Member, discord.Role)): raise TypeError('Can only pass member or role objects.') server = obj.server id = ('r' if type(obj) is discord.Role else '') + obj.id protected = self.duelists.get(server.id, {}).get("protected", []) if protect == (id in protected): return False elif protect: protected.append(id) else: protected.remove(id) if server.id not in self.duelists: self.duelists[server.id] = {} self.duelists[server.id]['protected'] = protected dataIO.save_json(JSON_PATH, self.duelists) return True
Example #2
Source File: emote_role_toggle.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
def user_has_role(role, user_roles): """ Checks if a user has a specific role. :param role: The role to check. :type role: discord.Role :param user_roles: A list of the user's roles. :type user_roles: list[discord.Role] :return: :rtype: bool """ has = False for user_role in user_roles: if user_role.id == role.id: has = True break return has
Example #3
Source File: roles.py From NabBot with Apache License 2.0 | 6 votes |
def autorole_list(self, ctx: NabCtx): """Shows a list of autorole rules.""" rules = await ctx.pool.fetch("SELECT role_id, rule FROM role_auto WHERE server_id = $1", ctx.guild.id) if not rules: return await ctx.error("This server has no autorole rules.") entries = [] for role_id, guild in rules: role: discord.Role = discord.utils.get(ctx.guild.roles, id=role_id) if role is None: continue entries.append(f"{role.mention} — `{guild}`") if not entries: return await ctx.error("This server has no autorole rules.") per_page = 20 if await ctx.is_long() else 5 pages = Pages(ctx, entries=entries, per_page=per_page) pages.embed.title = "Autorole rules" try: await pages.paginate() except errors.CannotPaginate as e: await ctx.error(e)
Example #4
Source File: fetch.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
def make_overwrite_data(prms): """ Makes a data dict for storage for a permission overwrite. :param prms: The permissions to process. :type prms: dict :return: """ data = [] for entry in prms: prm = prms[entry] allow, deny = prm.pair() edat = { "deny": deny.value, "id": str(entry.id), "type": 'role' if isinstance(entry, discord.Role) else 'member' } data.append(edat) return data
Example #5
Source File: gameroles.py From FlameCogs with MIT License | 6 votes |
def delactivity(self, ctx, role: discord.Role, activity: str): """ Remove an activity from triggering a role. Roles and activities with multiple words need to be surrounded in quotes. You can get the name of your current activity with [p]gameroles currentactivity. """ roledict = await self.config.guild(ctx.guild).roledict() rid = str(role.id) if rid not in roledict: return await ctx.send(f'`{role.name}` is not managed by gameroles.') if activity not in roledict[rid]: return await ctx.send(f'`{activity}` does not trigger `{role.name}`.') roledict[rid].remove(activity) await self.config.guild(ctx.guild).roledict.set(roledict) await ctx.send(f'`{role.name}` is no longer triggered by `{activity}`!') if ctx.guild.id in self.cache: del self.cache[ctx.guild.id]
Example #6
Source File: gameroles.py From FlameCogs with MIT License | 6 votes |
def listactivities(self, ctx, role: discord.Role): """ List the activities that trigger a role. Roles with multiple words need to be surrounded in quotes. """ roledict = await self.config.guild(ctx.guild).roledict() rid = str(role.id) if rid not in roledict: return await ctx.send(f'`{role.name}` is not managed by gameroles.') if roledict[rid] == []: return await ctx.send(f'`{role.name}` currently has no activities that trigger it.') activities = '\n'.join(roledict[rid]) await ctx.send( f'Activities that currently trigger `{role.name}`:\n' f'```\n{activities}```' )
Example #7
Source File: fetch.py From apex-sigma-core with GNU General Public License v3.0 | 6 votes |
def make_role_data(rol): """ Makes a data dict for storage for a role. :param rol: The role to store. :type rol: discord.Role :rtype: dict """ data = { "hoist": rol.hoist, "name": rol.name, "mentionable": rol.mentionable, "color": rol.color.value, "position": rol.position, "id": str(rol.id), "managed": rol.managed, "permissions": rol.permissions.value } return data
Example #8
Source File: roles.py From NabBot with Apache License 2.0 | 6 votes |
def on_guild_role_delete(self, role: discord.Role): """Called when a role is deleted. Removes joinable groups from the database when the role is deleted. """ async with self.bot.pool.acquire() as conn: joinable_result = await conn.execute("DELETE FROM role_joinable WHERE role_id = $1", role.id) auto_result = await conn.execute("DELETE FROM role_auto WHERE role_id = $1", role.id) deleted_joinable = get_affected_count(joinable_result) deleted_auto = get_affected_count(auto_result) if deleted_auto: self.bot.dispatch("role_auto_deleted", role) if deleted_joinable: self.bot.dispatch("role_joinable_deleted", role) # endregion # region Custom Events # Todo: Requires optimization
Example #9
Source File: __init__.py From seasonalbot with MIT License | 6 votes |
def unlocked_role(role: discord.Role, delay: int = 5) -> None: """ Create a context in which `role` is unlocked, relocking it automatically after use. A configurable `delay` is added before yielding the context and directly after exiting the context to allow the role settings change to properly propagate at Discord's end. This prevents things like role mentions from failing because of synchronization issues. Usage: >>> async with unlocked_role(role, delay=5): ... await ctx.send(f"Hey {role.mention}, free pings for everyone!") """ await role.edit(mentionable=True) await asyncio.sleep(delay) try: yield finally: await asyncio.sleep(delay) await role.edit(mentionable=False)
Example #10
Source File: giveaway.py From graham_discord_bot with MIT License | 6 votes |
def role_check(self, msg: discord.Message) -> bool: "Return true if user can participate in giveaways, false otherwise" giveaway_roles = config.Config.instance().get_giveaway_roles() if len(giveaway_roles) == 0: return True # not configured to be restrictive can_participate = False for role in msg.author.roles: if role.id in giveaway_roles: can_participate = True break if not can_participate: role_names = [] for role_id in giveaway_roles: role: discord.Role = msg.guild.get_role(role_id) if role is not None: role_names.append(role.name) resp_str = "" for idx, name in enumerate(role_names): resp_str += name if idx != len(role_names) - 1: resp_str += ", " await Messages.add_x_reaction(msg) await Messages.send_error_dm(msg.author, f"Sorry, only users with the following roles can participate in giveaways: {resp_str}") return False return True
Example #11
Source File: cog.py From bot with MIT License | 6 votes |
def on_guild_role_update(self, before: Role, after: Role) -> None: """Syncs role with the database if any of the stored attributes were updated.""" if after.guild.id != constants.Guild.id: return was_updated = ( before.name != after.name or before.colour != after.colour or before.permissions != after.permissions or before.position != after.position ) if was_updated: await self.bot.api_client.put( f'bot/roles/{after.id}', json={ 'colour': after.colour.value, 'id': after.id, 'name': after.name, 'permissions': after.permissions.value, 'position': after.position, } )
Example #12
Source File: gameroles.py From FlameCogs with MIT License | 6 votes |
def addactivity(self, ctx, role: discord.Role, activity: str): """ Add an activity to trigger a role. Roles and activities with multiple words need to be surrounded in quotes. You can get the name of your current activity with [p]gameroles currentactivity. """ roledict = await self.config.guild(ctx.guild).roledict() rid = str(role.id) if rid not in roledict: return await ctx.send(f'`{role.name}` is not managed by gameroles.') if activity in roledict[rid]: return await ctx.send(f'`{activity}` already triggers `{role.name}`.') roledict[rid].append(activity) await self.config.guild(ctx.guild).roledict.set(roledict) await ctx.send(f'`{role.name}` is now triggered by `{activity}`!') if ctx.guild.id in self.cache: del self.cache[ctx.guild.id]
Example #13
Source File: salary.py From RPGBot with GNU General Public License v3.0 | 6 votes |
def create(self, ctx, role: discord.Role, interval: NumberConverter, *items_or_number: data.ItemOrNumber): """Create a daily salary for a user with the given role. The time interval is the interval which must pass before the user may collect the salary again, in seconds. If a role with a salary is deleted, the salary will also be deleted. For example `rp!salary create @Bot Creator 3600 500` Will create a salary of $500 for a user hourly `rp!salary create @Bot Creator 86400 Bananax3 Orangex4` Will create a salary of 3 Bananas and 4 Oranges for a user daily Requires Bot Moderator or Bot Admin """ if not items_or_number: await ctx.send(await _(ctx, "Missing argument, see rp!help salary create")) return sals = await self.bot.di.get_salaries(ctx.guild) if len(items_or_number) == 1 and isinstance(items_or_number[0], int): items_or_number = items_or_number[0] sals[role.id] = {'int': interval, 'val': items_or_number} await self.bot.di.update_salaries(ctx.guild, sals) await ctx.send((await _(ctx, "Successfully created a daily salary of {} for {}")).format(items_or_number, role))
Example #14
Source File: roles.py From NabBot with Apache License 2.0 | 6 votes |
def autorole_remove(self, ctx: NabCtx, role: InsensitiveRole, *, guild: str): """Removes an autorole rule. Role names, mentions and ids are accepted. Role names with multiple words need to be quoted. Note that members that currently have the role won't be affected.""" group: discord.Role = role guild = guild.replace("\"", "") exists = await ctx.pool.fetchval("SELECT true FROM role_auto WHERE role_id = $1 AND lower(rule) = $2", group.id, guild.lower()) if not exists: await ctx.error("That rule doesn't exist.") return # Can't modify role higher than the owner's top role top_role: discord.Role = ctx.author.top_role if group >= top_role: await ctx.error("You can't delete a role rule for a role higher than yours.") return await ctx.success(f"Auto role rule removed. Note that the role won't be removed from current members.") await ctx.pool.execute("DELETE FROM role_auto WHERE role_id = $1 AND lower(rule) = $2", group.id, guild.lower())
Example #15
Source File: punish.py From calebj-cogs with GNU General Public License v3.0 | 6 votes |
def _role_from_string(server, rolename, roles=None): if roles is None: roles = server.roles else: roles = [r for r in roles if isinstance(r, discord.Role)] if rolename.isdigit(): role = discord.utils.get(roles, id=rolename) if role: log.debug("Role {} found from ID {}".format(role.name, rolename)) return role rolename = rolename.lower() role = discord.utils.find(lambda r: r.name.lower() == rolename, roles) try: log.debug("Role {} found from rolename {}".format(role.name, rolename)) except Exception: log.debug("Role not found for rolename {}".format(rolename)) return role
Example #16
Source File: activitylog.py From calebj-cogs with GNU General Public License v3.0 | 6 votes |
def format_overwrite(target, channel, before, after): target_str = 'Channel overwrites: {0.name} ({0.id}): '.format(channel) target_str += 'role' if isinstance(target, discord.Role) else 'member' target_str += ' {0.name} ({0.id})'.format(target) if before: bpair = [x.value for x in before.pair()] if after: apair = [x.value for x in after.pair()] if before and after: fmt = ' updated to values %i, %i (was %i, %i)' return target_str + fmt % tuple(apair + bpair) elif after: return target_str + ' added with values %i, %i' % tuple(apair) elif before: return target_str + ' removed (was %i, %i)' % tuple(bpair)
Example #17
Source File: buyrole.py From refactored-cogs with Mozilla Public License 2.0 | 6 votes |
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
Example #18
Source File: buyrole.py From refactored-cogs with Mozilla Public License 2.0 | 6 votes |
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))
Example #19
Source File: activity.py From Trusty-cogs-archive with MIT License | 6 votes |
def add_server(self, ctx, channel:discord.Channel=None, role:discord.Role=None, invite_link=None): """Set the server for activity checking""" server = ctx.message.server if channel is None: channel = ctx.message.channel if role is not None: role = role.id if role is None: role = await self.get_everyone_role(server) if server.id in self.log: await self.bot.say("This server is already checking for activity!") return if invite_link is None: await self.bot.say("You'll need to supply an invite link if you want one for members to rejoin") self.settings[server.id] = {"channel": channel.id, "check_roles": [role], "time": 604800, "invite": True, "link": invite_link, "rip_count": 0} dataIO.save_json(self.settings_file, self.settings) await self.build_list(ctx, server) await self.bot.send_message(ctx.message.channel, "Sending activity check messages to {}".format(channel.mention))
Example #20
Source File: activity.py From Trusty-cogs-archive with MIT License | 6 votes |
def role_ignore(self, ctx, role:discord.Role): """Add or remove a role to be checked. Remove all roles to check everyone.""" server = ctx.message.server server_roles = self.settings[server.id]["check_roles"] channel = ctx.message.channel added_role = False everyone_role = await self.get_everyone_role(server) if role.id in server_roles: self.settings[server.id]["check_roles"].remove(role.id) await self.bot.send_message(channel, "Now ignoring {}!".format(role.name)) added_role = True if role.id not in server_roles and not added_role: self.settings[server.id]["check_roles"].append(role.id) await self.bot.send_message(channel, "Now checking {}!".format(role.name)) if len(server_roles) < 1: self.settings[server.id]["check_roles"].append(everyone_role) await self.bot.send_message(channel, "Now checking everyone!") if len(server_roles) > 1 and everyone_role in server_roles: self.settings[server.id]["check_roles"].remove(everyone_role) dataIO.save_json(self.settings_file, self.settings)
Example #21
Source File: star.py From Trusty-cogs-archive with MIT License | 6 votes |
def add_role(self, ctx, role:discord.Role=None): """Add a role allowed to add messages to the starboard defaults to @everyone""" server = ctx.message.server if server.id not in self.settings: await self.bot.send_message(ctx.message.channel, "I am not setup for the starboard on this server!\ \nuse starboard set to set it up.") return everyone_role = await self.get_everyone_role(server) if role is None: role = everyone_role if role.id in self.settings[server.id]["role"]: await self.bot.send_message(ctx.message.channel, "{} can already add to the starboard!".format(role.name)) return if everyone_role.id in self.settings[server.id]["role"] and role != everyone_role: self.settings[server.id]["role"].remove(everyone_role.id) self.settings[server.id]["role"].append(role.id) dataIO.save_json("data/star/settings.json", self.settings) await self.bot.send_message(ctx.message.channel, "Starboard role set to {}.".format(role.name))
Example #22
Source File: star.py From Trusty-cogs-archive with MIT License | 6 votes |
def setup_starboard(self, ctx, channel: discord.Channel=None, emoji="⭐", role:discord.Role=None): """Sets the starboard channel, emoji and role""" server = ctx.message.server if channel is None: channel = ctx.message.channel if "<" in emoji and ">" in emoji: emoji = await self.check_server_emojis(server, emoji) if emoji is None: await self.bot.send_message(ctx.message.channel, "That emoji is not on this server!") return else: emoji = ":" + emoji.name + ":" + emoji.id if role is None: role = await self.get_everyone_role(server) self.settings[server.id] = {"emoji": emoji, "channel": channel.id, "role": [role.id], "threshold": 0, "messages": [], "ignore": []} dataIO.save_json("data/star/settings.json", self.settings) await self.bot.say("Starboard set to {}".format(channel.mention))
Example #23
Source File: gameroles.py From FlameCogs with MIT License | 6 votes |
def addrole(self, ctx, role: discord.Role): """ Sets a role to be managed by gameroles. Roles with multiple words need to be surrounded in quotes. The bot's highest role needs to be above the role that you are adding and the bot needs permission to manage roles. """ roledict = await self.config.guild(ctx.guild).roledict() rid = str(role.id) if rid in roledict: return await ctx.send( f'`{role.name}` is already managed by gameroles. ' f'Use `{ctx.prefix}gameroles addactivity` to add activities.' ) roledict[role.id] = [] await self.config.guild(ctx.guild).roledict.set(roledict) await ctx.send( f'`{role.name}` is now managed by gameroles! ' f'Use `{ctx.prefix}gameroles addactivity` to add activities.' ) if ctx.guild.id in self.cache: del self.cache[ctx.guild.id]
Example #24
Source File: gameroles.py From FlameCogs with MIT License | 6 votes |
def delrole(self, ctx, role: Union[discord.Role, int]): """ Stop a role from being managed by gameroles. Roles with multiple words need to be surrounded in quotes. Accepts the ID of the role in case it was deleted. """ roledict = await self.config.guild(ctx.guild).roledict() if isinstance(role, discord.Role): rid = str(role.id) name = role.name else: rid = str(role) name = rid if rid not in roledict: return await ctx.send(f'`{name}` is not managed by gameroles.') del roledict[rid] await self.config.guild(ctx.guild).roledict.set(roledict) await ctx.send(f'`{name}` is no longer managed by gameroles!') if ctx.guild.id in self.cache: del self.cache[ctx.guild.id]
Example #25
Source File: captcha.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def role(self) -> Optional[discord.Role]: server = self.cog.bot.get_server(self.server_id) if server: return discord.utils.get(server.roles, id=self.role_id) else: return None
Example #26
Source File: captcha.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def captchaset_role_mode(self, ctx, role_mode: str = None): """ Show/set role mode role_mode must be verified, unverified, or left blank to show the current setting """ server = ctx.message.server settings = self.settings.get(server.id) extra = None if role_mode: if role_mode.lower().startswith('unverified'): role_mode = False elif role_mode.lower().startswith('verified'): role_mode = True else: await self.bot.send_cmd_help(ctx) if (role_mode is not None) and not settings: self.settings[server.id] = settings = ServerConfig(self, server.id, role_mode=role_mode) extra = "\n\nNote that Captcha hasn't been enabled yet; run `%scaptchaset enabled yes`." % ctx.prefix adj = 'now' self.save() elif role_mode is None: role_mode = settings.role_mode adj = 'currently' elif settings.role_mode == role_mode: adj = 'already' else: adj = 'now' settings.role_mode = role_mode self.save() desc = 'verified' if role_mode else 'unverified' await self.bot.say('Role mode is %s set to %s.%s' % (adj, desc, extra or ''))
Example #27
Source File: captcha.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def captchaset_role(self, ctx, role: discord.Role = None): """ Sets or displays the current un/verified role. """ server = ctx.message.server settings = self.settings.get(server.id) extra = None if role and role >= server.me.top_role: await self.bot.say(warning("That role is too high for me to manage.")) return if role and not settings: self.settings[server.id] = settings = ServerConfig(self, server.id, role_id=role.id) adj = 'now' extra = "Note that Captcha hasn't been enabled yet; run `%scaptchaset enabled yes`." % ctx.prefix self.save() elif role is None: role = settings and settings.role adj = 'currently' elif settings.role == role: adj = 'already' else: adj = 'now' settings.role = role self.save() desc = (role.name if role.mentionable else role.mention) if role else 'not set' role_type = 'Verified' if settings.role_mode else 'Unverified' msg = '%s role is %s %s.' % (role_type, adj, desc) if extra: msg += '\n\n' + extra await self.bot.say(msg)
Example #28
Source File: captcha.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def __init__(self, cog, server_id, **data): self.cog = cog self.server_id = server_id self._handles = {} # prevents duplicate challenges from races in role add/remove self._pending_ids = set() # Generated challenge length self.challenge_length = data.get('challenge_length', 8) # Captcha generator (plain, image, or wheezy) self.challenge_type = ChallengeType(data.get('challenge_type', ChallengeType.WHEEZY)) # ID of channel for posting challenges/responses self.channel_id = data.get('channel_id') # Whether the cog is enabled in a server self.enabled = data.get('enabled', False) # How long to wait for reply before kicking (0 = none) self.kick_timeout = data.get('kick_timeout', 5 * 60) # dict of UID : challenge data self.pending = data.get('pending', {}) # The retry cooldown time for image-based captchas self.retry_cooldown = data.get('retry_cooldown', 60) # ID of dis/approval role self.role_id = data.get('role_id') # Role means approval? If false, disapproval. self.role_mode = data.get('role_mode', True) # Send challenge via DM? self.use_dm = data.get('use_dm', False) # Send challenge on member join? self.on_join = data.get('on_join', True) # Send challenge on role add/remove self.on_role = data.get('on_role', True)
Example #29
Source File: duel.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def _protect_role(self, ctx, role: discord.Role): """Adds a role to the protection list""" if self.protect_common(role, True): await self.bot.say("The %s role has been successfully added to the protection list." % role.name) else: await self.bot.say("The %s role is already in the protection list." % role.name)
Example #30
Source File: duel.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def _unprotect_role(self, ctx, role: discord.Role): """Removes a role from the duel protection list""" if self.protect_common(role, False): await self.bot.say("The %s role has been successfully removed from the protection list." % role.name) else: await self.bot.say("The %s role is not in the protection list." % role.name)