class RoleCollectionClass(AbstractRoleCollection): """Enum of roles in the correct order (last ones have a lower position)""" # Bot role BOT = RoleDescription( name="Bot", permissions=Permissions(8), # admin right colour=Colour.green(), mentionable=True, ) # Developer DEV = RoleDescription( name="Admin", permissions=Permissions.all(), # all rights colour=Colour.dark_red(), ) # Game master MASTER = RoleDescription( name="Game master", permissions=Permissions(2147483127), # all rights except admin colour=Colour.dark_red(), mentionable=True, ) # Visitor, base role VISITOR = RoleDescription( name="Player", permissions=Permissions(68224000), # change nickname, view channels, read message history, connect colour=Colour.red(), ) DEFAULT = DefaultRoleDescription(permissions=Permissions(use_voice_activation=True))
async def test_detect_haiku_finds_multiple_word_haiki(bot, message): message.clean_content = "two two one three two one one one four" clazz = Haiku(bot) clazz.syllables = {"one": 1, "two": 2, "three": 3, "four": 4} await clazz.detect_haiku(message) embed = Embed(colour=Colour.dark_red()).add_field(name=EMBED_NAME, value="_two two one\nthree two one one\none four_") message.channel.send.assert_called_once_with(embed=embed)
def embed_post(link): post_num = link.split('#')[1] post = requests.get(link).text soup = BeautifulSoup(post, 'html.parser') post_tag = soup.select('#{}'.format(post_num))[0] post_content = post_tag.select('.messageText')[0].get_text() # 2048 is Discord's limit for embed description if len(post_content) > 2048: post_content = post_content[:2045] + '...' embed = Embed() embed.type = "rich" embed.color = Colour.dark_red() embed.title = soup.select('h1')[0].get_text() embed.url = link embed.description = post_content embed.set_author( name=post_tag.get('data-author'), url=CODEX_ROOT + post_tag.select('.avatar')[0].get('href'), icon_url=CODEX_ROOT + post_tag.select('.avatar img')[0].get('src')) return embed
async def test_detect_haiku_finds_case_insensitive_haiku(bot, message): message.clean_content = "FiVe SEVEN fIve" clazz = Haiku(bot) clazz.syllables = {"five": 5, "seven": 7} await clazz.detect_haiku(message) embed = Embed(colour=Colour.dark_red()).add_field(name=EMBED_NAME, value="_FiVe\nSEVEN\nfIve_") message.channel.send.assert_called_once_with(embed=embed)
class WebhookHandler(logging.Handler): _colours = { logging.DEBUG: Colour.light_grey(), logging.INFO: Colour.gold(), logging.WARNING: Colour.orange(), logging.ERROR: Colour.red(), logging.CRITICAL: Colour.dark_red() } def __init__(self, webhook_url, level=logging.NOTSET): super().__init__(level) self._webhook_logger = EmbedWebhookLogger(webhook_url) def emit(self, record: logging.LogRecord): self.format(record) message = f'{record.message}\n{record.exc_text or ""}' message = message[:1987] + '...' if len(message) > 1987 else message self._webhook_logger.log( Embed(colour=self._colours.get(record.levelno), title=record.name, description=f'```py\n{message}\n```', timestamp=datetime.datetime.fromtimestamp( record.created)).add_field( name=ZWSP, value=f'{record.filename}:{record.lineno}'))
async def test_detect_haiku_ignores_punctuation(bot, message): message.clean_content = "five, seven.?! five" clazz = Haiku(bot) clazz.syllables = {"five": 5, "seven": 7} await clazz.detect_haiku(message) embed = Embed(colour=Colour.dark_red()).add_field(name=EMBED_NAME, value="_five\nseven\nfive_") message.channel.send.assert_called_once_with(embed=embed)
def predict_colour(rcode: str) -> Colour: colour = Colour.default() if rcode == "0": colour = Colour.dark_green() elif rcode == "1": colour = Colour.dark_red() return colour
async def define_winner(self, message_reaction, message_author, message): bot = self.ctx.bot if (message_author != bot.user and message_reaction.message.id == message.id and message_reaction.emoji in bot_constants.JOKENPO_PIECES): pc_choice, user_choice = choice( bot_constants.JOKENPO_PIECES), message_reaction.emoji pcwin = user_choice == self.jokenpo_winning_elements[pc_choice] userwin = pc_choice == self.jokenpo_winning_elements[user_choice] embed = Embed() embed.add_field(name='Você escolheu', value=user_choice) embed.add_field(name='O computador escolheu', value=pc_choice) if userwin and not pcwin: embed.title = 'Vencedor' embed.description = 'O vencedor foi você!! Parabéns' embed.colour = Colour.dark_green() elif pcwin and not userwin: embed.title = 'Perdedor' embed.description = 'O computador levou a melhor dessa vez, tende de novo!' embed.colour = Colour.dark_red() else: embed.title = 'Empate' embed.description = 'Mentes brilhantes pensam igual, foi um empate!' embed.colour = Colour.orange() await handler.edit_message(message, logger, embed=embed)
def create_embed(data, parl=0): try: for e in data['Surveys']: if int(data['Surveys'][e]['Parliament_ID']) == parl: last = e break embed = Embed(title='Aktuelle Umfrage ' + data['Parliaments'][str(parl)]['Name'], color=Colour.dark_red()) embed.description = 'Wahl: ' + data['Parliaments'][str(parl)]['Election'] +\ '\nUmfrage von: ' + data['Institutes'][data['Surveys'][last]['Institute_ID']]['Name'] + \ '\nUmfrage im Auftrag von: ' + data['Taskers'][data['Surveys'][last]['Tasker_ID']]['Name'] embed.set_footer(text='Umfrage von: ' + str(data['Surveys'][last]['Date'])) for e, party in enumerate(data['Surveys'][last]['Results']): embed.add_field( name=str(data['Parties'][party]['Name']), value=str(data['Surveys'][last]['Results'][party]) + '%\n', inline=False) except KeyError: SHL.output( "Got an invalid syntax. Perhaps the API is not available or deprecated" ) return except: SHL.output( "Something went wrong while parsing the Embed. Perhaps the API is not available or deprecated" ) return return embed
async def element_color(element): switch = { 'Light': Colour.gold(), 'Dark': Colour.dark_purple(), 'Fire': Colour.dark_red(), 'Water': Colour.dark_blue(), 'Forest': Colour.dark_green() } return switch.get(element)
async def help(ctx): embed = Embed(colour=Colour.dark_red()) embed.set_author(name='Help') embed.add_field( name=bot.command_prefix + 'sam <notification channel> <notification role> <discussion channel>', value= 'Set where to send notifications when a new Manga chapter drops, together with a role that get\'s notified and a channel where discussions can be held.', inline=False) embed.add_field( name=bot.command_prefix + 'saln <notification channel> <notification role> <discussion channel>', value= 'Set where to send notifications when a new Light Novel Volume drops, together with a role that get\'s notified and a channel where discussions can be held.', inline=False) embed.add_field( name=bot.command_prefix + 'sawn <notification channel> <notification role> <discussion channel>', value= 'Set where to send notifications when a new Web Novel chapter drops, together with a role that get\'s notified and a channel where discussions can be held.', inline=False) embed.add_field( name=bot.command_prefix + 'saa <notification channel> <notification role> <discussion channel>', value= 'Set where to send notifications when a new Anime Episode drops, together with a role that get\'s notified and a channel where discussions can be held.', inline=False) embed.add_field(name=bot.command_prefix + 'lac', value='List all set announcement channels.', inline=False) embed.add_field(name=bot.command_prefix + 'dac <ID>', value='Delete an announcement channel with the given ID.', inline=False) embed.add_field(name=bot.command_prefix + 'sfm <feed url>', value='Set Manga rss feed to check for updates.', inline=False) embed.add_field(name=bot.command_prefix + 'sfln <feed url>', value='Set Light Novel rss feed to check for updates.', inline=False) embed.add_field(name=bot.command_prefix + 'sfwn <feed url>', value='Set Web Novel rss feed to check for updates.', inline=False) embed.add_field(name=bot.command_prefix + 'lf', value='List all set feeds.', inline=False) embed.add_field(name=bot.command_prefix + 'df <ID>', value='Delete a feed with the given ID.', inline=False) embed.add_field(name=bot.command_prefix + 'prefix <prefix>', value='Change the prefix for the commands.', inline=False) embed.add_field(name=bot.command_prefix + 'kw <search phrase>', value='Search the kumo wiki and return the post summary.', inline=False) await ctx.send(embed=embed)
async def ban(self, ctx, user: GlobalUserConverter, *, reason: str = ""): """Bans a member from the server. You can provide a user either by their ID or mentioning them. In order to do this, the bot and you must have Ban Member permissions. """ embed = UserEmbed(user) if reason: embed.add_field(name="Reason for Banning", value=reason, inline=False) await ctx.send( "Are you sure you want to ban this user? Should I (m)essage them with the reason for banning? " "(y/m/n)", embed=embed) confirmation = await self.client.wait_for( "message", check=lambda m: m.author == ctx.message.author and m.channel == ctx .channel) ban_with_message = confirmation.content.lower().startswith("m") if not (confirmation.content.lower().startswith("y") or ban_with_message): await ctx.send("Ban aborted!") return if ban_with_message: await ctx.send("What's the message? (Or say `cancel`)") new_message = await self.client.wait_for( "message", check=lambda m: m.author == ctx.message.author and m.channel == ctx.channel) if "cancel" == new_message.content.lower(): await ctx.send("Ban aborted!") return ban_embed = Embed(colour=Colour.dark_red(), title="You have been banned from: {}".format( ctx.guild), description="The admin says:\n\n{}".format( new_message.content)) try: await user.send(embed=ban_embed) except: await ctx.send("I was unable to send a message to that user!") return await _ban_user_process(ctx, user, 0, reason)
async def on_raw_reaction_add(self, payload): request = get_register_request(payload.message_id) if payload.channel_id == REGISTER_REQUESTS_CHANNEL and bool( request) and payload.user_id != self.bot.user.id: channel = await self.bot.fetch_channel(REGISTER_REQUESTS_CHANNEL) message = await channel.fetch_message(payload.message_id) server = self.bot.get_guild(payload.guild_id) mod_member = server.get_member(payload.user_id) player_member = server.get_member(request[1]) required_role = get(server.roles, name=MOD_ROLE) if str( payload.emoji ) == "✅" and required_role.position <= mod_member.top_role.position: Player.add_player(request[0], request[1]) remove_register_request(payload.message_id) await message.clear_reactions() await message.edit( content= f"✅ {mod_member.name} accepted {player_member.mention}'s request for IGN" f" **{request[2]}**", embed=None) try: await success_embed( player_member, f"Your IGN request for **{request[2]}** was approved") except Forbidden: # This means the bot can't DM the user await channel.send( "This user has PMs off, failed to send DM.") elif str( payload.emoji ) == "❌" and required_role.position <= mod_member.top_role.position: remove_register_request(payload.message_id) await message.clear_reactions() await message.edit( content= f"❌ {mod_member.name} denied {player_member.mention}'s request for IGN" f" **{request[2]}**", embed=None) try: await player_member.send(embed=Embed( title="Denied IGN Request", description= f"Your request for IGN **{request[2]}** was denied.", color=Colour.dark_red())) except Forbidden: # This means the bot can't DM the user await channel.send( "This user has PMs off, failed to send DM.")
async def reply(self, ctx: Context, user: User, *, message: str): """ Reply message to User DM. """ # Send the message await user.send(message) # Send back to mod channel embed = Embed(colour=Colour.dark_red()) embed.set_author(name=f"Replied to {user}", icon_url=ctx.author.avatar_url) embed.description = user.id embed.add_field(name="Message:", value=message) await ctx.send(embed=embed) # Delete the comamnd message when It's done. await ctx.message.delete()
async def close(self, ctx: Context, reason: str = None, colour: Colour = Colour.dark_red()) -> None: """Close the menu.""" if ctx.author.id not in self.tasks: return if self.tasks[ctx.author.id]['details']['state'] == 0: return # Preventing double close and Event Bug. self.tasks[ctx.author.id]['details']['state'] = 0 message = self.tasks[ctx.author.id]["info"]["message"] try: await message.clear_reactions() await message.edit(embed=self.close_embed(reason, colour)) except: pass # Ignore all exception, Our task is already done. await sleep(2) # this is a cooldown system. # Can also use try but this is easier. if ctx.author.id in self.tasks: del self.tasks[ctx.author.id]
def embed_tweet(tweet): embed = Embed() embed.type = "rich" embed.color = Colour.dark_red() author = tweet.get('data-author') author_profile = tweet.select('.avatar')[0].get('href') avatar = tweet.select('.avatar img')[0].get('src') embed.title = tweet.select('.messageContent blockquote')[0].get_text() embed.url = CODEX_ROOT + tweet.select('.privateControls a')[0].get('href') embed.timestamp = datetime.datetime.fromtimestamp( int(tweet.select('.privateControls abbr')[0].get('data-time'))) embed.set_author(name=author, url=CODEX_ROOT + author_profile, icon_url=CODEX_ROOT + avatar) return embed
async def handle_user_input_error(self, ctx: Context, e: errors.UserInputError) -> None: if isinstance(e, errors.MissingRequiredArgument): await ctx.send(f":x: **Missing required argument;** `{e.param.name}`") elif isinstance(e, errors.TooManyArguments): await ctx.send(f":x: **Too many arguments;** `{e}`") elif isinstance(e, errors.BadArgument): await ctx.send(f":x: **Bad argument;** `{e}`") elif isinstance(e, errors.BadUnionArgument): await ctx.send(f":x: **Bad argument;** `{e}`\n```py\n{e.errors[-1]}\n```") elif isinstance(e, errors.ArgumentParsingError): await ctx.send(f":x: **Argument parsing error;** `{e}`") else: embed = Embed( title = "Input error", description = "Something about your input seems off. Check the arguments and try again.", colour = Colour.dark_red(), timestamp = ctx.message.created_at ) await ctx.send(embed=embed)
async def detect_haiku(self, message): if message.author == self.bot.user: return words = self.get_words(message) i = 0 lines = [] for target_syllables in [5, 7, 5]: line = self.get_haiku_line(words[i:], target_syllables) if line is not None: i += len(line) lines.append(" ".join(line)) else: return # it's not a haiku if i == len(words): haiku = "\n".join(lines) embed = Embed(colour=Colour.dark_red()).add_field( name=":cherry_blossom: **Haiku Detected** :cherry_blossom:", value=f"_{haiku}_") await message.channel.send(embed=embed)
async def eval_command(self, ctx: Context, *, code: str = None) -> None: if not code: await ctx.send(":x: Invalid Args, Code is needed") return embed = Embed( description= "This command will only run the code for 10 seconds; futher than that will be terminate!" ) embed.set_author(name="Executing Code...") m = await ctx.send(embed=embed) owner = await self.bot.is_owner(ctx.author) ignore = True if owner else False log.debug(f"Eval command; Ignore black list: {ignore}") code = self.prepare_input(code, ignore) if code == "Black list word found!": embed = Embed( colour=Colour.dark_red(), description= "Found black-listed key word in your code!\nYour Job has been canceled." ) embed.set_author(name="Execution Terminated") await m.edit(embed=embed) return log.trace( f"Eval command: {ctx.author}({ctx.author.id}) with code:\n{code}") result = await post_eval(code, ctx.author.id) output, rcode = result output = self.format_output(output) embed = Embed(title=f"Exit code: {rcode}", colour=self.predict_colour(str(rcode))) value = f"```python\n\n{output}\n```" embed.add_field(name="Full Output", value=value) await m.edit(embed=embed)
async def anime(ctx, *, message=" "): jikan = Jikan() if message == " ": await ctx.send("Please enter an anime: ?anime <anime name>") else: temp_lst = [] new_dict = jikan.search('anime', query=message) counter = 1 for info in new_dict['results']: embed_anime = Embed(title="Search", color=Colour.dark_red()) embed_anime.add_field(name="Title", value=info['title'], inline=False) embed_anime.add_field(name="Score", value=info['score'], inline=False) embed_anime.add_field(name="Synopsis", value=info['synopsis'], inline=False) if info['airing'] is True: embed_anime.add_field(name="Airing Now", value="Yes", inline=False) else: embed_anime.add_field(name="Airing Now", value="No", inline=False) embed_anime.add_field(name="More info", value=info['url'], inline=False) embed_anime.set_thumbnail(url=info['image_url']) embed_anime.set_footer(text="Time: " + today_date.strftime("%m/%d/%Y, %H:%M:%S")) temp_lst.append(embed_anime) counter += 1 if counter == 11: break page_cont = BotEmbedPaginator(ctx, temp_lst) await page_cont.run()
def embed_thread(thread): embed = Embed() embed.type = "rich" embed.color = Colour.dark_red() author = thread.get('data-author') author_profile = thread.select('.avatarContainer a')[0].get('href') avatar = thread.select('.avatarContainer img')[0].get('src') thread_url = thread.select('.PreviewTooltip')[0].get('href') thread_title = thread.select('.PreviewTooltip')[0].get_text() last_post_date = thread.select('abbr.DateTime')[0].get('data-time') last_post_date = datetime.datetime.fromtimestamp(int(last_post_date)) forum = thread.select('.forumLink')[0].get_text() replies = thread.select('.major dd')[0].get_text() views = thread.select('.minor dd')[0].get_text() last_post_author = thread.select('.lastPostInfo a')[0].get_text() embed.title = thread_title embed.url = CODEX_ROOT + thread_url embed.timestamp = last_post_date embed.set_author(name=author, url=CODEX_ROOT + author_profile, icon_url=CODEX_ROOT + avatar) embed.add_field(name='Forum', value=forum) embed.add_field(name='Last message', value=last_post_author) embed.add_field(name='Replies', value=replies, inline=True) embed.add_field(name='Views', value=views, inline=True) return embed
async def logBan(guild, user): r = DictionaryReader() logChannel = client.get_channel(int(r.moderationLogChannel())) if not guild: return bannedBy = guild.me banReason = '' # Checks if the bot can see the audit log if guild.me.guild_permissions.view_audit_log: auditLogs = guild.audit_logs(limit=100, action=discord.AuditLogAction.ban) logs = await auditLogs.flatten() banLog = None for log in logs: if log.target.id == user.id: banLog = log break bannedBy = banLog.user if banLog else bannedBy banReason = banLog.reason emb = Embed() emb.title = 'User {0.name} Banned'.format(user) emb.type = 'rich' emb.colour = Colour.dark_red() emb.set_footer(text='Timestamp: ' + time.strftime("%Y-%m-%d %H:%M:%S")) emb.set_author(name=user.name, icon_url=user.avatar_url) emb.add_field(name='Banned by', value=bannedBy.name) if not guild.me.guild_permissions.view_audit_log: emb.add_field(name='Warning', value='Bot cant see AuditLog') emb.add_field(name='Reason', value=banReason, inline=False) await logChannel.send(embed=emb)
async def error_embed(ctx, description): embed = Embed(title="Error ❌", description=description, color=Colour.dark_red()) message = await ctx.send(embed=embed) return message
from bot.data import DataManager from bot.interpreter import Interpreter log = logging.getLogger("bot") __author__ = 'Gareth Coles' GIST_CREATE_URL = "https://api.github.com/gists" GIST_URL = "https://api.github.com/gists/{}" GIST_REGEX = re.compile(r"gist:[a-z0-9]+") LOG_COLOURS = { logging.INFO: Colour.blue(), logging.WARNING: Colour.gold(), logging.ERROR: Colour.red(), logging.CRITICAL: Colour.dark_red() } CONFIG_KEY_DESCRIPTIONS = { "control_chars": "Characters that all commands must be prefixed with. You can always mention me as well instead.", "info_channel": "ID for the currently-configured info channel. Use the `setup` command if you want to change this.", "notes_channel": "ID for the currently-configured notes channel. Use the `setup` command if you want to change this." } WELCOME_MESSAGE = [ """ Hello! I was invited to this server to manage an info-channel.
"https://cdn.discordapp.com/attachments/700683544103747594/711013623257890857/nivelian.png", "neutral": "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/rocket_1f680.png", "void": "https://cdn.discordapp.com/attachments/700683544103747594/711013699841687602/void.png" } errorIcon = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/exclamation-mark_2757.png" winIcon = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/trophy_1f3c6.png" rocketIcon = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/rocket_1f680.png" # colours to use in faction-related embed strips factionColours = { "terran": Colour.gold(), "vossk": Colour.dark_green(), "midorian": Colour.dark_red(), "nivelian": Colour.dark_blue(), "neutral": Colour.purple() } # Data representing all ship items in the game. These are used to create bbShip objects, # which are stored in builtInShipObjs in a similar dict format. # Ships to not have tech levels in GOF2, so tech levels will be automaticaly generated # for the sake of the bot during bot.on_ready. builtInShipData = {} # Data representing all module items in the game. These are used to create bbModule objects, # which are stored in builtInModuleObjs in a similar dict format. builtInModuleData = {} # Data representing all primary weapon items in the game. These are used to create bbWeapon objects,
async def create_list_pages(bot, ctx, title: str, info: list, if_empty: str = "Empty List", sep: str = "\n", elements_per_page: int = 10, thumbnails=None, can_be_reversed=False, random_item=False): if not info: await ctx.send(embed=Embed( title=title, description=if_empty, colour=Colour.dark_red())) return contents = [] num_pages = ceil(len(info) / elements_per_page) page = "" current_page = 1 for index, value in enumerate(info): page = page + str(value + sep) if not (index + 1) % elements_per_page: contents.append(page) page = "" contents.append(page) embed = Embed(title=title, description=contents[current_page - 1], colour=Colour.dark_purple()) embed.set_footer(text=f"Page {current_page}/{num_pages}") if thumbnails: if len(thumbnails) == 1: embed.set_thumbnail(url=thumbnails[0]) else: embed.set_thumbnail(url=thumbnails[current_page - 1]) buttons = [] if num_pages != 1: buttons.append( manage_components.create_button(ButtonStyle.primary, emoji="◀")) buttons.append( manage_components.create_button(ButtonStyle.primary, emoji="▶")) if can_be_reversed: buttons.append( manage_components.create_button(ButtonStyle.secondary, label="Reverse")) if random_item: buttons.append( manage_components.create_button(ButtonStyle.secondary, label="Shuffle")) buttons.append( manage_components.create_button(ButtonStyle.danger, label="Close")) action_row = manage_components.create_actionrow(*buttons) message = await ctx.send(embed=embed, components=[action_row]) while True: try: button_context: ComponentContext = await manage_components.wait_for_component( bot, timeout=120, components=action_row) if button_context.author.id != ctx.author.id: await button_context.send( "These buttons belong to someone else - try using the command yourself", hidden=True) continue except TimeoutError: embed.set_footer( text=f"Page {current_page}/{num_pages} (Timed Out)") await message.edit(embed=embed, components=None) break if "emoji" in button_context.component.keys(): if button_context.component["emoji"]["name"] == "▶": if current_page != num_pages: current_page += 1 embed = Embed(title=title, description=contents[current_page - 1], colour=Colour.dark_purple()) elif current_page == num_pages and num_pages != 1: # Jump from last page to first page current_page = 1 embed = Embed(title=title, description=contents[current_page - 1], colour=Colour.dark_purple()) elif button_context.component["emoji"]["name"] == "◀": if current_page == 1 and num_pages != 1: # Jump from first page to last page current_page = num_pages embed = Embed(title=title, description=contents[current_page - 1], colour=Colour.dark_purple()) elif current_page > 1: current_page -= 1 embed = Embed(title=title, description=contents[current_page - 1], colour=Colour.dark_purple()) if thumbnails: if len(thumbnails) == 1: embed.set_thumbnail(url=thumbnails[0]) else: embed.set_thumbnail(url=thumbnails[current_page - 1]) embed.set_footer(text=f"Page {current_page}/{num_pages}") await button_context.edit_origin(embed=embed) elif "label" in button_context.component.keys(): if button_context.component[ "label"] == "Reverse" and can_be_reversed: info.reverse() contents = [] num_pages = ceil(len(info) / elements_per_page) page = "" for index, value in enumerate(info): page = page + str(value + sep) if not (index + 1) % elements_per_page: contents.append(page) page = "" contents.append(page) current_page = 1 embed = Embed(title=title, description=contents[current_page - 1], colour=Colour.dark_purple()) if thumbnails: if len(thumbnails) == 1: embed.set_thumbnail(url=thumbnails[0]) else: embed.set_thumbnail(url=thumbnails[current_page - 1]) embed.set_footer(text=f"Page {current_page}/{num_pages}") await button_context.edit_origin(embed=embed) elif button_context.component["label"] == "Shuffle" and random_item: embed = Embed(title=title, description=choice(info), colour=Colour.dark_purple()) await button_context.edit_origin(embed=embed) elif button_context.component["label"] == "Close": await message.edit(content="Closing message..", embed=None, components=None) await button_context.edit_origin(content="List Pages Closed") # This requires 2 requests, one to actually clear the embed and components and another to show to discord the interaction succeeded # Hopefully a change is made to the slash lib so it supports removing the embed/components break
async def on_message(message): if message.author == client.user: return # hello command elif message.content.startswith('*hello'): await message.channel.send("Hello <@" + str(message.author.id) + "> ! " + ":slight_smile:") # help command* elif message.content.startswith('*help'): embed = discord.Embed(title='Help', description='help for you :slight_smile:', colour=Colour.blue()) embed.add_field(name="For server admins (more info *info_server_admins)", value="nothing(yet)", inline=False) embed.add_field(name="not nice stuff (more info *info_not_nice)", value="`roast` `kill` `insane_detection`", inline=False) embed.add_field(name="Miscellaneous (more info *info_miscellaneous)", value="`coinflip` `hello` `credits` `hi bot`(creators only)", inline=False) embed.add_field(name="epic gifs (more info *info_gifs)", value="`table_flip` `fish_artillery` `nani`", inline=False) embed.add_field(name="made by SunnyJimBob#7082 ever since 07/27/2020", value="_ ", inline=False) await message.channel.send(message.channel, embed=embed) # more info about not nice stuff elif message.content.startswith("*info_not_nice"): embed = discord.Embed(title="More info about not nice stuff", description='info for you :slight_smile:', colour=Colour.red()) embed.add_field(name="roast", value="*roast @user will roast anyone you put after *roast", inline=False) embed.add_field(name="kill", value="*kill @user will make anyone you put after *kill die in a funny way", inline=False) embed.add_field(name="insane_detection", value="*insane_detection tells you how sane you are") await message.channel.send(message.channel, embed=embed) # more info about Miscellaneous elif message.content.startswith('*info_miscellaneous'): embed = discord.Embed(title='More info about miscellaneous', description='help for you :slight_smile:', colour=Colour.gold()) embed.add_field(name="hello", value="*hello makes the bot say hello back to you", inline=False) embed.add_field(name="coinflip", value="*coinflip randomly chooses between heads and tails ",inline=False) embed.add_field(name="credits",value="*credits gives you the list of people who worked on this bot", inline=False) embed.add_field(name="hi bot",value="only for creators",inline=False) await message.channel.send(embed=embed) # more info about gifs elif message.content.startswith('*info_gifs'): embed = discord.Embed(title="more info about gifs", description='info for you :slight_smile:', colour=Colour.green()) embed.add_field( name="*table_flip", value="will give you a table flip gif (credit to https://tenor.com/view/table-flip-machine-kaomoji-gif-17427776)", inline=False) embed.add_field( name="*fish_artillery", value="will give you a gif of a fish cannon (credit to https://tenor.com/view/fishy-explosion-human-fish-cannon-gif-17822939)", inline=False) embed.add_field( name="*nani", value=" will give you a nani gif (credit to https://media.giphy.com/media/1NVugSXiJGJZvWMOud/giphy.gif)", inline=False) await message.channel.send(message.channel, embed=embed) # coinflip elif message.content.startswith('*coinflip'): ok = random.randint(1, 100) if ok > 50: text = "heads" else: text = "tails" await message.channel.send(text) # credits elif message.content.startswith('*credits'): embed = discord.Embed(title='Credits', colour=Colour.blue()) embed.add_field(name="creator", value="SunnyJimBob#7082", inline=False) embed.add_field(name="contributor", value="Meow.#6462", inline=False) embed.add_field(name="sponsors", value="None(yet)", inline=False) await message.channel.send(message.channel, embed=embed) # hi bot elif message.content.startswith('*hi bot'): if str(message.author) == "SunnyJimBob#7082": await message.channel.send("hello creator") else: await message.channel.send("***ew your a normie, not a creator*** :rage: ") # gifs elif message.content.startswith('*table_flip'): await message.channel.send("https://tenor.com/view/table-flip-machine-kaomoji-gif-17427776") elif message.content.startswith('*fish_artillery'): await message.channel.send("https://tenor.com/view/fishy-explosion-human-fish-cannon-gif-17822939") elif message.content.startswith('*nani'): await message.channel.send("https://media.giphy.com/media/1NVugSXiJGJZvWMOud/giphy.gif") # insane_detection elif message.content.startswith('*insane_detection'): sane = random.randint(1, 100) if sane > 50: await message.channel.send("<@"+str(message.author.id) + ">") embed = discord.Embed(title='Your insane!', colour=Colour.dark_red()) embed.add_field(name="you are " + str(sane) + "% insane", value=":zany_face:") embed.add_field(name="Should you see a doctor?", value="Um duh your insane!!!", inline=False) elif sane < 50: message.channel.send("<@"+str(message.author.id)+">") embed = discord.Embed(title='Your sane!', colour=Colour.dark_blue()) embed.add_field(name="you are " + str(sane) + "% insane", value=":slight_smile:") embed.add_field(name="Should you see a doctor?", value="No, but you should still get it checked", inline=False) await message.channel.send(message.channel, embed=embed) # roast elif message.content.startswith('*roast'): hi = random.randint(1, 7) if hi == 1: await message.channel.send('Mirrors cant talk, luckly for you, they cant laugh either :rofl:') elif hi == 2: await message.channel.send('Some day youll go far... and i hope you stay there :rofl:') elif hi == 3: await message.channel.send('If laughter is the best medicine, your face must be curing the world. :rofl:') elif hi == 4: await message.channel.send( 'When i see your face theres not a thing i would change... except the direction i was walking in :rofl:') elif hi == 5: await message.channel.send('Hey, you have something on your chin... no, the 3rd one down :rofl:') elif hi == 6: await message.channel.send('you :rofl:') elif hi == 7: await message.channel.send('Everyone when you fall: OMG is the floor ok?')
async def register(self, ctx, minecraft_username=""): """ Registers Minecraft username to Discord. Required to sign up for PUGs. Usage: register <minecraft_username> Example: register Ninsanity """ if not minecraft_username: embed = Embed(title="Error ❌", description="Missing argument <minecraft_username>", color=Colour.dark_red()) embed.add_field(name="Example", value="-register Ninsanity") await ctx.send(embed=embed) return uuid = MojangAPI.get_uuid(minecraft_username) if uuid: condition = Player.player_check(uuid, ctx.author.id) if not condition: if check_user_requests(ctx.author.id): await error_embed( ctx, "You have already submitted a register request") else: request_channel = self.bot.get_channel( REGISTER_REQUESTS_CHANNEL) embed = Embed( title=f"Register Request: {minecraft_username}", description= f"React below to verify {ctx.author.mention}", colour=Colour.dark_purple()) embed.set_thumbnail( url=f"https://cravatar.eu/helmavatar/{uuid}/128.png") message = await request_channel.send(embed=embed) await message.add_reaction("✅") await message.add_reaction("❌") if add_register_request(uuid, ctx.author.id, minecraft_username, message.id): await ctx.send(embed=Embed( title="Registration Pending", description= f"Requested to register **{minecraft_username}**" f" to {ctx.author.mention}", color=Colour.dark_purple())) else: await error_embed( ctx, "There was an error storing your register request. Contact a PUG Dev" ) elif condition == 1: await ctx.send(embed=Embed( title="Error ❌", description= f"**{minecraft_username}** is already registered", color=Colour.dark_red())) else: await ctx.send(embed=Embed( title="Error ❌", description=f"{ctx.author.mention} is already registered", color=Colour.dark_red())) else: await ctx.send(embed=Embed( title="Error ❌", description=f"**{minecraft_username}** does not exist", color=Colour.dark_red()))
def close_embed(reason: str, colour: Colour = Colour.dark_red()) -> Embed: """Create a Closed Embed.""" embed = Embed(colour = colour) embed.title = "[Closed Menu]" if reason is None else reason return embed
async def editmaps(self, ctx, operation="", map_id: int = 0): if not has_permissions(ctx, ADMIN_ROLE): await ctx.send("You do not have sufficient permissions to perform this command", hidden=True) return False def check(m): return m.author == ctx.author and m.channel == ctx.channel map_id = int(map_id) if operation == "add": with open("utils/maps.json", "r+") as file: data = load(file) for k, v in data.items(): if int(v) == map_id: return await error_embed(ctx, "Map already exists") embed = Embed(title="Adding map to database", description="Enter the name of the map", color=Colour.dark_purple()) embed.set_footer(text="Type \"cancel\" to cancel") message = await ctx.send(embed=embed) response = await self.bot.wait_for("message", check=check) if not response.content: return await error_embed(ctx, "Not a string") if response.content.lower() == "cancel": return await ctx.send(embed=Embed(description="❌ Adding map cancelled", color=Colour.dark_red())) name = response.content embed = Embed(title="Adding map to database", description="Would you like to add an image?", color=Colour.dark_purple()) embed.set_footer(text="Type \"y/yes\" to add map with an image\nType \"n/no\" to add map without an image\nType \"cancel\" to cancel map adding") message = await ctx.send(embed=embed) response = await self.bot.wait_for("message", check=check) if response.content.lower() in ["done", "finished", "yes", "y"]: #add map if y embed = Embed(title="Adding map to database", description="This can be a direct upload, or a direct link to an image (not supported yet)", color=Colour.dark_purple()) message = await ctx.send(embed=embed) response = await self.bot.wait_for("message", check=check) #Send image here if not response.attachments: return await error_embed(ctx, "No image attached") if not response.attachments[0].content_type.startswith("image"): return await error_embed(ctx, "File uploaded is not image") attachment = response.attachments[0] embed = Embed(title="Confirm addition (y/n)", description=f"Are you sure you want to add {name} ({map_id})?", color=Colour.dark_purple()) embed.set_image(url=attachment.url) message = await ctx.send(embed=embed) response = await self.bot.wait_for("message", check=check) is_correct = response.content.lower() == "y" or response.content.lower() == "yes" if not is_correct: return await ctx.send(embed=Embed(description="❌ Adding map cancelled", color=Colour.dark_red())) await attachment.save(f"assets/map_screenshots/{map_id}.jpg") compress(f"assets/map_screenshots/{map_id}.jpg") await response_embed(ctx, "✅ Map added", "") elif response.content.lower() in ["no", "n"]: await response_embed(ctx, "✅ Map added", "") elif response.content.lower() == "cancel": return await ctx.send(embed=Embed(description="❌ Adding map cancelled", color=Colour.dark_red())) else: return await ctx.send(embed=Embed(description="❌ Adding map cancelled, please type yes, no or cancel next time", color=Colour.dark_red())) new_data = {name: map_id} data = None with open("utils/maps.json", "r+") as file: data = load(file) data.update(new_data) with open("utils/maps.json", "w") as file: dump(data, file, sort_keys=True, indent=4) elif operation == "del": name = None with open("utils/maps.json", "r+") as file: data = load(file) for k, v in data.items(): if int(v) == map_id: name = k data.pop(k) break if name is None: return await error_embed(ctx, "Map not found") try: file = File(f"assets/map_screenshots/{map_id}.jpg", filename=f"{map_id}.png") embed = Embed(file=file, title="Confirm deletion (y/n)", description=f"Are you sure you want to delete **{name}** ({map_id})?", color=Colour.dark_purple()) embed.set_image(url=f"attachment://{map_id}.png") message = await ctx.send(file=file, embed=embed) except FileNotFoundError: embed = Embed(title="Confirm deletion (y/n)", description=f"Are you sure you want to delete **{name}** ({map_id})?", color=Colour.dark_purple()) message = await ctx.send(embed=embed) response = await self.bot.wait_for("message", check=check) is_correct = response.content.lower() == "y" or response.content.lower() == "yes" if not is_correct: return await ctx.send(embed=Embed(description="❌ Deleting map cancelled", color=Colour.dark_red())) with open("utils/maps.json", "w") as file: dump(data,file, sort_keys=True, indent=4) if os.path.exists(f"assets/map_screenshots/{map_id}.jpg"): os.remove(f"assets/map_screenshots/{map_id}.jpg") return await response_embed(ctx, "✅ Map deleted", "")