Advertisement
HTG_YT

hartexbeta.py

Apr 22nd, 2020
740
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.69 KB | None | 0 0
  1. class HartexBeta(commands.AutoShardedBot):
  2.     """
  3.    Class: HartexBeta
  4.  
  5.    Represents the HarTex Beta bot.
  6.  
  7.    Inherits: commands.AutoShardedBot
  8.    """
  9.  
  10.     def __init__(self):
  11.         super(HartexBeta, self).__init__(command_prefix="hb.", help_command=None, status=discord.Status.dnd,
  12.                                          activity=discord.Activity(name="in development",
  13.                                                                    type=discord.ActivityType.playing),
  14.                                          case_insensitive=True)
  15.         self.start_time = datetime.utcnow()
  16.         self.version = __version_format__(1, 0, 0)
  17.         self.shard_count = 1
  18.  
  19.     async def on_ready(self):
  20.         """
  21.        Asynchronous Method: on_ready
  22.  
  23.        The method is activated when the bot is online.
  24.        :return:
  25.        """
  26.  
  27.         print(f"HarTex Beta >> HarTex Beta is online!")
  28.         print(await self.connect_config_database())
  29.  
  30.     async def on_command(self, context: commands.Context):
  31.         """
  32.        Asynchronous Method: on_command
  33.  
  34.        The method is activated when a command is executed.
  35.        :param context: The command context.
  36.        :return:
  37.        """
  38.  
  39.         print(f"HarTex Beta >> Command '{context.command}' is executed by {context.author} in {context.guild}.")
  40.  
  41.     async def on_guild_join(self, guild: discord.Guild):
  42.         """
  43.        Asynchronous Method: on_guild_join
  44.  
  45.        This method is activated when the bot joins a Discord guild.
  46.        :param guild: The guild the bot joined.
  47.        :return:
  48.        """
  49.  
  50.         print(f"HarTex Beta >> The bot is added to {guild.name}(ID: {guild.id}).")
  51.  
  52.         try:
  53.             cursor = await self.cursor_config
  54.  
  55.             await cursor.execute(sql.SQL('select * from "HarTexBetaConfig".public.guilds'))
  56.  
  57.             guilds = await cursor.fetchall()
  58.  
  59.             for g in guilds:
  60.                 if guild.id == g[0]:
  61.                     pass
  62.                 else:
  63.                     continue
  64.             else:
  65.                 await guild.leave()
  66.         except Exception as error:
  67.             print(f"HarTex Beta >> Failed to fetch guilds. Error: {error}")
  68.  
  69.     async def on_guild_remove(self, guild: discord.Guild):
  70.         """
  71.        Asynchronous Method: on_guild_remove
  72.  
  73.        This method is activated when the bot is removed from a Discord guild.
  74.        :param guild: The guild the bot is removed from.
  75.        :return:
  76.        """
  77.  
  78.         print(f"HarTex Beta >> The bot is removed from {guild.name}(ID: {guild.id})")
  79.  
  80.     async def on_command_completion(self, ctx: discord.ext.commands.Context):
  81.         """
  82.        Asynchronous Method: on_command_completion
  83.  
  84.        This method is activated when a command is completed without errors.
  85.        :param ctx: The command context.
  86.        :return:
  87.        """
  88.  
  89.         (await self.config_connection).close()
  90.  
  91.     def run_hartexbeta(self, token: str):
  92.         """
  93.        Method: run_hartexbeta
  94.  
  95.        Runs the bot.
  96.        :param token: The bot token.
  97.        :return:
  98.        """
  99.  
  100.         super().run(token)
  101.  
  102.     async def connect_config_database(self) -> aiopg.Connection:
  103.         """
  104.        Asynchronous Method: connect_config_database
  105.  
  106.        Connects to the bot database.
  107.        :return:
  108.        """
  109.  
  110.         try:
  111.             with open("core/database_credentials.yaml", "r") as yaml_reader:
  112.                 file = yaml.safe_load(yaml_reader)
  113.  
  114.             connection = await aiopg.connect(
  115.                 database=file['database_credentials']['hartex_beta_config']['database'],
  116.                 user=file['database_credentials']['hartex_beta_config']['user'],
  117.                 password=file['database_credentials']['hartex_beta_config']['password'],
  118.                 host=file['database_credentials']['hartex_beta_config']['host'],
  119.                 port=file['database_credentials']['hartex_beta_config']['port']
  120.             )
  121.  
  122.             return connection
  123.         except Exception as exception:
  124.             print(f"HarTex Beta >> An error occurred when trying to connect to database HarTexBetaConfig: {exception}")
  125.  
  126.     async def close_hartexbeta(self):
  127.         """
  128.        Asynchronous Method: close_hartexbeta
  129.  
  130.        Shuts down the bot.
  131.        :return:
  132.        """
  133.  
  134.         await super().close()
  135.  
  136.     def load_commands(self):
  137.         """
  138.        Method: load_commands
  139.  
  140.        Loads all the commands for the bot.
  141.        :return:
  142.        """
  143.         for filename in os.listdir("./cmds"):
  144.             if filename.endswith(".py"):
  145.                 self.load_extension(f"cmds.{filename[:-3]}")
  146.                 print(f"HarTex Beta >> Loaded extension {filename[:-3]}.")
  147.  
  148.     def reload_commands(self):
  149.         """
  150.        Method: reload_commands
  151.  
  152.        Reloads all the commands for the bot.
  153.        :return:
  154.        """
  155.  
  156.         for filename in os.listdir("./cmds"):
  157.             if filename.endswith(".py"):
  158.                 self.reload_extension(f"cmds.{filename[:-3]}")
  159.                 print(f"HarTex Beta >> Reloaded extension {filename[:-3]}.")
  160.  
  161.     def unload_commands(self):
  162.         """
  163.        Method: unload_commands
  164.  
  165.        Unloads all the commands for the bot.
  166.        :return:
  167.        """
  168.  
  169.         for filename in os.listdir("./cmds"):
  170.             if filename.endswith(".py"):
  171.                 self.unload_extension(f"cmds.{filename[:-3]}")
  172.                 print(f"HarTex Beta >> Unloaded extension {filename[:-3]}.")
  173.  
  174.     @property
  175.     def uptime(self) -> str:
  176.         """
  177.        Property: uptime
  178.  
  179.        The bot's uptime.
  180.        :return:
  181.        """
  182.  
  183.         second = datetime.utcnow() - self.start_time
  184.         minute, second = divmod(second.seconds, 60)
  185.         hour, minute = divmod(minute, 60)
  186.         day, hour = divmod(hour, 24)
  187.         week, day = divmod(day, 7)
  188.  
  189.         return f"{week} weeks, {day} days, {hour} hours, {minute} minutes, {second} seconds"
  190.  
  191.     @property
  192.     def token(self) -> str:
  193.         """
  194.        Property: token
  195.  
  196.        The bot token.
  197.        :return:
  198.        """
  199.  
  200.         with open("core/token.yaml") as yaml_reader:
  201.             file = yaml.safe_load(yaml_reader)
  202.  
  203.             return file['token']
  204.  
  205.     @property
  206.     async def config_connection(self):
  207.         """
  208.        Property: config_connection
  209.  
  210.        The bot database connection.
  211.        :return:
  212.        """
  213.  
  214.         return await self.connect_config_database()
  215.  
  216.     @property
  217.     async def cursor_config(self) -> aiopg.Cursor:
  218.         """
  219.        Property: cursor_config
  220.  
  221.        The cursor of the existing database connection.
  222.        :return:
  223.        """
  224.         connection = await self.config_connection
  225.  
  226.         return await connection.cursor()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement