Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.04 KB | None | 0 0
  1. from math import ceil
  2.  
  3. import asyncio
  4. from discord.ext import commands
  5. import logging
  6. import json
  7. import traceback
  8. from .utils import discord_utils as utils
  9. from .utils import discord_arg_parser as argparse
  10.  
  11. class BotConfigurator(commands.Cog):
  12.     def __init__(self, bot):
  13.         self.bot = bot
  14.         self.db_conn = bot.db_conn
  15.         self.zbp_server = self.bot.get_guild(self.bot.settings.zbp_server)
  16.         self.log = logging.getLogger('root.cogs.bot_setup')
  17.  
  18.     @commands.check(utils.is_owner)
  19.     @commands.group()
  20.     async def setup(self, ctx):
  21.         pass
  22.  
  23.     @setup.command(name='roles')
  24.     async def setup_roles(self, ctx, *, args=None):
  25.         # Get current roles supported
  26.         rows = self.db_conn.fetch_table('helpers')
  27.         if not rows:
  28.             await self.bot.embed_print(ctx, color='info',
  29.                                        description=f'No roles currently configured')
  30.         else:
  31.             # TODO: Add code for printing out the roles
  32.             print("TODO")
  33.  
  34.         # Display the menu for this command
  35.         msg = (f"Would you like to:\n"
  36.                f"{self.bot.settings.emojis['add']} `Add Roles`\n"
  37.                f"{self.bot.settings.emojis['reset']} `Clear Roles`\n"
  38.                f"{self.bot.settings.emojis['cancel']} `Cancel Operation`")
  39.         embed_out = await self.bot.embed_print(ctx, title='Role Setup Menu', color='info',
  40.                                                description=f'{msg}', _return=True)
  41.         panel = await ctx.send(embed=embed_out)
  42.         raw_emojis = (
  43.             f"{self.bot.settings.emojis['add']}",
  44.             f"{self.bot.settings.emojis['reset']}",
  45.             f"{self.bot.settings.emojis['cancel']}"
  46.         )
  47.         for raw_emoji in raw_emojis:
  48.             await panel.add_reaction(raw_emoji)
  49.  
  50.         # Interpret the actions to be taken
  51.         def check(reaction, user):
  52.             if user != ctx.message.author:
  53.                 return False
  54.             if str(reaction.emoji) in raw_emojis:
  55.                 return True
  56.         try:
  57.             reaction, user = await ctx.bot.wait_for('reaction_add', check=check, timeout=60.0)
  58.             await reaction.remove(user)
  59.         except asyncio.TimeoutError:
  60.             await panel.clear()
  61.         finally:
  62.             await panel.clear_reactions()
  63.         if str(reaction.emoji) == f"{self.bot.settings.emojis['add']}":
  64.             await self.set_roles(ctx)
  65.  
  66.     async def set_roles(self, ctx):
  67.         # Set the variable needed to track the information
  68.         emoji = self.bot.settings.emojis
  69.         panel = ''
  70.         roles_dict = {}         # {role1: {}, role2: {}}
  71.         roles_list = []         # [role1, role2]
  72.         indexer = {}            # {'1': (0, 9), '2': (10, 19)}
  73.         for role in self.bot.zulu_server.roles:
  74.             if role.name == '@everyone':
  75.                 continue
  76.             roles_dict[role.name] = {
  77.                 'name': role.name,
  78.                 'role': role,
  79.                 'picked': False
  80.             }
  81.             roles_list.append(role.name)
  82.  
  83.         # Sort list
  84.         roles_list.sort(key=lambda x: x.lower())
  85.  
  86.         # Get range blocks
  87.         blocks = ceil(len(roles_list) / 10)
  88.         for block in range(1, blocks+1):
  89.             # {'1': (0, 9), '2': (10, 19)}
  90.             indexer[str(block)] = ((block * 10 - 10), (block * 10 - 1))
  91.  
  92.         # Get the first panel and msg object
  93.         panel = get_panel_embed(roles_list[0:9], roles_dict, emoji)
  94.         embed_panel = await self.bot.embed_print(ctx, description=panel, _return=True)
  95.         msg_output = await ctx.send(embed=embed_panel)
  96.         await set_buttons(ctx, msg_output, emoji)
  97.  
  98.         # Create the check for the wait for
  99.         def check(reaction, user):
  100.             """A couple checks to make sure we stay complient"""
  101.             # Test that only the user executing the command
  102.             if not ctx.author.id == user.id:
  103.                 return False
  104.             # Make sure that the reaction is for the correct message
  105.             if not msg_output.id == reaction.message.id:
  106.                 return False
  107.             # Make sure we ignore the bot
  108.             if user.bot:
  109.                 return False
  110.             return True
  111.  
  112.         # After first message is out we can focus on using it
  113.         iterate = True
  114.         index = 1
  115.         while iterate:
  116.             try:
  117.                 # Wait for the user interaction
  118.                 reaction, user = await ctx.bot.wait_for('reaction_add', timeout=60, check=check)
  119.                 # Clear the pick so it looks nicer
  120.                 await msg_output.remove_reaction(reaction, user)
  121.  
  122.                 # If role was picked
  123.                 if reaction.emoji.name.startswith('rcs'):
  124.                     num = reaction.emoji.name.lstrip('rcs')                 # Strips the num from 'rcs#'
  125.                     role_set = roles_list[indexer[str(index)][0]:indexer[str(index)][1]]  # takes the role set
  126.                     chosen_role = role_set[int(num) - 1]
  127.                     print(chosen_role)
  128.                     # Modify the dictionary
  129.                     if roles_dict[chosen_role]['picked']:
  130.                         roles_dict[chosen_role]['picked'] = False
  131.                     else:
  132.                         roles_dict[chosen_role]['picked'] = True
  133.                 elif reaction.emoji.name == 'delete':
  134.                     await msg_output.delete()
  135.                     iterate = False
  136.  
  137.                 # Get a new panel
  138.                 block = indexer[str(index)]                 # {'1': (0, 9)}
  139.                 role_names = roles_list[block[0]:block[1]]  # roles_list[0, 9]
  140.                 panel = get_panel_embed(role_names, roles_dict, emoji)
  141.                 embed_panel = await self.bot.embed_print(ctx, description=panel, _return=True)
  142.                 await msg_output.edit(embed=embed_panel)
  143.  
  144.                 # # Now get the set of roles to pick
  145.                 # block = indexer[str(index)]                 # {'1': (0, 9)}
  146.                 # role_names = roles_list[block[0]:block[1]]  # roles_list[0, 9]
  147.  
  148.             except asyncio.TimeoutError:
  149.                 await msg_output.clear_reactions()
  150.  
  151.         #     # Variables for controlling flow
  152.         #     block = indexer[str(index)]                    # {'1': (0, 9)
  153.         #     role_names = roles_list[block[0]:block[1]]     # roles_list[0, 9]
  154.         #
  155.         #     # Create the panel to be printed
  156.         #     panel = get_panel_embed(role_names, roles_dict, emoji)
  157.         #
  158.         #     # Get the display object and add the reactions to it
  159.         #     display = await self.bot.embed_print(ctx, description=panel, _return=True)
  160.         #     display = await ctx.send(embed=display)
  161.         #
  162.         #
  163.         #     reaction, user = await ctx.bot.wait_for('reaction_add', timeout=60.0)
  164.         #     index += 1
  165.  
  166.  
  167. def get_panel_embed(roles_names, roles_dict, emoji):
  168.     """Returns the formatted panel to be places inside the embed"""
  169.     panel = ('**Select the roles you want to configure:**\n'
  170.              f'`  ` {emoji["delete"]} `Cancel operation`\n'
  171.              f'`  ` {emoji["save"]} `Save settings and commit`\n'
  172.              f'`  ` {emoji["right"]} `Next page`\n\n')
  173.     for idx, role_name in enumerate(roles_names):
  174.         emoji_num = f'rcs{str(idx + 1)}'
  175.         if roles_dict[role_name]['picked']:
  176.             mark = 'checked'
  177.         else:
  178.             mark = 'unchecked'
  179.         panel += f'{emoji[emoji_num]} {emoji[mark]} {role_name}\n'
  180.     return panel
  181.  
  182.  
  183. async def set_buttons(ctx, display, emoji):
  184.     """Puts the emojis on the panel"""
  185.     for idx in range(0, 9):
  186.         number = f'rcs{str(idx + 1)}'
  187.         await display.add_reaction(emoji[number])
  188.     await display.add_reaction(emoji['delete'])
  189.     await display.add_reaction(emoji['save'])
  190.     await display.add_reaction(emoji['right'])
  191.  
  192. def setup(bot):
  193.     bot.add_cog(BotConfigurator(bot))
  194.  
  195.  
  196. #cur.execute("INSERT INTO friends(name) VALUES ('Tom')")
  197.         # self.db_conn.cursor.execute("INSERT INTO helpers VALUES (11123,'Jason')")
  198.         # self.db_conn.conn.commit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement