async def go(self, ctx, location=None): with open(profiles, "r") as f: profile = json.load(f)[str(ctx.author.id)] places = profile["places"] if location is None: components = [] for place in places: components.append( ActionRow( Button(label=place.replace("_", " ").capitalize(), style=ButtonStyle.blurple, custom_id=place))) em = discord.Embed( title="Location to Go", description= "Where do you want to go ?\nClick on button to go to a place.", colour=discord.Colour.blue()) em.set_footer(text="Use command location to know your location", url=ctx.author.url) msg = await ctx.send(embed=em, components=components) try: waiter = msg.wait_for_button_click( check=lambda x: x.author.id == ctx.author.id, timeout=30) except asyncio.TimeoutError: msg.edit(embed=discord.Embed( title="Interaction Ended", description="***: )***\nThanks for using Minecord", colour=discord.Colour.light_grey())) return location = waiter.clicked_button_cutom_id location = await game.get_id(location) location_name = location.replace("_", " ").capitalize() await ctx.send(f"You went to {location_name}", file=open(f"cogs/assets/{location}.png")) await game.location(location)
async def button(self, ctx): # Make a row of buttons row_of_buttons = ActionRow( Button(style=ButtonStyle.green, label="Green button", custom_id="green"), Button(style=ButtonStyle.red, label="Red button", custom_id="red")) # Send a message with buttons msg = await ctx.send("This message has no buttons!") await ctx.send("done") await msg.edit(content="This message has buttons!", components=[row_of_buttons]) await ctx.send("done 2") on_click = msg.create_click_listener(timeout=60) @on_click.matching_id("red") async def on_test_button(inter): # This function only works if the author presses the button # Becase otherwise the previous decorator cancels this one await inter.reply("You've clicked the red button!") @on_click.matching_id("green") async def on_test_button(inter): # This function only works if the author presses the button # Becase otherwise the previous decorator cancels this one await inter.message.edit(components=[]) await inter.reply("You've clicked the green button!") @on_click.timeout async def on_timeout(): await msg.edit(content=msg.content.replace("has", "had"), components=[])
async def help_timeout(): buttons = ActionRow( Button(style=ButtonStyle.green, label="Information", emoji="❕", disabled=True), Button(style=ButtonStyle.blurple, label="FAQ", emoji="❔", disabled=True), Button(style=ButtonStyle.secondary, label="Characters", emoji="🧑", disabled=True), ) await msg.edit(components=[buttons])
async def build(self, ctx, monument=None): if not await is_over_channel(ctx): return build = Button(label="Build", style=ButtonStyle.green, custom_id="build") build_disabled = Button(label="Build", style=ButtonStyle.red, custom_id="build_disabled", disabled=True) def check(m): return m.author.id == ctx.author.id with open(info, "r") as f: data = json.load(f) if monument is None: target = "last" #Creating Button back = Button(label="Back", style=ButtonStyle.grey, custom_id="back") forward = Button(label="»", style=ButtonStyle.blurple, custom_id="forward") backward = Button(label="«", style=ButtonStyle.blurple, custom_id="backward") forward_disabled = Button(label="»", style=ButtonStyle.blurple, custom_id="forward_disabled", disabled=True) backward_disabled = Button(label="«", style=ButtonStyle.blurple, custom_id="backward_disabled", disabled=True) em = discord.Embed(title="Build Command", description='''Items to build''', colour=discord.Colour.green()) em.add_field( name="Houses", value= "**Level 1 House - Dirt House**\n id - ```dirt```\n**Level 2 House - Wooden House**\n id - ```wooden```\n**Level 3 House - Stone Mansion**\n id - ```stone```\n**Level 4 House - Modern Apartment**\n id - ```modern```\n**Level 5 House - Castle-e-Minecraft**\n id - ```castle```" ) em.set_footer(icon_url=ctx.author.avatar_url, text="Use command build <item id> to build an item.") msg = await ctx.send( embed=em, components=[ActionRow(backward_disabled, build, forward)]) no_button_check = False button = "" while True: try: if not no_button_check: waiter = await msg.wait_for_button_click(check=check, timeout=60.0) button = waiter.clicked_button.label no_button_check = False except asyncio.TimeoutError: print("Exit") await msg.edit(embed=em, components=[ ActionRow(backward_disabled, build_disabled, forward_disabled) ]) return if button == "«": if target == "first": target = "middle" em.set_field_at( 0, name="Farm", value= "**Farm Level 1 - Miniature Farm**\n id - ```mini```\n**Farm Level 2 - Smol Farm**\n id - ```smol```\n**Farm Level 3 - Normal Farm**\n id - ```normal```\n**Farm Level 4 - Big Farm**\n id - ```big```\n**Farm Level 5 - Giant Farm**\n id - ```giant```" ) await msg.edit( embed=em, components=[ActionRow(backward, build, forward)]) else: target = "last" em.set_field_at( 0, name="Houses", value= "**Level 1 House - Dirt House**\n id - ```dirt```\n**Level 2 House - Wooden House**\n id - ```wooden```\n**Level 3 House - Stone Mansion**\n id - ```stone```\n**Level 4 House - Modern Apartment**\n id - ```modern```\n**Level 5 House - Castle-e-Minecraft**\n id - ```castle```" ) await msg.edit(embed=em, components=[ ActionRow(backward_disabled, build, forward) ]) elif button == "Build": em.description = "What do you want to Build ?\nClick on the button to build an item." em.remove_field(index=0) async def get_buttons(label, ids): buttons = [] j = 0 for i in label: builds = data["build"][ids[j]] if target != "middle": for key in builds: colour = await game.inv_searcher( ctx, key, value=builds[key]) if colour is False: break else: colour = await game.build_searcher( ctx, builds[0]) and await game.inv_searcher( ctx, builds[1], data["tools"][builds[1]]) if colour: colour = ButtonStyle.green else: colour = ButtonStyle.red button = Button(label=i, style=colour, custom_id=ids[j]) j += 1 buttons.append(button) return buttons buttons = [] if target == "last": labels = [ "House Level 1 - Dirt House", "House Level 2 - Wooden House", "House Level 3 - Stone Mansion", "House Level 4 - Modern Apartment", "House Level 5 - Castle-e-Minecraft" ] ids = [ "dirt_house", "wooden_house", "stone_mansion", "modern_apartment", "castle-e-minecraft" ] buttons = await get_buttons(labels, ids) await msg.edit(embed=em, components=[ ActionRow(buttons[0], buttons[1], buttons[2], buttons[3], buttons[4]), ActionRow(back) ]) elif target == "first": buttons = await get_buttons( ["Xp Farm", "Shaft Mine", "Nether Portal"], ["xp_farm", "shaft_mine", "nether_portal"]) await msg.edit(embed=em, components=[ ActionRow(buttons[0], buttons[1], buttons[2], back) ]) else: label = [ "Farm Level 1 - Miniature Farm", "Farm Level 2 - Smol Farm", "Farm Level 3 - Normal Farm", "Farm Level 4 - Big Farm", "Farm Level 5 - Giant Farm" ] ids = [ "miniature_farm", "smol_farm", "normal_farm", "big_farm", "giant_farm" ] buttons = await get_buttons(label, ids) await msg.edit(embed=em, components=[ ActionRow( buttons[0], buttons[1], buttons[2], buttons[3], buttons[4], ), ActionRow(back) ]) try: waiter = await msg.wait_for_button_click(check=check, timeout=60.0) buttons = waiter.clicked_button.custom_id if button != "back": build_cmd = self.client.get_command("build") await ctx.invoke(build_cmd, buttons) else: button = "«" no_button_check = True em.add_field(name="Hi", value="Bye") continue except asyncio.TimeoutError: print("Exit") await msg.edit(embed=em, components=[ ActionRow(backward_disabled, build_disabled, forward_disabled) ]) return else: if target == "last": target = "middle" em.set_field_at( 0, name="Farm", value= "**Farm Level 1 - Miniature Farm**\n id - ```mini```\n**Farm Level 2 - Smol Farm**\n id - ```smol```\n**Farm Level 3 - Normal Farm**\n id - ```normal```\n**Farm Level 4 - Big Farm**\n id - ```big```\n**Farm Level 5 - Giant Farm**\n id - ```giant```" ) await msg.edit( embed=em, components=[ActionRow(backward, build, forward)]) else: target = "first" em.set_field_at( 0, name="Other", value= "**Nether Portal**\n id - ```nether```\n**Xp Farm**\n id - ```xp```\n**Shaft Mine**\n id - ```shaft```" ) await msg.edit(embed=em, components=[ ActionRow(backward, build, forward_disabled) ]) else: monument = await game.get_id(monument) if monument is None: await ctx.send( "The item you are looking for does not even exists lol") return builds = data["build"][monument] farms = [ "miniature_farm", "smol_farm", "normal_farm", "big_farm", "giant_farm" ] can_build = True em = discord.Embed(title=monument.replace("_", " ").capitalize(), description="", colour=discord.Colour.green()) description = "" if monument in farms: farm_name = builds[0].replace("_", " ").capitalize() if await game.build_searcher(ctx, builds[0]): description += f":white_check_mark: {farm_name}\n" else: can_build = False description += f":x: {farm_name}\n" durability = data["tools"][builds[1]] name = builds[1].replace("_", " ").capitalize() if game.inv_searcher(ctx, builds[1], durability): description += f"\n:white_check_mark: {name} : {durability}\n" else: can_build = False description += f"\n:x: {name} : {durability}\n" else: for building in builds: name = building.replace("_", " ").capitalize() if await game.inv_searcher(ctx, building, builds[building]): description += f":white_check_mark: {name} : {builds[building]}\n" else: can_build = False description += f":x: {name} : {builds[building]}\n" em.description = description if can_build: msg = await ctx.send(embed=em, components=[ ActionRow( Button(label="End Interaction", style=ButtonStyle.grey, custom_id="end"), build) ]) else: em.colour = discord.Colour.red() msg = await ctx.send(embed=em, components=[ ActionRow( Button(label="End Interaction", style=ButtonStyle.grey, custom_id="end"), build_disabled) ]) while True: try: waiter = await msg.wait_for_button_click(check=check, timeout=60.0) if waiter.clicked_button.label == "Build": pass else: raise asyncio.TimeoutError except asyncio.TimeoutError: em.title = "Interaction Ended" em.description = "***: )***\nThanks for using Minecord" await msg.edit(embed=em, components=[ ActionRow( Button(label="End Interaction", style=ButtonStyle.grey, custom_id="end", disabled=True), build_disabled) ])
async def start(self, start_index=0): # allow menu to start on a page other than 0 if start_index < 0 or start_index >= len(self._ButtonsMenu__pages): start_index = 0 # before the menu starts, ensure the "components" kwarg is implemented inside the `_ctx.send` method. If it's missing, raise an error (the menu cannot function without it) send_info = inspect.getfullargspec(self._ctx.send) if 'components' not in send_info.kwonlyargs: raise MissingSetting( 'The "components" kwarg is missing from the .send() method. Did you forget to initialize the menu first using static method ButtonsMenu.initialize(...)?' ) # ensure at least 1 page exists before starting the menu if self._menu_type in (ButtonsMenu.TypeEmbed, ButtonsMenu.TypeText ) and not self._ButtonsMenu__pages: raise NoPages( "You cannot start a ButtonsMenu when you haven't added any pages" ) # ensure only valid menu types have been set if self._menu_type not in (ButtonsMenu.TypeEmbed, ButtonsMenu.TypeEmbedDynamic, ButtonsMenu.TypeText): raise ButtonsMenuException('ButtonsMenu menu_type not recognized') # add page (normal menu) if self._menu_type == ButtonsMenu.TypeEmbed: self._refresh_page_director_info(ButtonsMenu.TypeEmbed, self._ButtonsMenu__pages) self._msg = await self._ctx.send( embed=self._ButtonsMenu__pages[start_index], components=[ActionRow(*self._row_of_buttons) ]) # allowed_mentions not needed in embeds # add row (dynamic menu) elif self._menu_type == ButtonsMenu.TypeEmbedDynamic: for data_clump in self._chunks(self._dynamic_data_builder, self.__rows_requested): joined_data = '\n'.join(data_clump) if len(joined_data) <= 2000: possible_block = f"```{self.wrap_in_codeblock}\n{joined_data}```" embed = discord.Embed( ) if self.custom_embed is None else self.custom_embed.copy( ) embed.description = joined_data if not self.wrap_in_codeblock else possible_block self._ButtonsMenu__pages.append(embed) else: raise DescriptionOversized( 'With the amount of data that was recieved, the embed description is over discords size limit. Lower the amount of "rows_requested" to solve this problem' ) else: # set the main/last pages if any if any((self._main_page_contents, self._last_page_contents)): self._ButtonsMenu__pages = collections.deque( self._ButtonsMenu__pages) if self._main_page_contents: self._main_page_contents.reverse() self._ButtonsMenu__pages.extendleft( self._main_page_contents) if self._last_page_contents: self._ButtonsMenu__pages.extend( self._last_page_contents) self._refresh_page_director_info(ButtonsMenu.TypeEmbedDynamic, self._ButtonsMenu__pages) # make sure data has been added to create at least 1 page if not self._ButtonsMenu__pages: raise NoPages( 'You cannot start a ButtonsMenu when no data has been added' ) self._msg = await self._ctx.send( embed=self._ButtonsMenu__pages[start_index], components=[ActionRow(*self._row_of_buttons) ]) # allowed_mentions not needed in embeds # add page (text menu) else: self._refresh_page_director_info(ButtonsMenu.TypeText, self._ButtonsMenu__pages) self._msg = await self._ctx.send( content=self._ButtonsMenu__pages[start_index], components=[ActionRow(*self._row_of_buttons)], allowed_mentions=self.allowed_mentions) self._pc = _PageController(self._ButtonsMenu__pages) self._pc.index = start_index self._is_running = True self._main_session_task = asyncio.get_event_loop().create_task( self._execute_interactive_session()) self._main_session_task.add_done_callback(self._done_callback)
def interface_init(self): self.bj_player_row = ActionRow.from_dict( self.game.embed_data['bj_player_row']) self.create_other_players_fields() self.setup_callbacks()
def interface_init(self): """interface related initializations""" self.bj_wager_row = ActionRow.from_dict( self.game.embed_data['bj_wager_row']) self.setup_callbacks()
async def brawl(self, ctx): embed=discord.Embed(title="TCR ***BRAWL*** Version 1.0.0", description="TCR Brawl is a turn-based fighting game written in Python and playable via a Discord bot. It includes all of your" " favorite TCR members and former TCR members.", color=discord.Color.random()) embed.add_field(name="How to Play:", value="Grab a friend and take a bot channel. Use the `brawl battle` command to get started! The `battle` command has two aliases," " `fight` and `start`. You will be prompted to pick a character, then the game will begin! If you want info on a character before playing, use `brawl info`.", inline=False) embed.add_field(name="All Commands:", value="`brawl`, `info`, `help`, `faq`.", inline=False) embed.add_field(name="Our FAQ", value="You may want to suggest a character, or you don't want your own person in the game. Check the FAQ to see how to deal with stuff.", inline=False) embed.set_thumbnail(url="https://images-ext-2.discordapp.net/external/SydGsxAv1JDLCgm4qALPhcke7fv6TWoyVR2lQhEu-NI/%3Fsize%3D128/https/cdn.discordapp.com/icons/681882711945641997/a_2c2eeae970672cefecdb5b8536f42a47.gif") embed.set_image(url="https://media.discordapp.net/attachments/773319739581136916/864310160520249384/tcabrawl.png?width=1025&height=404") embed.set_footer(text="TCR Brawl created by UnsoughtConch.") faq = discord.Embed(title="Frequently Asked Questions", description="These aren't really frequently asked.", color=discord.Color.random()) faq.add_field(name="Why am I not a character here?", value="This has a few answers. You either aren't very familiar, we haven't got to you yet, or we can't think of a good moveset for you.") faq.add_field(name="I'm in this game and don't want to be. How can I remove myself?", value="If you don't want to be in our game, please contact UnsoughtConch#9225.") faq.add_field(name="I want to make improvements to the game/a character. Can I?", value="Of course! Make a pull request from [the Coding Bot repository](https://github.com/The-Coding-Academy/Coding-Bot-v4) and edit the JSON or code!") faq.add_field(name="How can I suggest a character?", value="Contact UnsoughtConch#9225.") chars = discord.Embed(title="TCR ***BRAWL*** Characters") for character in data: char = data[character] desc = f"Class: {char['class']}\nAttack One: {char['atk_1']['name']}\nAttack Two: {char['atk_2']['name']}\nAbility: {char['ability']['name']}" chars.add_field(name=character, value=desc) chars.set_footer(text="You can get a more interactive and overall better info screen with ;info.") main_comps = ActionRow( Button(style=ButtonStyle.green, label="Information", emoji="❕", disabled=True), Button(style=ButtonStyle.blurple, label="FAQ", emoji="❔"), Button(style=ButtonStyle.secondary, label="Characters", emoji="🧑") ) faq_comps = ActionRow( Button(style=ButtonStyle.green, label="Information", emoji="❕"), Button(style=ButtonStyle.blurple, label="FAQ", emoji="❔", disabled=True), Button(style=ButtonStyle.secondary, label="Characters", emoji="🧑") ) chars_comps = ActionRow( Button(style=ButtonStyle.green, label="Information", emoji="❕"), Button(style=ButtonStyle.blurple, label="FAQ", emoji="❔"), Button(style=ButtonStyle.secondary, label="Characters", emoji="🧑", disabled=True) ) msg = await ctx.send(embed=embed, components=[main_comps]) on_click = msg.create_click_listener(timeout=60) @on_click.not_from_user(ctx.author) async def help_not_from_user(inter): await inter.reply("You have to be the command invoker to press these buttons.", ephemeral=True) @on_click.from_user(ctx.author) async def help_from_user(inter): await inter.reply(type=6) if str(inter.clicked_button.emoji) == "❔": await inter.message.edit(embed=faq, components = [faq_comps]) elif str(inter.clicked_button.emoji) == "❕": await inter.message.edit(embed=embed, components = [main_comps]) elif str(inter.clicked_button.emoji) == "🧑": await inter.message.edit(embed=chars, components=[chars_comps]) @on_click.timeout async def help_timeout(): buttons = ActionRow( Button(style=ButtonStyle.green, label="Information", emoji="❕", disabled=True), Button(style=ButtonStyle.blurple, label="FAQ", emoji="❔", disabled=True), Button(style=ButtonStyle.secondary, label="Characters", emoji="🧑", disabled=True), ) await msg.edit(components=[buttons])
async def battle(self, ctx, user:discord.Member): if user == ctx.author: return await ctx.send(embed=discord.Embed(title="You cannot battle yourself.", color=discord.Color.red())) embed = discord.Embed(title=f"Waiting for {user.display_name} to accept...", color=discord.Color.random()) buttons = ActionRow( Button(style=ButtonStyle.green, label="Accept", emoji="✅"), Button(style=ButtonStyle.red, label="Deny", emoji="❌") ) base = await ctx.send(embed=embed, components=[buttons]) def check(m): return m.author == user try: inter = await base.wait_for_button_click(check=check, timeout=30) except: await base.edit(embed=f"{user.display_name} failed to respond in time!", color=discord.Color.red()) await self.endgame(ctx) await inter.reply(type=6) embed = discord.Embed(title=f"{ctx.author.display_name}, choose your user!", color=discord.Color.random()) char_menu_opts = [] for character in data: char = data[character] desc = f"Class: {char['class']}\nAttack One: {char['atk_1']['name']}\nAttack Two: {char['atk_2']['name']}\nAbility: {char['ability']['name']}" embed.add_field(name=character, value=desc) char_menu_opts.append(SelectOption(character, character)) char_menu = SelectMenu(placeholder="Choose your user!", options=char_menu_opts) await base.delete() base = await ctx.send(embed=embed, components=[char_menu]) def check(m): return m.author == ctx.author try: inter = await base.wait_for_dropdown(check=check, timeout=120) except: await base.edit(embed=discord.Embed(f"{ctx.author.display_name} failed to respond in time!", color=discord.Color.red())) await self.endgame(ctx) await inter.reply(type=6) author_character = [option.label for option in inter.select_menu.selected_options][0] embed.title = f"{user.display_name}, choose your user!" await base.edit(embed=embed) def check(m): return m.author == user try: inter = await base.wait_for_dropdown(check=check, timeout=120) except: await ctx.send(embed=discord.Embed(f"{user.display_name} failed to respond in time!", color=discord.Color.red())) await self.endgame(ctx) await inter.reply(type=6) await base.delete() user_character = [option.label for option in inter.select_menu.selected_options][0] self.battle_hp[ctx.author.id] = 100 self.battle_hp[user.id] = 100 # True means author turn, False means user turn turne = True await self.write_action(ctx.author.id, f"{author_character} ({ctx.author.display_name}) picks a fight with {user_character} ({user.display_name})") while True: if self.battle_hp[ctx.author.id] < 1 or self.battle_hp[user.id] < 1: break if turne is True: turn = ctx.author character = author_character turn_hp = self.battle_hp[ctx.author.id] turn_class = data[character]['class'] enemy = user enemy_character = user_character enemy_hp = self.battle_hp[user.id] enemy_class = data[enemy_character]['class'] else: turn = user character = user_character turn_hp = self.battle_hp[user.id] turn_class = data[character]['class'] enemy = ctx.author enemy_character = author_character enemy_hp = self.battle_hp[user.id] enemy_class = data[enemy_character]['class'] if turn.id in self.placebo: if self.placebo[turn.id] == 0: self.battle_hp[turn.id] = self.battle_hp[turn.id] - data[character]['ability']['temp_xp'] else: self.placebo[turn.id] = self.placebo[turn.id] - 1 embed = discord.Embed(title=f"{turn.display_name}'s Turn") if turn_hp > 75: embed.color = discord.Color.green() elif turn_hp > 25: embed.color = discord.Color.gold() elif turn_hp <= 25: embed.color = discord.Color.red() embed.add_field(name="Character:", value=character) embed.add_field(name="HP:", value=turn_hp) embed.add_field(name="** **", value="** **") embed.add_field(name=data[character]['atk_1']['name'], value="ATTACK: " + data[character]['atk_1']['desc']) embed.add_field(name=data[character]['atk_2']['name'], value="ATTACK: " + data[character]['atk_2']['desc']) embed.add_field(name=data[character]['ability']['name'], value="ABILITY: " + data[character]['ability']['desc']) embed.set_thumbnail(url=data[character]['pfp']) options=[ SelectOption(data[character]['atk_1']['name'], "atk_1"), SelectOption(data[character]['atk_2']['name'], "atk_2"), SelectOption(data[character]['ability']['name'], "ability") ] if turn.id in self.cooldowns: flag = False if 'atk_1' in self.cooldowns[turn.id]['moves']: del self.cooldowns[turn.id]['moves']['atk_1'] del options[0] flag = True if 'ability' in self.cooldowns[turn.id]['moves']: if turn.id in self.ext_turns: pass else: if self.cooldowns[turn.id]['moves']['ability'] == 1: del self.cooldowns[turn.id]['moves']['ability'] else: self.cooldowns[turn.id]['moves']['ability'] = self.cooldowns[turn.id]['moves']['ability'] - 1 if flag is True: del options[1] else: del options[2] menu = SelectMenu( placeholder="Select a move...", options=options ) msg1 = await ctx.send(embed=embed, components=[menu]) def check(m): return m.author == turn try: inter = await msg1.wait_for_dropdown(check=check, timeout=120) except: await ctx.send(embed=discord.Embed(title=f"{turn.display_name} failed to respond on time, making {enemy.display_name} the winner!", color=discord.Color.red())) await self.endgame(ctx, user) return await inter.reply(type=6) move = [option.value for option in inter.select_menu.selected_options][0] if move == "ability": if turn.id in self.cooldowns: self.cooldowns[turn.id]['moves']['ability'] = 2 else: self.cooldowns[turn.id] = {'moves': {'ability': 2}} if data[character][move]['type'] == 'heal': self.battle_hp[turn.id] = self.battle_hp[turn.id] + data[character][move]['health'] if data[character][move]['health_gain_amt'] == 2: self.battle_hp[enemy.id] = self.battle_hp[enemy.id] + data[character][move]['health'] phrase = f"{turn.display_name} healths both parties with {data[character][move]['name']} and gains {data[character][move]['health']} health!" else: phrase = f"{turn.display_name} healths themself with {data[character][move]['name']} and gains {data[character][move]['health']} health!" elif data[character][move]['type'] == 'stun': self.ext_turns[turn.id] = data[character][move]['ext_turns'] phrase = f"{turn.display_name} stuns {enemy.display_name} with {data[character][move]['name']} and gains {self.ext_turns[turn.id]} extra turns!" elif data[character][move]['type'] == 'options': buttons = ActionRow( Button(style=ButtonStyle.green, label="Chill", emoji="😃"), Button(style=ButtonStyle.red, label="Angry", emoji="😡") ) msg2 = await ctx.send(embed=discord.Embed(title=f"{turn.display_name}, what option would you like to invoke?"), components=[buttons]) def check(m): return m.author == turn try: inter = await msg2.wait_for_button_click(check=check, timeout=60) except: await self.endgame(ctx, user) return await ctx.send(embed=discord.Embed(title=f"{turn.display_name} didn't choose in time, making {enemy.display_name} the winner!", color=discord.Color.red())) await inter.reply(type=6) option = inter.clicked_button.label if data[character][move]['options'][option]['ext_dmg'] == 0: try: del self.options[turn.id] except: pass self.options[turn.id] = data[character][move]['options'][option]['ext_dmg'] phrase = f"{turn.display_name} chooses {option} with {data[character][move]['name']} and gains {data[character][move]['options'][option]['ext_dmg']} extra power!" await msg2.delete() elif data[character][move]['type'] == "placebo": self.battle_hp[turn.id] = self.battle_hp[turn.id] + data[character][move]['temp_xp'] self.placebo[turn.id] = data[character][move]['turns'] phrase = f"{turn.display_name} invokes a placebo with {data[character][move]['name']} that gives them {data[character][move]['temp_xp']} more HP for {data[character][move]['turns']} turns!" else: try: dmg_class = data[character][move]['dmg_exc']['class'] if dmg_class == enemy_class: ext_dmg = data[character][move]['dmg_exc']['ext_dmg'] dmg = ext_dmg + data[character][move]['dmg'] else: dmg = data["wefrefwfwef"] except KeyError: try: dmg_char = data[character][move]['dmg_exc']['name'] if dmg_char == enemy_character: dmg = data[character][move]['dmg_exc']['ext_dmg'] + data[character][move]['dmg'] except KeyError: dmg = data[character][move]['dmg'] if move == 'atk_1': if turn.id in self.cooldowns: self.cooldowns[turn.id]['moves']['atk_1'] = 0 else: self.cooldowns[turn.id] = {'moves': {'atk_1': 0}} if turn.id in self.options: ext_dmg = self.options[turn.id] dmg = ext_dmg + dmg del self.options[turn.id] phrase = f"{character} deals {dmg} damage to {enemy_character} with {data[character][move]['name']}" if turne is True: self.battle_hp[user.id] = self.battle_hp[user.id] - dmg else: self.battle_hp[ctx.author.id] = self.battle_hp[ctx.author.id] - dmg await msg1.delete() await self.write_action(ctx.author.id, phrase) phrsmsg = await ctx.send(phrase) try: turns = self.ext_turns[turn.id] if turns == 0: del self.ext_turns[turn.id] e = self.battle_hp[2] self.ext_turns[turn.id] = self.ext_turns[turn.id] - 1 turne = True if turn == ctx.author else False except: turne = True if turn == user else False await asyncio.sleep(5) await phrsmsg.delete() if self.battle_hp[ctx.author.id] < 1: embed = discord.Embed(title=user_character + ": " + data[user_character]['catchphrase'] if user_character != 'BobDotCom' else random.choice(data[user_character]['catchphrase']), description=f"{user_character} won!") embed.set_footer(text=f"Remaining HP: {turn_hp}") await ctx.send(embed=embed) await self.endgame(ctx, user) else: embed = discord.Embed(title=author_character + ": " + data[author_character]['catchphrase'] if author_character != 'BobDotCom' else random.choice(data[author_character]['catchphrase']), description=f"{author_character} won!") embed.set_footer(text=f"Remaining HP: {turn_hp}") await ctx.send(embed=embed) await self.write_action(ctx.author.id, f"{ctx.author.display_name} ({author_character}) wins the battle with {turn_hp} HP remaining.") await self.endgame(ctx, user)
async def eat(self, ctx, eatable=None, quantity=None): with open(profiles, "r") as f: profile = json.load(f) inv = profile[str(ctx.author.id)]["inv"] with open(info, "r") as f: data = json.load(f) if eatable is None: msg = await ctx.send( "Loading Eatable Food items from your inventory") while True: buttons = [] em = discord.Embed( title="Eat Command", description= "All eatable items from your inventory are here\nClick on button on eat an item.\nIf there is not button which means you have nothing to eat.", colour=discord.Colour.green()) em.add_field(name="Health", value=await game.hearts(ctx)) em.add_field(name="Hunger", value=await game.food(ctx)) for item in inv: if item in data[ "food"] and item != "wheat" and item != "spider_eye" and item != "sugarcane": buttons.append( ActionRow( Button( label=item.replace("_", " ").capitalize() + f" X {inv[item]}", style=ButtonStyle.blurple, custom_id=item))) await msg.edit(content=None, embed=em, components=buttons) try: waiter = await msg.wait_for_button_click( check=lambda x: x.author.id == ctx.author.id, timeout=30) except asyncio.TimeoutError: await msg.edit(embed=discord.Embed( title="Interaction Ended", description="***: )***\nThanks for using Minecord.", colour=discord.Colour.light_grey()), components=[]) return button = waiter.clicked_button.custom_id health_increase = random.randint(1, 20) await game.inv_manager(ctx, button, -1) game.food_level(ctx, health_increase) else: eatable = await game.get_id(eatable) if eatable is None: await ctx.send("The item you are trying to eat doesn't exists") return if not eatable in inv: await ctx.send("You don't even own this item") return if isinstance(int, quantity): if inv[eatable] < quantity: await ctx.send("Too large quantity") return elif quantity == "max" or quantity == "all": quantity = inv[eatable] else: await ctx.send( "Quantity is not defined or invalid quantity.\nQuantity can be number or ```max``` or ```all```." ) return health_increase = data["food_health"][eatable] * quantity await game.inv_manager(eatable, -quantity) await game.food_level(health_increase) food_name = eatable.replace("_", " ").capitalize() msg = await ctx.send(f"You ate {quantity} {food_name}", components=Button( label="Check Health", style=ButtonStyle.blurple, custom_id="health_check_button")) waiter = await self.client.wait_for_button_click( check=lambda x: x.autuor.id == ctx.author.id, timeout=30) cmd = await self.client.get_command("health") await ctx.invoke(cmd, ctx)
async def inv(self, ctx): with open(profiles, 'r') as f: profile = json.load(f) inv = profile[str(ctx.author.id)]["inv"] with open(info, "r") as f: data = json.load(f) target = 0 size = 0 for i in list(inv.keys()): size += 1 if size == 0: await ctx.reply("You have nothing in your inventory.") return def get_type(id): for keys in data: if id in data[keys]: return keys def get_filter_size(id): size = 0 for i in inv: if i in data[id]: size += 1 page = 1 max_page = int(size / 5) filter = None if size % 5 != 0: max_page += 1 pages = [] target = 0 for i in range(max_page): em = discord.Embed(title=f"{ctx.author.name}'s inventory", description="Inventory Items", colour=discord.Colour.green()) if max_page > (i + 1): items = 5 elif max_page == (i + 1): remaining = size % 5 if remaining == 0: items = 5 else: items = remaining for item in range(items): id = list(inv.keys())[target] name = id.replace("_", " ").capitalize() emoji = data["id"][id] em.add_field( name=f"{target+1}) {emoji} {name} - {inv[id]}", value= f"ID ```{list(inv.keys())[target]}``` - {get_type(id)} - [Click here for item info](https://github.com/)", inline=False) target += 1 em.set_footer( text= f"Use m!info [item] to get info on an item - Page {page+i} of {max_page}", icon_url=ctx.author.avatar_url) pages.append(em) #Creating Buttons fd = Button(style=ButtonStyle.blurple, label="»", custom_id="fd") bk = Button(style=ButtonStyle.blurple, label="«", custom_id="bk") fd_disabled = Button(style=ButtonStyle.grey, label="»", custom_id="fd_disabled", disabled=True) bk_disabled = Button(style=ButtonStyle.grey, label="«", custom_id="bk_disabled", disabled=True) #Creating Select Menu. filter_bar = SelectMenu(custom_id="filter", placeholder="Choose up to 1 option.", max_values=1, options=[ SelectOption("Blocks", "block"), SelectOption("Jewel", "jewels"), SelectOption("Usables", "usables"), SelectOption("Food", "food"), SelectOption("Tools", "tools"), SelectOption("Armour", "armour") ]) #Sending Message if max_page == 1: fd2 = fd_disabled await ctx.send(embed=pages[0], components=[ActionRow(bk_disabled, fd2)]) return else: fd2 = fd msg = await ctx.send( embed=pages[0], components=[filter_bar, ActionRow(bk_disabled, fd2)]) while True: try: def check(m): return m.author.id == ctx.author.id waiter, pending = await asyncio.wait( [ msg.wait_for_button_click(check=check, timeout=30.0), msg.wait_for_dropdown(check=check, timeout=30.0) ], return_when=asyncio.FIRST_COMPLETED) except asyncio.TimeoutError: await msg.edit( embed=discord.Embed( title="Interaction Ended", description="***: )***\nThanks for using Minecord", colour=discord.Colour.blue()), components=[ActionRow(bk_disabled, fd_disabled)]) return for i in waiter: print(i.result) button = waiter.clicked_button.label backward = bk forward = fd if button == "»": page += 1 if page == max_page: forward = fd_disabled elif button == "«": page -= 1 if page == 1: backward = bk_disabled await msg.edit(embed=pages[page - 1], components=[ActionRow(backward, forward)])