async def settings(self, ctx, *args): """Shows the user settings and allows editing on the fly""" self.log_command_call("settings", ctx.message) new_settings, errors = self.maybe_parse_args(args) # We do not allow invalid args if len(errors) > 0: description = "\n".join(errors) embed = create_error_embed(description=description) else: user_id = str(ctx.message.author.id) user_custom_settings = get_user_settings(user_id) # Maybe update settings if len(new_settings.keys()) > 0: new_user_settings = {**user_custom_settings, **new_settings} update_user_settings(user_id, new_user_settings) # No need to re-fetch if updated user_settings = { **DEFAULT_USER_SETTINGS, **user_custom_settings, **new_settings, } description = "\n".join( [f"{k}: `{v}`" for k, v in user_settings.items()]) embed = create_embed(title="Your current settings are:", description=description) await ctx.send(embed=embed)
async def cats(self, ctx): url = get_image_url(2) embed = create_embed(autorName='Cats', icon_url=url, img_url=url, footer='Cats') await ctx.send(embed=embed)
async def clear(self, ctx, limit): """Checks the last N messages in the channel and remove both commands and bot messages""" self.log_command_call("clear", ctx.message) error = self._validate_clear_args(limit) if error is not None: error_embed = create_error_embed(description=error) await ctx.send(embed=error_embed) else: limit = int(limit) + 1 # To account for THIS command call await ctx.channel.purge( limit=limit, check=lambda msg: self._should_delete(msg, ctx)) # Send some feedback auto_destruct_timer = 5 feedback_embed = create_embed( title="Purge recap", description=f"Check the last {limit-1} message for deletion", ) feedback_embed.set_footer( text= f"This message will auto-destruct in {auto_destruct_timer} seconds" ) message = await ctx.send(embed=feedback_embed) # Then we delete the call and our feedback time.sleep(auto_destruct_timer) await ctx.message.delete() await message.delete()
async def send_answers(self): """Create proposals and send them to the board""" # Combine Black Cards and MongoPlayer answers results = list() black_card = await self.get_black_card() players = await self.get_players() for player in players: if player.document_id != self.tsar_id: answers = list() player_answers = await player.get_answers() for answer in player_answers: self._document["white_cards"].append(answer.document_id) answers.append(answer.text) result = black_card.text.format(*answers) results.append([player.document_id, result]) await player.delete_answers() shuffle(results) self._document["results"] = results await self.save() # Send answers to the board proposals = str() for index, value in enumerate(self._document["results"]): proposals += "{}. {}".format(index + 1, value[1]) message = create_embed( dict(fields=dict( name="Proposals", value=proposals.rstrip(), inline=False))) return message
async def save(self, ctx, name, *args): """Creates a shortcut for a group of roll instructions""" self.log_command_call("save", ctx.message) errors = self._validate_set_instructions(name, *args) if len(errors) > 0: description = "\n".join(errors) embed = create_error_embed(description=description) else: user_id = str(ctx.message.author.id) user_shortcuts = get_user_shortcuts(user_id) _max = (self.MAX_SHORTCUTS if name not in user_shortcuts else self.MAX_SHORTCUTS + 1) if len(user_shortcuts.items()) > _max: description = f"Cannot have more than `{self.MAX_SHORTCUTS}` shortcuts. \ \nPlease remove some using the `remove` command" embed = create_error_embed(description=description) else: instructions_as_string = " ".join(args) user_shortcuts[name] = instructions_as_string update_user_shortcuts(user_id, user_shortcuts) description = ( f"The `{name}` shortcut now points to `{instructions_as_string}`" ) embed = create_embed(title="Settings updated!", description=description) await ctx.send(embed=embed)
async def dogs(self, ctx): url = get_image_url(1) embed = create_embed(autorName='Dog', icon_url=url, img_url=url, footer='Dog') await ctx.send(embed=embed)
async def greetings(self, ctx): helpdict = help[0] embed = create_embed( title=helpdict['greetings']['title'], description=helpdict['greetings']['description'], fields=helpdict['fields'], ) await ctx.send(embed=embed)
async def invite(self, ctx): helpdict = help[0] embed = create_embed( title=helpdict['invite']['title'], description=helpdict['invite']['description'], fields=[helpdict['invite']], ) await ctx.send(embed=embed)
async def on_message(self, message): """On mentioned-first, returns the current prefix for this bot on this guild""" if len(message.mentions) == 0 or message.mentions[0] != self.bot.user: return self.log_command_call("getprefix", message) prefix_value = get_command_prefix(self.bot, message) embed = create_embed( description=f"My current prefix on this guild is `{prefix_value}`") await message.channel.send(embed=embed)
async def score(self): """Displays the score""" scores = await self.get_players_score() fields = list() for player, score in scores: fields.append( dict(name=player.user.display_name, value=score, inline=True)) message = create_embed(dict(title="Score", fields=fields)) await self.board.send(embed=message)
async def help(self, ctx): helpdict = help[0] if (ctx.subcommand_passed != None): return else: embed = create_embed( title=helpdict['title']['title'], description=helpdict['title']['description'], fields=[helpdict['commands']], ) return await ctx.send(embed=embed)
async def setprefix(self, ctx, prefix): """Changes prefix for this bot on this guild. Only usable by admins.""" self.log_command_call("setprefix", ctx.message) guild_id = str(ctx.guild.id) settings = get_guild_settings(guild_id) settings["prefix"] = prefix update_guild_settings(guild_id, settings) description = f"From now on, I'll respond to the `{prefix}` command prefix" embed = create_embed(title="Settings updated!", description=description) await ctx.send(embed=embed)
async def removeall(self, ctx): """Deletes all the shortcuts of the user""" self.log_command_call("removeall", ctx.message) user_id = str(ctx.message.author.id) user_shortcuts = get_user_shortcuts(user_id) if len(user_shortcuts.keys()) == 0: description = "Looks like you have no existing shortcuts!" embed = create_warning_embed(description=description) else: update_user_shortcuts(user_id, {}) description = "All your shortcuts have been removed" embed = create_embed(title="Settings updated!", description=description) await ctx.send(embed=embed)
async def show(self, ctx): """Shows the current shortcuts for the user""" self.log_command_call("show", ctx.message) shortcuts = get_user_shortcuts(str(ctx.message.author.id)) if len(shortcuts.keys()) == 0: description = "Looks like you have no existing shortcuts!" embed = create_warning_embed(description=description) else: description = "\n".join( [f"{k}: {v}" for k, v in shortcuts.items()]) description = generate_discord_markdown_string([description]) embed = create_embed(title="Here are your shortcuts:", description=description) await ctx.send(embed=embed)
async def remove(self, ctx, name): """Deletes an existing shortcut for the user""" self.log_command_call("remove", ctx.message) user_id = str(ctx.message.author.id) user_shortcuts = get_user_shortcuts(user_id) if name not in user_shortcuts.keys(): description = f"Found no shortcut with the name `{name}` in your settings" embed = create_warning_embed(description=description) else: del user_shortcuts[name] update_user_shortcuts(user_id, user_shortcuts) description = f"The `{name}` shortcut has been removed successfully" embed = create_embed(title="Settings updated!", description=description) await ctx.send(embed=embed)
async def draw_black_card(self): """Draw a new Black Card and send it to the board""" # Get a new Black Card query = [{"$sample": {"size": 1}}] card_number = len(self.black_cards_id) while len(self.black_cards_id) is card_number: async for document in self._client[ self._DATABASE]["black_cards"].aggregate(query): if document["_id"] not in self.black_cards_id: self._document["black_cards"].append(document["_id"]) await self.save() # Send Black Card to the board black_card = await self.get_black_card() message = create_embed( dict(title="Question - Pick {}".format(black_card.pick), description=black_card.text)) return message
async def draw_white_cards(self, used_cards): """Draw white cards for the player Arguments: used_cards {*ObjectId} -- ObjectId of used cards """ query = [{"$sample": {"size": 1}}] while not len(self.white_cards_id) is self._WHITE_CARDS_NUMBER: async for document in self._client[ self._DATABASE]["white_cards"].aggregate(query): if document["_id"] not in used_cards: self._document["white_cards"].append(document["_id"]) await self.save() proposals = str() white_cards = await self.get_white_cards() for index, card in enumerate(white_cards): proposals += "{}. {}\n".format(index + 1, card.text) embed = create_embed( dict(fields=dict( name="Answers", value=proposals.rstrip(), inline=False))) await self.channel.send(embed=embed)
async def on_command_error(ctx, error): """Triggered when a command send an error Decorators: BOT.event Arguments: ctx {Context} -- Context of the message error {Exception} -- Discord error """ content = dict(colour=Color.dark_red()) critical(ctx.command, error) field = dict(name="Error", inline=False) if isinstance(error, errors.NoPrivateMessage): field["value"] = ":warning: This command cannot be used in private messages." elif isinstance(error, errors.CommandOnCooldown): field["value"] = ":stopwatch: This command is on cooldown, \ retry after {:.2f} seconds".format(error.retry_after) elif isinstance(error, errors.DisabledCommand): field["value"] = "This command is disabled and cannot be used." elif isinstance(error, errors.CommandNotFound): field["value"] = ":grey_question: Unknown command. \ Use `{}help` to get commands".format(ctx.prefix) elif isinstance(error, errors.MissingPermissions): field["value"] = ":no_entry_sign: {}".format(error.message) elif isinstance(error, errors.MissingRequiredArgument): field["value"] = "An argument is missing" elif isinstance(error, errors.CheckFailure): field["value"] = ":no_entry_sign: At least 1 check has failed" elif isinstance(error, errors.NotOwner): field["value"] = ":no_entry_sign: You are not the owner of the bot" elif isinstance(error, errors.CommandInvokeError): field["value"] = ":stop_sign: The command {} has thrown an error.".format(ctx.command) critical('In {0.command.qualified_name}:'.format(ctx)) print_tb(error.original.__traceback__) critical('{0.__class__.__name__}: {0}'.format(error.original)) content["fields"] = field message = create_embed(content) await ctx.author.send(embed=message)
async def ping(self, ctx): """Checks if the bot is up""" self.log_command_call("ping", ctx.message) embed_output = create_embed(description="pong") await ctx.send(embed=embed_output)
async def about(self, ctx): """Provides a recap of the bot information""" self.log_command_call("about", ctx.message) embed = create_embed(description=ABOUT_TEXT) await ctx.send(embed=embed)
async def help(self, ctx): """Checks if the bot is up""" self.log_command_call("help", ctx.message) await ctx.send(HELP_TEXT) embed_output = create_embed(description=MORE_INFO_TEXT) await ctx.send(embed=embed_output)