Python discord.ext.commands.group() Examples
The following are 30
code examples of discord.ext.commands.group().
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.ext.commands
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: deck.py From SML-Cogs with MIT License | 6 votes |
def decklink_to_cards(self, url): """Convert decklink to cards.""" card_keys = None # search for Clash Royale decks m_crlink = re.search('(http|ftp|https)://link.clashroyale.com/deck/..\?deck=[\d\;]+', url) # search for royaleapi deck stats link m_rapilink = re.match('(https|http)://royaleapi.com/decks/stats/([a-z,-]+)/?', url) m_rapilink_section = re.match('(https|http)://royaleapi.com/decks/stats/([a-z,-]+)/.+', url) if m_crlink: url = m_crlink.group() decklinks = re.findall('2\d{7}', url) card_keys = [] for decklink in decklinks: card_key = await self.card_decklink_to_key(decklink) if card_key is not None: card_keys.append(card_key) elif m_rapilink and not m_rapilink_section: s = m_rapilink.group(2) card_keys = s.split(',') return card_keys
Example #2
Source File: database.py From GW2Bot with MIT License | 6 votes |
def cache_pois(self): async def bulk_write(group): requests = [] for item in group: item["_id"] = item.pop("id") requests.append( ReplaceOne({"_id": item["_id"]}, item, upsert=True)) try: await self.db.pois.bulk_write(requests) except BulkWriteError as e: self.log.exception("BWE while caching continents") continents = await self.call_api("continents/1/floors?ids=all") pois = [] for continent in continents: for region in continent["regions"].values(): for game_map in region["maps"].values(): for poi in game_map["points_of_interest"].values(): del poi["chat_link"] poi["continent_id"] = continent["id"] pois.append(poi) if len(pois) > 200: await bulk_write(pois) pois = [] print("Continents done")
Example #3
Source File: logstash.py From SML-Cogs with MIT License | 6 votes |
def get_channel_params(self, channel: Channel): """Return extra fields for channel.""" extra = { 'id': channel.id, 'name': channel.name, 'server': self.get_server_params(channel.server), 'position': channel.position, 'is_default': channel.is_default, 'created_at': channel.created_at.isoformat(), 'type': { 'text': channel.type == ChannelType.text, 'voice': channel.type == ChannelType.voice, 'private': channel.type == ChannelType.private, 'group': channel.type == ChannelType.group } } return extra
Example #4
Source File: draftroyale.py From SML-Cogs with MIT License | 6 votes |
def draftutil_cards(self, ctx): """List available cards by emojis.""" emojis = [v["emoji"] for k, v in self.crdata["Cards"].items()] groups = grouper(emojis, 25) for group in groups: out = [] for emoji in group: if emoji is not None: out.append('<:{}:{}>'.format(emoji, self.emojis[emoji])) await self.bot.say(' '.join(out)) # out = [] # for emoji in emojis: # if emoji is not None: # out.append('<:{}:{}>'.format(emoji, self.emojis[emoji])) # em = discord.Embed() # em.add_field(name="", value="".join(out)) # await self.bot.say(embed=em)
Example #5
Source File: homebrew.py From avrae with GNU General Public License v3.0 | 6 votes |
def tome_sub(self, ctx, url): """Subscribes to another user's tome.""" tome_id_match = re.search(r"homebrew/spells/([0-9a-f]{24})/?", url) if not tome_id_match: return await ctx.send("Invalid tome URL.") try: tome = await Tome.from_id(ctx, tome_id_match.group(1)) except NoActiveBrew: return await ctx.send("Pack not found.") if not tome.public: return await ctx.send("This tome is not public.") await tome.subscribe(ctx) await ctx.send(f"Subscribed to {tome.name}. " # by {tome.owner['username']}. " # todo f"Use `{ctx.prefix}tome {tome.name}` to select it.")
Example #6
Source File: loot.py From NabBot with Apache License 2.0 | 6 votes |
def loot_show(self, ctx, *, item: str): """Shows item info from loot database.""" result, item_list = await self.item_show(item) if not item_list: return await ctx.error("There's no item with that name.") item = item_list[0] embed = discord.Embed(title=item["name"], description=f"Group: {item['group']}", colour=discord.Colour.from_rgb(item["red"], item["green"], item["blue"])) content = "" for item in item_list: content += "ID: {id} | Size: {sizeX}x{sizeY} | {size}px | rgb: {red},{green},{blue} | " \ "sell: {value_sell:,} | buy: {value_buy:,}\n".format(**item) fields = split_message(content, FIELD_VALUE_LIMIT) name = "Frame info" for i, field in enumerate(fields[:5]): if i: name = "\u200F" embed.add_field(name=name, value=field, inline=False) if len(fields) > 5: embed.set_footer(text="Too many frames to display all information.") embed.set_image(url="attachment://results.png") await ctx.send(embed=embed, file=discord.File(io.BytesIO(result), "results.png"))
Example #7
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 #8
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 #9
Source File: clashroyale.py From RemixBot with MIT License | 5 votes |
def crmembers(self, ctx): '''A command group that finds the worst and best members in a clan''' await ctx.send(f'Proper usage: `{ctx.prefix}members <best | worst> <clan_tag>`')
Example #10
Source File: utility.py From RemixBot with MIT License | 5 votes |
def math(self, ctx): '''A command group for math commands''' await ctx.send('Available commands:\n`add <a> <b>`\n`subtract <a> <b>`\n`multiply <a> <b>`\n`divide <a> <b>`\n`remainder <a> <b>`\n`power <a> <b>`\n`factorial <a>`')
Example #11
Source File: log.py From Discord-SelfBot with MIT License | 5 votes |
def log(self, ctx): """Command group for managing logging.""" if ctx.invoked_subcommand is None: await edit(ctx, content='\N{HEAVY EXCLAMATION MARK SYMBOL} ``on``, ``off``, ``status``, ``show``, ``key <word>``, ``guild``, ``channel``, ``blacklist channel``, ``blacklist <word>`` or ``blacklist user <user>``', ttl=5) # Log On
Example #12
Source File: adventure.py From Dumb-Cogs with MIT License | 5 votes |
def add_synonym(self, other): """Every word in a group of synonyms shares the same list.""" self.synonyms.extend(other.synonyms) other.synonyms = self.synonyms
Example #13
Source File: roles.py From NabBot with Apache License 2.0 | 5 votes |
def group(self, ctx: NabCtx, *, _group: InsensitiveRole): """Joins or leaves a group (role). If you're not in the group, you will be added. If you're already in the group, you will be removed. To see a list of joinable groups, use `group list`""" group: discord.Role = _group exists = await ctx.pool.fetchval("SELECT true FROM role_joinable WHERE role_id = $1", group.id) if not exists: await ctx.error(f"Group `{group.name}` doesn't exists.") return # Check if user already has the role member_role = discord.utils.get(ctx.author.roles, id=group.id) try: if member_role is None: await ctx.author.add_roles(group, reason="Joined group") else: await ctx.author.remove_roles(member_role, reason="Left group") except discord.Forbidden: await ctx.error("I need `Manage Roles` to manage groups.") except discord.HTTPException: await ctx.error("Something went wrong. Try again later.") else: if member_role is None: await ctx.success(f"Joined `{group.name}`.") else: await ctx.success(f"You left `{group.name}`.")
Example #14
Source File: roles.py From NabBot with Apache License 2.0 | 5 votes |
def group_add(self, ctx: NabCtx, *, name: str): """Creates a new group for members to join. The group can be a new role that will be created with this command. If the name matches an existent role, that role will become joinable. You need `Manage Roles` permissions to use this command.""" name = name.replace("\"", "") forbidden = ["add", "remove", "delete", "list"] converter = InsensitiveRole() try: role = await converter.convert(ctx, name) except commands.BadArgument: try: if name.lower() in forbidden: raise discord.InvalidArgument() role = await ctx.guild.create_role(name=name, reason="Created joinable role") except discord.Forbidden: await ctx.error("I need `Manage Roles` permission to create a group.") return except discord.InvalidArgument: await ctx.error("Invalid group name.") return exists = await ctx.pool.fetchval("SELECT true FROM role_joinable WHERE role_id = $1", role.id) if exists: await ctx.error(f"Group `{role.name}` already exists.") return # Can't make joinable group a role higher than the owner's top role top_role: discord.Role = ctx.author.top_role if role >= top_role: await ctx.error("You can't make a group from a role higher or equals than your highest role.") return await ctx.pool.execute("INSERT INTO role_joinable(server_id, role_id) VALUES($1, $2)", ctx.guild.id, role.id) await ctx.success(f"Group `{role.name}` created successfully.")
Example #15
Source File: roles.py From NabBot with Apache License 2.0 | 5 votes |
def group_remove(self, ctx: NabCtx, *, _group: InsensitiveRole): """Removes a group. Removes a group, making members unable to join. When removing a group, you can optionally delete the role too.""" group: discord.Role = _group exists = await ctx.pool.fetchval("SELECT true FROM role_joinable WHERE role_id = $1", group.id) if not exists: await ctx.error(f"`{group.name}` is not a group.") 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 group of a role higher than your highest role.") return msg = await ctx.send(f"Group `{group.name}` will be removed." f"Do you want to remove the role too?") confirm = await ctx.react_confirm(msg, timeout=60, delete_after=True) if confirm is True: try: await group.delete(reason=f"Group removed by {ctx.author}") await ctx.success(f"Group `{group.name}` was removed and the role was deleted.") except discord.Forbidden: await ctx.error(f"I need `Manage Roles` permission to delete the role.\n" f"{ctx.tick()} Group `{group.name}` removed.") else: await ctx.success(f"Group `{group.name}` was removed.") await ctx.pool.execute("DELETE FROM role_joinable WHERE role_id = $1", group.id)
Example #16
Source File: sync.py From GW2Bot with MIT License | 5 votes |
def guildsync(self, ctx): """In game guild rank to discord roles synchronization commands This group allows you to set up a link between your ingame roster and discord. When enabled, new roles will be created for each of your ingame ranks, and ingame members are periodically synced to have the correct role in discord.""" if ctx.invoked_subcommand is None: await ctx.send_help(ctx.command)
Example #17
Source File: general.py From GW2Bot with MIT License | 5 votes |
def guild_default(self, ctx, *, guild_name=None): """ Set your preferred guild for guild commands on this Discord Server. Commands from the guild command group invoked without a guild name will default to this guild. Invoke this command without an argument to reset the default guild. """ guild = ctx.guild if guild_name is None: await self.bot.database.set_guild(guild, { "guild_ingame": None, }, self) return await ctx.send( "Your preferred guild is now reset for " "this server. Invoke this command with a guild " "name to set a default guild.") endpoint_id = "guild/search?name=" + guild_name.replace(' ', '%20') # Guild ID to Guild Name try: guild_id = await self.call_api(endpoint_id) guild_id = guild_id[0] except (IndexError, APINotFound): return await ctx.send("Invalid guild name") except APIForbidden: return await ctx.send( "You don't have enough permissions in game to " "use this command") except APIError as e: return await self.error_handler(ctx, e) # Write to DB, overwrites existing guild await self.bot.database.set_guild(guild, { "guild_ingame": guild_id, }, self) await ctx.send("Your default guild is now set to {} for this server. " "All commands from the `guild` command group " "invoked without a specified guild will default to " "this guild. To reset, simply invoke this command " "without specifying a guild".format(guild_name.title()))
Example #18
Source File: discordgram_ccs.py From SML-Cogs with MIT License | 5 votes |
def discordgramccsreply(self, ctx, id, *, msg): """Reply to a Discordgram by ID.""" author = ctx.message.author server = ctx.message.server if server.id not in self.settings: return if not id.isdigit(): await self.bot.say("id must be a number.") return id = int(id) messages = self.settings[server.id]["MESSAGES"] if id >= len(messages): await self.bot.say("That is not a valid Discordgram id.") return message = messages[id] channel_id = self.settings[server.id]["CHANNEL"] channel = self.bot.get_channel(channel_id) bot_msg = await self.bot.get_message( channel, message["BOT_MESSAGE_ID"]) transformations = { '@everyone': '@\u200beveryone', '@here': '@\u200bhere' } def repl2(obj): return transformations.get(obj.group(0), '') pattern = re.compile('|'.join(transformations.keys())) msg = pattern.sub(repl2, msg) comment = "**{}:** {}".format(author.display_name, msg) prev_content = bot_msg.clean_content.rsplit('::', 1) content = "{}\n{}\n\n::{}".format( prev_content[0].rstrip(), comment.rstrip(), prev_content[1].rstrip()) await self.bot.edit_message(bot_msg, new_content=content)
Example #19
Source File: Reminders.py From NotSoBot with MIT License | 5 votes |
def get_time(self, txt): time = 0 if txt.isdigit(): time += int(txt) elif txt.split()[0].isdigit(): s = txt.split()[0] time += int(s) txt = txt[len(s):] else: match = self.time_regex.match(txt) if match is None or not match.group(0): return False months = match.group('months') weeks = match.group('weeks') days = match.group('days') hours = match.group('hours') minutes = match.group('minutes') seconds = match.group('seconds') if months: time += int(months) * 2592000 if weeks: time += int(weeks) * 604800 if days: time += int(days) * 86400 if hours: time += int(hours) * 3600 if minutes: time += int(minutes) * 60 if seconds: time += int(seconds) text = re.sub(self.time_regex, '', txt) if text and text[0] == ' ': text = text[1:] return time, text
Example #20
Source File: antilink.py From refactored-cogs with Mozilla Public License 2.0 | 5 votes |
def _new_message(self, message): """Finds the message and checks it for regex""" user = message.author if message.server is None: return if message.server.id in self.json: if self.json[message.server.id]['toggle'] is True: roles = [r.name for r in user.roles] bot_admin = settings.get_server_admin(message.server) bot_mod = settings.get_server_mod(message.server) if message.channel.id in self.json[message.server.id]['excluded_channels']: return elif user.id == settings.owner: return elif bot_admin in roles: return elif bot_mod in roles: return elif user.permissions_in(message.channel).manage_messages is True: return elif user == message.server.me: return if self.json[message.server.id]['strict']: for match in self.regex_url.finditer(message.content): if self.emoji_string not in match.group(0): asyncio.sleep(0.5) await self.bot.delete_message(message) if self.json[message.server.id]['dm'] is True: await self.bot.send_message(message.author, self.json[message.server.id]['message']) break elif self.regex.search(message.content) is not None or self.regex_discordme.search(message.content) is not None: asyncio.sleep(0.5) await self.bot.delete_message(message) if self.json[message.server.id]['dm'] is True: await self.bot.send_message(message.author, self.json[message.server.id]['message'])
Example #21
Source File: _utils.py From Dozer with GNU General Public License v3.0 | 5 votes |
def group(**kwargs): """Links command groups""" kwargs.setdefault('cls', Group) return commands.group(**kwargs)
Example #22
Source File: _utils.py From Dozer with GNU General Public License v3.0 | 5 votes |
def group(self, *args, **kwargs): """Initiates a command group""" kwargs.setdefault('cls', Group) return super(Group, self).command(*args, **kwargs)
Example #23
Source File: sheetManager.py From avrae with GNU General Public License v3.0 | 5 votes |
def beyond(self, ctx, url: str, *args): """ Loads a character sheet from [D&D Beyond](https://www.dndbeyond.com/), resetting all settings. __Valid Arguments__ `-nocc` - Do not automatically create custom counters for limited use features. """ loading = await ctx.send('Loading character data from Beyond...') url = DDB_URL_RE.match(url) if url is None: return await loading.edit(content="This is not a D&D Beyond link.") url = url.group(1) override = await self._confirm_overwrite(ctx, f"beyond-{url}") if not override: return await ctx.send("Character overwrite unconfirmed. Aborting.") parser = BeyondSheetParser(url) await self._load_sheet(ctx, parser, args, loading)
Example #24
Source File: reminders.py From code-jam-5 with MIT License | 5 votes |
def convert(self, ctx, argument): """Custom converter for the `>reminders` group command. This function does the following lookups: 1. By day (`Monday`, `Tuesday`, `Wednesday` etc.) 2. By Goal ID (1, 2, 5, 10 etc.) 3. By goal name (`Ride Bike`, `Drink Water`, etc.) Returns --------- reminder : :class:`list` of :class:`~Reminder`: The reminder being requested. """ if argument.lower() in REMINDER_DAYS: # it's a day of week reminder = ctx.db.get_reminders_on_day(argument.capitalize()) if not reminder: raise commands.BadArgument(f'No reminders found on {argument}.') return list(reminder) try: # it's a goal ID goal_id = int(argument) reminder = await ctx.db.get_reminder_by_goal_id_async(goal_id) if not reminder: raise commands.BadArgument('Goal ID not found.') return [reminder] except ValueError: pass reminder = await ctx.db.get_reminder_by_goal_name_async(argument) if not reminder: raise commands.BadArgument('Goal name not found.') return [reminder]
Example #25
Source File: initTracker.py From avrae with GNU General Public License v3.0 | 5 votes |
def status(self, ctx, name: str, *, args: str = ''): """Gets the status of a combatant or group. __Valid Arguments__ private - PMs the controller of the combatant a more detailed status.""" combat = await Combat.from_ctx(ctx) combatant = await combat.select_combatant(name, select_group=True) if combatant is None: await ctx.send("Combatant or group not found.") return private = 'private' in args.lower() if not isinstance(combatant, CombatantGroup): private = private and str(ctx.author.id) == combatant.controller status = combatant.get_status(private=private) if private and isinstance(combatant, MonsterCombatant): status = f"{status}\n* This creature is a {combatant.monster_name}." else: status = "\n".join([co.get_status(private=private and str(ctx.author.id) == co.controller) for co in combatant.get_combatants()]) if private: controller = ctx.guild.get_member(int(combatant.controller)) if controller: await controller.send("```markdown\n" + status + "```") else: await ctx.send("```markdown\n" + status + "```")
Example #26
Source File: initTracker.py From avrae with GNU General Public License v3.0 | 5 votes |
def remove_effect(self, ctx, name: str, effect: str = None): """Removes a status effect from a combatant or group. Removes all if effect is not passed.""" combat = await Combat.from_ctx(ctx) targets = [] target = await combat.select_combatant(name, select_group=True) if isinstance(target, CombatantGroup): targets.extend(target.get_combatants()) else: targets.append(target) out = "" for combatant in targets: if effect is None: combatant.remove_all_effects() out += f"All effects removed from {combatant.name}.\n" else: to_remove = await combatant.select_effect(effect) children_removed = "" if to_remove.children: children_removed = f"Also removed {len(to_remove.children)} child effects.\n" to_remove.remove() out += f'Effect {to_remove.name} removed from {combatant.name}.\n{children_removed}' await ctx.send(out) await combat.final()
Example #27
Source File: initTracker.py From avrae with GNU General Public License v3.0 | 5 votes |
def remove_combatant(self, ctx, *, name: str): """Removes a combatant or group from the combat. Usage: !init remove <NAME>""" combat = await Combat.from_ctx(ctx) combatant = await combat.select_combatant(name, select_group=True) if combatant is None: return await ctx.send("Combatant not found.") if combatant is combat.current_combatant: return await ctx.send("You cannot remove a combatant on their own turn.") if combatant.group is not None: group = combat.get_group(combatant.group) if len(group.get_combatants()) <= 1 and group is combat.current_combatant: return await ctx.send( "You cannot remove a combatant if they are the only remaining combatant in this turn.") combat.remove_combatant(combatant) await ctx.send("{} removed from combat.".format(combatant.name)) await combat.final()
Example #28
Source File: events.py From GW2Bot with MIT License | 5 votes |
def timer_embed(self, ctx, group): time = datetime.datetime.utcnow() position = ( 60 * time.hour + time.minute ) % 120 # this gets the minutes elapsed in the current 2 hour window maps = self.gamedata["event_timers"][group] title = { "hot": "HoT Event Timer", "pof": "PoF Event Timer", "day": "Day/Night cycle" }.get(group) embed = discord.Embed(title=title, color=await self.get_embed_color(ctx)) for location in maps: duration_so_far = 0 current_phase = None index = 0 phases = location["phases"] for i, phase in enumerate(phases): if position < duration_so_far: break current_phase = phase["name"] index = i duration_so_far += phase["duration"] index += 1 if index == len(phases): if phases[0]["name"] == phases[index - 1]["name"]: index = 1 duration_so_far += phases[0]["duration"] else: index = 0 next_phase = phases[index]["name"] time_until = duration_so_far - position value = ("Current phase: **{}**" "\nNext phase: **{}** in **{}** minutes".format( current_phase, next_phase, time_until)) embed.add_field(name=location["name"], value=value, inline=False) embed.set_footer(text=self.bot.user.name, icon_url=self.bot.user.avatar_url) return embed
Example #29
Source File: recensor.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def check_match(predicate: Callable[[str], Optional[SRE_Match]], string: str) -> dict: """ Match task worker. Takes a predicate returning a regex match and the string to pass it. Returns a dict of time elapsed and match information (if any) or any match exception. """ t0 = time.perf_counter() ret = {} try: match = predicate(string) except Exception as e: match = None ret['exception'] = e elapsed = time.perf_counter() - t0 ret['time'] = elapsed if match: ret['match'] = match.group(0) ret['span'] = match.span(0) groups = match.groups() if groups: ret.update({ 'group_matches' : tuple(match.group(i + 1) for i in range(len(groups))), 'group_spans' : tuple(match.span(i + 1) for i in range(len(groups))), 'groupdict' : match.groupdict(), 'groups' : groups }) return ret
Example #30
Source File: recensor.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
def check_match_iter(predicate: Callable[[str], Iterator[SRE_Match]], string: str) -> List[dict]: """ Finditer match task worker. """ ret_list = [] match_iter = predicate(string) while True: t0 = time.perf_counter() ret = {} try: match = next(match_iter) except StopIteration: break except Exception as e: match = None ret['exception'] = e elapsed = time.perf_counter() - t0 ret['time'] = elapsed if match: ret['match'] = match.group(0) ret['span'] = match.span(0) groups = match.groups() if groups: ret.update({ 'group_spans' : tuple(match.span(i + 1) for i in range(len(groups))), 'groupdict' : match.groupdict(), 'groups' : groups }) ret_list.append(ret) if 'exception' in ret: break return ret_list