Python discord.ext.commands.MissingRequiredArgument() Examples
The following are 30
code examples of discord.ext.commands.MissingRequiredArgument().
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
.
Example #1
Source File: bot.py From rewrite with GNU General Public License v3.0 | 6 votes |
def on_command_error(self, ctx, exception): exc_class = exception.__class__ if exc_class in (commands.CommandNotFound, commands.NotOwner): return exc_table = { commands.MissingRequiredArgument: f"{WARNING} The required arguments are missing for this command!", commands.NoPrivateMessage: f"{WARNING} This command cannot be used in PM's!", commands.BadArgument: f"{WARNING} A bad argument was passed, please check if your arguments are correct!", IllegalAction: f"{WARNING} A node error has occurred: `{getattr(exception, 'msg', None)}`", CustomCheckFailure: getattr(exception, "msg", None) or "None" } if exc_class in exc_table.keys(): await ctx.send(exc_table[exc_class]) else: await super().on_command_error(ctx, exception)
Example #2
Source File: bot.py From RemixBot with MIT License | 6 votes |
def on_command_error(ctx, error): send_help = (commands.MissingRequiredArgument, commands.BadArgument, commands.TooManyArguments, commands.UserInputError) if isinstance(error, commands.CommandNotFound): # fails silently pass elif isinstance(error, send_help): _help = await send_cmd_help(ctx) await ctx.send(embed=_help) elif isinstance(error, commands.CommandOnCooldown): await ctx.send(f'This command is on cooldown. Please wait {error.retry_after:.2f}s') elif isinstance(error, commands.MissingPermissions): await ctx.send('You do not have the permissions to use this command.') # If any other error occurs, prints to console. else: print(''.join(traceback.format_exception(type(error), error, error.__traceback__)))
Example #3
Source File: RPGBot.py From RPGBot with GNU General Public License v3.0 | 5 votes |
def on_command_error(self, ctx, exception): self.stats.increment("RPGBot.errors", tags=["RPGBot:errors"], host="scw-8112e8") logging.info(f"Exception in {ctx.command} {ctx.guild}:{ctx.channel} {exception}") exception = getattr(exception, "original", exception) traceback.print_tb(exception.__traceback__) print(exception) try: if isinstance(exception, commands.MissingRequiredArgument): await ctx.send(f"```{exception}```") elif isinstance(exception, TimeoutError): await ctx.send(await _(ctx, "This operation ran out of time! Please try again")) elif isinstance(exception, discord.Forbidden): await ctx.send(await _(ctx, "Error: This command requires the bot to have permission to send links.")) else: await ctx.send(f"`{exception} If this is unexpected, please report this to the bot creator`") except discord.Forbidden: pass
Example #4
Source File: reminders.py From code-jam-5 with MIT License | 5 votes |
def cog_command_error(self, ctx, error): """Send errors to the user if a bad argument has been passed. """ if isinstance(error, (commands.BadArgument, commands.MissingRequiredArgument)): return await ctx.send(str(error))
Example #5
Source File: climate_arguments.py From code-jam-5 with MIT License | 5 votes |
def cog_command_error(self, ctx, error): """Error handler for the cog; returns errors to the user if required. """ if isinstance(error, (commands.BadArgument, commands.MissingRequiredArgument, commands.CheckFailure) ): return await ctx.send(str(error))
Example #6
Source File: farmer_game.py From code-jam-5 with MIT License | 5 votes |
def cog_command_error(self, ctx, error): if isinstance(error, (commands.BadArgument, commands.MissingRequiredArgument, commands.CheckFailure)): await ctx.send(str(error)) try: await ctx.db_stats.remove_last_used() except AttributeError: # command wasn't decorated with `@requires_account` pass
Example #7
Source File: pollmaster.py From pollmaster with MIT License | 5 votes |
def on_command_error(ctx, e): if hasattr(ctx.cog, 'qualified_name') and ctx.cog.qualified_name == "Admin": # Admin cog handles the errors locally return if SETTINGS.log_errors: ignored_exceptions = ( commands.MissingRequiredArgument, commands.CommandNotFound, commands.DisabledCommand, commands.BadArgument, commands.NoPrivateMessage, commands.CheckFailure, commands.CommandOnCooldown, commands.MissingPermissions, discord.errors.Forbidden, ) if isinstance(e, ignored_exceptions): # log warnings # logger.warning(f'{type(e).__name__}: {e}\n{"".join(traceback.format_tb(e.__traceback__))}') return # log error logger.error(f'{type(e).__name__}: {e}\n{"".join(traceback.format_tb(e.__traceback__))}') traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr) if SETTINGS.msg_errors: # send discord message for unexpected errors e = discord.Embed( title=f"Error With command: {ctx.command.name}", description=f"```py\n{type(e).__name__}: {str(e)}\n```\n\nContent:{ctx.message.content}" f"\n\tServer: {ctx.message.server}\n\tChannel: <#{ctx.message.channel}>" f"\n\tAuthor: <@{ctx.message.author}>", timestamp=ctx.message.timestamp ) await ctx.send(bot.owner, embed=e) # if SETTINGS.mode == 'development': raise e
Example #8
Source File: admin.py From pollmaster with MIT License | 5 votes |
def cog_command_error(self, ctx, error): if isinstance(error, commands.CheckFailure): await ctx.send("Only the owner can use this module. Join the support discord server if you are having " "any problems. This usage has been logged.") logger.warning(f'User {ctx.author} ({ctx.author.id}) has tried to access a restricted ' f'command via {ctx.message.content}.') elif isinstance(error, commands.MissingRequiredArgument): await ctx.send("Missing a required argument for this command.") else: logger.warning(error)
Example #9
Source File: poll.py From modmail-plugins with GNU General Public License v3.0 | 5 votes |
def poll_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): return await ctx.send("Missing the question.")
Example #10
Source File: core.py From NabBot with Apache License 2.0 | 5 votes |
def process_user_input_error(self, ctx: context.NabCtx, error: commands.UserInputError): """Handles UserInput errors. These are exceptions raised due to the user providing invalid or incorrect input.""" if isinstance(error, commands.MissingRequiredArgument): await ctx.error(f"The correct syntax is: `{ctx.clean_prefix}{ctx.command.qualified_name} {ctx.usage}`.\n" f"Try `{ctx.clean_prefix}help {ctx.command.qualified_name}` for more info.") elif isinstance(error, commands.BadArgument): _type, param = self.parse_bad_argument(str(error)) # Making these errors more understandable. if _type == "int": error = f"Parameter `{param}` must be numeric." await ctx.error(f"{error}\nTry `{ctx.clean_prefix}help {ctx.command.qualified_name}` for more info.")
Example #11
Source File: bot.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def on_command_error(self, context, exception): if isinstance(exception, commands.BadUnionArgument): msg = "Could not find the specified " + human_join( [c.__name__ for c in exception.converters] ) await context.trigger_typing() await context.send(embed=discord.Embed(color=self.error_color, description=msg)) elif isinstance(exception, commands.BadArgument): await context.trigger_typing() await context.send( embed=discord.Embed(color=self.error_color, description=str(exception)) ) elif isinstance(exception, commands.CommandNotFound): logger.warning("CommandNotFound: %s", exception) elif isinstance(exception, commands.MissingRequiredArgument): await context.send_help(context.command) elif isinstance(exception, commands.CheckFailure): for check in context.command.checks: if not await check(context): if hasattr(check, "fail_msg"): await context.send( embed=discord.Embed(color=self.error_color, description=check.fail_msg) ) if hasattr(check, "permission_level"): corrected_permission_level = self.command_perm( context.command.qualified_name ) logger.warning( "User %s does not have permission to use this command: `%s` (%s).", context.author.name, context.command.qualified_name, corrected_permission_level.name, ) logger.warning("CheckFailure: %s", exception) else: logger.error("Unexpected exception:", exc_info=exception)
Example #12
Source File: utility.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def status(self, ctx, *, status_type: str.lower): """ Set a status for the bot. Possible status types: - `online` - `idle` - `dnd` or `do not disturb` - `invisible` or `offline` To remove the current status: - `{prefix}status clear` """ if status_type == "clear": self.bot.config.remove("status") await self.bot.config.update() await self.set_presence() embed = discord.Embed(title="Status Removed", color=self.bot.main_color) return await ctx.send(embed=embed) status_type = status_type.replace(" ", "_") try: status = Status[status_type] except KeyError: raise commands.MissingRequiredArgument(SimpleNamespace(name="status")) _, status = await self.set_presence(status=status) self.bot.config["status"] = status.value await self.bot.config.update() msg = f"Status set to: {status.value}." embed = discord.Embed(title="Status Changed", description=msg, color=self.bot.main_color) return await ctx.send(embed=embed)
Example #13
Source File: nullctf.py From NullCTF with GNU General Public License v3.0 | 5 votes |
def on_command_error(ctx, error): if isinstance(error, commands.CommandNotFound): return if isinstance(error, commands.MissingRequiredArgument): await ctx.send("Missing a required argument. Do >help") if isinstance(error, commands.MissingPermissions): await ctx.send("You do not have the appropriate permissions to run this command.") if isinstance(error, commands.BotMissingPermissions): await ctx.send("I don't have sufficient permissions!") else: print("error not caught") print(error)
Example #14
Source File: roster.py From spirit with MIT License | 5 votes |
def setclass_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): manager = MessageManager(ctx) await manager.send_message("Oops! You didn't include your Destiny 2 class.") await manager.clean_messages()
Example #15
Source File: roster.py From spirit with MIT License | 5 votes |
def settimezone_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): manager = MessageManager(ctx) await manager.send_message("Oops! You didn't include your timezone.") await manager.clean_messages()
Example #16
Source File: manage_cog.py From wall_e with GNU General Public License v3.0 | 5 votes |
def on_command_error(self, ctx, error): if self.check_test_environment(ctx): if isinstance(error, commands.MissingRequiredArgument): logger.error('[ManageCog on_command_error()] Missing argument: {0}'.format(error.param)) e_obj = await imported_embed( ctx, author=self.config.get_config_value('bot_profile', 'BOT_NAME'), avatar=self.config.get_config_value('bot_profile', 'BOT_AVATAR'), description="Missing argument: {}".format(error.param) ) if e_obj is not False: await ctx.send(embed=e_obj) else: # only prints out an error to the log if the string that was entered doesnt contain just "." pattern = r'[^\.]' if re.search(pattern, str(error)[9:-14]): # author = ctx.author.nick or ctx.author.name # await ctx.send('Error:\n```Sorry '+author+', seems like the command # \"'+str(error)[9:-14]+'\"" doesn\'t exist :(```') if type(error) is discord.ext.commands.errors.CheckFailure: logger.warning( "[ManageCog on_command_error()] user {} " "probably tried to access a command they arent supposed to".format(ctx.author) ) else: traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) return # this command is used by the TEST guild to create the channel from which this TEST container will process # commands
Example #17
Source File: item.py From spirit with MIT License | 5 votes |
def item_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): manager = MessageManager(ctx) await manager.send_message("Oops! You didn't specify a search term.") await manager.clean_messages()
Example #18
Source File: general.py From spirit with MIT License | 5 votes |
def feedback_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): manager = MessageManager(ctx) await manager.send_message("You forgot to include your feedback!") await manager.clean_messages()
Example #19
Source File: modmail.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def logs(self, ctx, *, user: User = None): """ Get previous Modmail thread logs of a member. Leave `user` blank when this command is used within a thread channel to show logs for the current recipient. `user` may be a user ID, mention, or name. """ await ctx.trigger_typing() if not user: thread = ctx.thread if not thread: raise commands.MissingRequiredArgument(SimpleNamespace(name="member")) user = thread.recipient default_avatar = "https://cdn.discordapp.com/embed/avatars/0.png" icon_url = getattr(user, "avatar_url", default_avatar) logs = await self.bot.api.get_user_logs(user.id) if not any(not log["open"] for log in logs): embed = discord.Embed( color=self.bot.error_color, description="This user does not have any previous logs.", ) return await ctx.send(embed=embed) logs = reversed([log for log in logs if not log["open"]]) embeds = self.format_log_embeds(logs, avatar_url=icon_url) session = EmbedPaginatorSession(ctx, *embeds) await session.run()
Example #20
Source File: settings.py From spirit with MIT License | 5 votes |
def seteventdeleterole_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): manager = MessageManager(ctx) event_role = get_event_delete_role(ctx) if not event_role: role_display = '**None** (only Manage Sever members can delete events)' else: role_display = format_role_name(event_role) await manager.send_message("The current event delete role is: {}\n\n".format(role_display) + "To change the event delete role, use '{}settings seteventdeleterole <role_name>'".format(ctx.prefix)) await manager.clean_messages()
Example #21
Source File: settings.py From spirit with MIT License | 5 votes |
def setprefix_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): manager = MessageManager(ctx) await manager.send_message("Oops! You didn't provide a new prefix.") await manager.clean_messages()
Example #22
Source File: settings.py From spirit with MIT License | 5 votes |
def seteventrole_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): manager = MessageManager(ctx) event_role = get_event_role(ctx) if not event_role: role_display = 'None (anyone can make events)' else: role_display = format_role_name(event_role) await manager.send_message("The current event role is: **{}**\n\n".format(role_display) + "To change the event role, use '{}settings seteventrole <role_name>'".format(ctx.prefix)) await manager.clean_messages()
Example #23
Source File: error_handler.py From RTFMbot with Mozilla Public License 2.0 | 4 votes |
def _on_command_error(self, ctx, error, bypass = False): name, content = None, None raised = False if hasattr(ctx.command, 'on_error') or (ctx.command and hasattr(ctx.cog, f'_{ctx.command.cog_name}__error')) and not bypass: # Do nothing if the command/cog has its own error handler and the bypass is False return if isinstance(error, commands.CommandInvokeError) and hasattr(error, 'original'): error = error.original raised = True if isinstance(error, commands.CommandNotFound) or isinstance(error, commands.NotOwner): return elif isinstance(error, commands.MissingRequiredArgument): name = "SyntaxError" content = f"Command `{ctx.command.name}` missing 1 required argument: `{error.param.name}`" elif isinstance(error, commands.BadArgument): name = "TypeError" content = str(error.args[0]) elif isinstance(error, commands.CommandOnCooldown): name = "TimeoutError" content = f"Command on cooldown. Retry in `{format(error.retry_after, '.2f')}s`." elif isinstance(error, commands.CheckFailure): name = "PermissionError" content = "Escalation failed: you are not in the sudoers file.\nThis incident will be reported" elif isinstance(error, discord.Forbidden) or isinstance(error, discord.HTTPException): # We may not be able to send an embed or even send a message at this point bot_member = ctx.guild.get_member(self.bot.user.id) can_talk = ctx.channel.permissions_for(bot_member).send_messages if can_talk: return await ctx.send(f"```An error occurred while responding:\n{error.code} - {error.text}\n\nI need following permissions:\n\nEmbed links\nAttach files\nAdd reactions```") elif isinstance(error, UnicodeError): name = "UnicodeError" content = "The bot failed to decode your input or a command output. Make sure you only use UTF-8" if name is not None: emb = discord.Embed(title=name, description=content, colour=self.bot.config['RED']) await ctx.send(embed=emb) elif raised: print(f'{time.strftime("%d/%m/%y %H:%M:%S")} | {ctx.command.qualified_name}', file=sys.stderr) traceback.print_tb(error.__traceback__) print(f'{error.__class__.__name__}: {error}', file=sys.stderr, end='\n\n') else: print(traceback.format_exc())
Example #24
Source File: error_handler.py From code-jam-5 with MIT License | 4 votes |
def on_command_error(self, ctx, error): """Task when an error occurs.""" if isinstance(error, commands.CommandNotFound): return logger.info(f"{ctx.author} used {ctx.message.content} " f"but nothing was found.") if isinstance(error, commands.MissingRequiredArgument): logger.info(f"{ctx.author} called {ctx.message.content} and " f"triggered MissingRequiredArgument error.") return await ctx.send(f"`{error.param}` is a required argument.") if isinstance(error, commands.CheckFailure): logger.info(f"{ctx.author} called {ctx.message.content} and triggered" f" CheckFailure error.") return await ctx.send("You do not have permission to use this command!") if isinstance(error, (commands.UserInputError, commands.BadArgument)): logger.info(f"{ctx.author} called {ctx.message.content} and triggered" f" UserInputError error.") return await ctx.send("Invalid arguments.") if isinstance(error, commands.CommandOnCooldown): logger.info(f"{ctx.author} called {ctx.message.content} and" f" triggered ComamndOnCooldown error.") return await ctx.send(f"Command is on cooldown!" f" Please retry after `{error.retry_after}`") if isinstance(error, commands.BotMissingPermissions): logger.info(f"{ctx.author} called {ctx.message.content} and triggered" f" BotMissingPermissions error.") embed = discord.Embed() embed.colour = discord.Colour.blue() title = "The bot lacks the following permissions to execute the command:" embed.title = title embed.description = "" for perm in error.missing_perms: embed.description += str(perm) return await ctx.send(embed=embed) if isinstance(error, commands.DisabledCommand): logger.info(f"{ctx.author} called {ctx.message.content} and" f" triggered DisabledCommand error.") return await ctx.send("The command has been disabled!") logger.warning(f"{ctx.author} called {ctx.message.content} and" f" triggered the following error:\n {error}")
Example #25
Source File: general.py From cyberdisc-bot with MIT License | 4 votes |
def on_command_error(self, ctx, error): # Try provide some user feedback instead of logging all errors. if isinstance(error, commands.CommandNotFound): return # No need to log unfound commands anywhere or return feedback if isinstance(error, commands.MissingRequiredArgument): # Missing arguments are likely human error so do not need logging parameter_name = error.param.name return await ctx.send( f"\N{NO ENTRY SIGN} Required argument {parameter_name} was missing" ) elif isinstance(error, commands.CheckFailure): return await ctx.send( "\N{NO ENTRY SIGN} You do not have permission to use that command" ) elif isinstance(error, commands.CommandOnCooldown): retry_after = round(error.retry_after) return await ctx.send( f"\N{HOURGLASS} Command is on cooldown, try again after {retry_after} seconds" ) # All errors below this need reporting and so do not return if isinstance(error, commands.ArgumentParsingError): # Provide feedback & report error await ctx.send( "\N{NO ENTRY SIGN} An issue occurred while attempting to parse an argument" ) elif isinstance(error, commands.BadArgument): await ctx.send("\N{NO ENTRY SIGN} Conversion of an argument failed") else: await ctx.send( "\N{NO ENTRY SIGN} An error occured during execution, the error has been reported." ) extra_context = { "discord_info": { "Channel": ctx.channel.mention, "User": ctx.author.mention, "Command": ctx.message.content, } } if ctx.guild is not None: # We are NOT in a DM extra_context["discord_info"]["Message"] = ( f"[{ctx.message.id}](https://discordapp.com/channels/" f"{ctx.guild.id}/{ctx.channel.id}/{ctx.message.id})" ) else: extra_context["discord_info"]["Message"] = f"{ctx.message.id} (DM)" self.bot.log.exception(error, extra=extra_context)
Example #26
Source File: handler.py From DJ5n4k3 with MIT License | 4 votes |
def on_command_error(self, ctx, error): if hasattr(ctx.command, 'on_error'): return ignored = (commands.MissingRequiredArgument, commands.BadArgument, commands.NoPrivateMessage, commands.CheckFailure, commands.CommandNotFound, commands.DisabledCommand, commands.CommandInvokeError, commands.TooManyArguments, commands.UserInputError, commands.CommandOnCooldown, commands.NotOwner, commands.MissingPermissions, commands.BotMissingPermissions) error = getattr(error, 'original', error) if isinstance(error, commands.CommandNotFound): return elif isinstance(error, commands.BadArgument): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.MissingRequiredArgument): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.NoPrivateMessage): return elif isinstance(error, commands.CheckFailure): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like this command is thought for other users. You can't use it.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.DisabledCommand): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like this command in disabled.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.CommandInvokeError): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like something went wrong. Report this issue to the developer.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.TooManyArguments): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you gave too many arguments.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.UserInputError): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you did something wrong.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.CommandOnCooldown): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.NotOwner): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you do not own this bot.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.MissingPermissions): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url)) elif isinstance(error, commands.BotMissingPermissions): await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))
Example #27
Source File: thread.py From modmail with GNU Affero General Public License v3.0 | 4 votes |
def reply(self, message: discord.Message, anonymous: bool = False) -> None: if not message.content and not message.attachments: raise MissingRequiredArgument(SimpleNamespace(name="msg")) if not any(g.get_member(self.id) for g in self.bot.guilds): return await message.channel.send( embed=discord.Embed( color=self.bot.error_color, description="Your message could not be delivered since " "the recipient shares no servers with the bot.", ) ) tasks = [] try: await self.send( message, destination=self.recipient, from_mod=True, anonymous=anonymous ) except Exception: logger.error("Message delivery failed:", exc_info=True) tasks.append( message.channel.send( embed=discord.Embed( color=self.bot.error_color, description="Your message could not be delivered as " "the recipient is only accepting direct " "messages from friends, or the bot was " "blocked by the recipient.", ) ) ) else: # Send the same thing in the thread channel. msg = await self.send( message, destination=self.channel, from_mod=True, anonymous=anonymous ) tasks.append( self.bot.api.append_log( message, message_id=msg.id, channel_id=self.channel.id, type_="anonymous" if anonymous else "thread_message", ) ) # Cancel closing if a thread message is sent. if self.close_task is not None: await self.cancel_closure() tasks.append( self.channel.send( embed=discord.Embed( color=self.bot.error_color, description="Scheduled close has been cancelled.", ) ) ) await asyncio.gather(*tasks)
Example #28
Source File: main.py From THM-Bot with GNU Lesser General Public License v3.0 | 4 votes |
def on_command_error(ctx, error): error_to_skip = [CommandNotFound, MissingRequiredArgument] for error_type in error_to_skip: if isinstance(error, error_type): return raise error # Starting the bot.
Example #29
Source File: utility.py From modmail with GNU Affero General Public License v3.0 | 4 votes |
def activity(self, ctx, activity_type: str.lower, *, message: str = ""): """ Set an activity status for the bot. Possible activity types: - `playing` - `streaming` - `listening` - `watching` When activity type is set to `listening`, it must be followed by a "to": "listening to..." When activity type is set to `streaming`, you can set the linked twitch page: - `{prefix}config set twitch_url https://www.twitch.tv/somechannel/` To remove the current activity status: - `{prefix}activity clear` """ if activity_type == "clear": self.bot.config.remove("activity_type") self.bot.config.remove("activity_message") await self.bot.config.update() await self.set_presence() embed = discord.Embed(title="Activity Removed", color=self.bot.main_color) return await ctx.send(embed=embed) if not message: raise commands.MissingRequiredArgument(SimpleNamespace(name="message")) try: activity_type = ActivityType[activity_type] except KeyError: raise commands.MissingRequiredArgument(SimpleNamespace(name="activity")) activity, _ = await self.set_presence( activity_type=activity_type, activity_message=message ) self.bot.config["activity_type"] = activity.type.value self.bot.config["activity_message"] = activity.name await self.bot.config.update() msg = f"Activity set to: {activity.type.name.capitalize()} " if activity.type == ActivityType.listening: msg += f"to {activity.name}." else: msg += f"{activity.name}." embed = discord.Embed(title="Activity Changed", description=msg, color=self.bot.main_color) return await ctx.send(embed=embed)
Example #30
Source File: modmail.py From modmail with GNU Affero General Public License v3.0 | 4 votes |
def unblock(self, ctx, *, user: User = None): """ Unblock a user from using Modmail. Leave `user` blank when this command is used within a thread channel to unblock the current recipient. `user` may be a user ID, mention, or name. """ if user is None: thread = ctx.thread if thread: user = thread.recipient else: raise commands.MissingRequiredArgument(SimpleNamespace(name="user")) mention = getattr(user, "mention", f"`{user.id}`") name = getattr(user, "name", f"`{user.id}`") if str(user.id) in self.bot.blocked_users: msg = self.bot.blocked_users.pop(str(user.id)) or "" await self.bot.config.update() if msg.startswith("System Message: "): # If the user is blocked internally (for example: below minimum account age) # Show an extended message stating the original internal message reason = msg[16:].strip().rstrip(".") or "no reason" embed = discord.Embed( title="Success", description=f"{mention} was previously blocked internally {reason}.\n" f"{mention} is no longer blocked.", color=self.bot.main_color, ) embed.set_footer( text="However, if the original system block reason still applies, " f"{name} will be automatically blocked again. " f'Use "{self.bot.prefix}blocked whitelist {user.id}" to whitelist the user.' ) else: embed = discord.Embed( title="Success", color=self.bot.main_color, description=f"{mention} is no longer blocked.", ) else: embed = discord.Embed( title="Error", description=f"{mention} is not blocked.", color=self.bot.error_color ) return await ctx.send(embed=embed)