GoldyBot.goldy

  1import os
  2import sys
  3from typing import List
  4import GoldyBot, devgoldyutils
  5import nextcord
  6import threading, _thread
  7import time
  8
  9MODULE_NAME = "GOLDY"
 10
 11class Goldy(object):
 12    """๐Ÿ’› Goldy herself. More precisely the main class to control the whole of the Bot."""
 13    def __init__(self):
 14        self.nextcord_thread:threading.Thread = None
 15
 16    def start(self):
 17        """
 18        Awakens Goldy Bot! ๐Ÿ‘€๐Ÿ’กโฐ
 19        ---------------
 20        ### ***``Example:``***
 21
 22        ```python
 23        import GoldyBot
 24
 25        goldy = GoldyBot.Goldy()
 26
 27        goldy.start()
 28        ```
 29        """
 30        GoldyBot.log("warn", f"[{MODULE_NAME}] Goldy Bot is awakening...")
 31
 32        file_setup() # Run file setup.
 33        
 34        # Fixes some weird as fu#k bug when stopping the bot on windows.
 35        if GoldyBot.system.platform.system() == 'Windows':
 36            GoldyBot.asyncio.set_event_loop_policy(GoldyBot.asyncio.WindowsSelectorEventLoopPolicy())
 37
 38        print("")
 39
 40        # Start goldy input console.
 41        input_thread = threading.Thread(target=input_loop)
 42        input_thread.setDaemon(True)
 43        input_thread.start()
 44
 45        # Start V4
 46        from . import bot
 47        self.nextcord_thread = threading.Thread(target=bot.start)
 48        self.nextcord_thread.setDaemon(True)
 49        self.nextcord_thread.start()
 50
 51        # Cache goldy class.
 52        GoldyBot.cache.main_cache_dict["goldy_class"] = self
 53
 54        try: self.nextcord_thread.join()
 55        except KeyboardInterrupt: pass # Stops KeyboardInterrupt traceback.
 56
 57    async def setup(self, client:nextcord.Client):
 58        """Notifies Goldy Bot that the client is ready and it can do it's setup."""
 59
 60        #  Run setup on all allowed guilds.
 61        #------------------------------
 62        for guild in client.guilds:
 63            goldy_bot_guild = GoldyBot.utility.guilds.guild.Guild(guild)
 64
 65            if goldy_bot_guild.is_allowed:
 66                await goldy_bot_guild.setup()
 67
 68        #  Check if the config files have been edited for the guilds.
 69        not_edited_config_guilds = []
 70        for guild_ in GoldyBot.cache.main_cache_dict["guilds"]:
 71            guild:GoldyBot.utility.guilds.guild.Guild = GoldyBot.cache.main_cache_dict["guilds"][guild_]["object"]
 72
 73            if not guild.has_config_been_edited:
 74                not_edited_config_guilds.append(guild.code_name)
 75
 76        if not not_edited_config_guilds == []:
 77            self.stop(reason=f"Guild configs MUST be edited! These guilds have not had their config's edited: {not_edited_config_guilds}")
 78
 79        GoldyBot.logging.log(f"[{MODULE_NAME}] Guilds Setup Done!")
 80
 81    def stop(self, reason="Unknown"):
 82        """Safely shutdowns Goldy Bot and stops her from performing anymore actions, incase you know, things get weird. ๐Ÿ˜ณ"""
 83
 84        GoldyBot.log("warn", f"[{MODULE_NAME}] Goldy is Shuting down...")
 85        GoldyBot.log("info", f"[{MODULE_NAME}] Here's the reason why I was requested to shutdown for >>> {reason}")
 86
 87        GoldyBot.cache.main_cache_dict["bot_stop"] = True
 88
 89        sys.exit(reason)
 90
 91def file_setup():
 92    """Makes sure all files and directories are setup and ready to go."""
 93    GoldyBot.log(f"[{MODULE_NAME}] Setup is running...")
 94
 95    # Directories
 96    for dir in GoldyBot.settings.directories_to_check:
 97        if os.path.exists(dir) == False: # If the directory doesn't exist create it.
 98            GoldyBot.files.File(dir)
 99
100    # Create goldy.json if it doesn't exist already.
101    if not "goldy.json" in os.listdir(GoldyBot.paths.CONFIG):
102        goldy_config = GoldyBot.files.File(GoldyBot.paths.GOLDY_CONFIG_JSON).write(GoldyBot.files.File(GoldyBot.paths.GOLDY_CONFIG_JSON_TEMPLATE).read())
103
104    GoldyBot.log("info_2", f"[{MODULE_NAME}] File Setup Done!")
105
106def input_loop():
107    goldy = Goldy()
108
109    time.sleep(7)
110
111    GoldyBot.logging.log()
112    GoldyBot.logging.log("info", "Available Console Commands -> [stop] [extensions]")
113    GoldyBot.logging.log()
114
115    try:
116        while True:
117            command = input("")
118
119            if command.lower() == "stop":
120                raise EOFError
121
122            if command.lower() == "extensions":
123                all_modules = GoldyBot.utility.misc.merge_dict(
124                    GoldyBot.cache.main_cache_dict["modules"], 
125                    GoldyBot.cache.main_cache_dict["internal_modules"]
126                )
127
128                print("")
129
130                for module in all_modules:
131                    for extension in all_modules[module]["extensions"]:
132                        print(devgoldyutils.Console().BLUE(extension))
133
134                print("")
135
136            time.sleep(0.1)
137            
138    except EOFError:
139        print("\n")
140        _thread.interrupt_main()
141        goldy.stop("Master commanded me to stop!")
class Goldy:
12class Goldy(object):
13    """๐Ÿ’› Goldy herself. More precisely the main class to control the whole of the Bot."""
14    def __init__(self):
15        self.nextcord_thread:threading.Thread = None
16
17    def start(self):
18        """
19        Awakens Goldy Bot! ๐Ÿ‘€๐Ÿ’กโฐ
20        ---------------
21        ### ***``Example:``***
22
23        ```python
24        import GoldyBot
25
26        goldy = GoldyBot.Goldy()
27
28        goldy.start()
29        ```
30        """
31        GoldyBot.log("warn", f"[{MODULE_NAME}] Goldy Bot is awakening...")
32
33        file_setup() # Run file setup.
34        
35        # Fixes some weird as fu#k bug when stopping the bot on windows.
36        if GoldyBot.system.platform.system() == 'Windows':
37            GoldyBot.asyncio.set_event_loop_policy(GoldyBot.asyncio.WindowsSelectorEventLoopPolicy())
38
39        print("")
40
41        # Start goldy input console.
42        input_thread = threading.Thread(target=input_loop)
43        input_thread.setDaemon(True)
44        input_thread.start()
45
46        # Start V4
47        from . import bot
48        self.nextcord_thread = threading.Thread(target=bot.start)
49        self.nextcord_thread.setDaemon(True)
50        self.nextcord_thread.start()
51
52        # Cache goldy class.
53        GoldyBot.cache.main_cache_dict["goldy_class"] = self
54
55        try: self.nextcord_thread.join()
56        except KeyboardInterrupt: pass # Stops KeyboardInterrupt traceback.
57
58    async def setup(self, client:nextcord.Client):
59        """Notifies Goldy Bot that the client is ready and it can do it's setup."""
60
61        #  Run setup on all allowed guilds.
62        #------------------------------
63        for guild in client.guilds:
64            goldy_bot_guild = GoldyBot.utility.guilds.guild.Guild(guild)
65
66            if goldy_bot_guild.is_allowed:
67                await goldy_bot_guild.setup()
68
69        #  Check if the config files have been edited for the guilds.
70        not_edited_config_guilds = []
71        for guild_ in GoldyBot.cache.main_cache_dict["guilds"]:
72            guild:GoldyBot.utility.guilds.guild.Guild = GoldyBot.cache.main_cache_dict["guilds"][guild_]["object"]
73
74            if not guild.has_config_been_edited:
75                not_edited_config_guilds.append(guild.code_name)
76
77        if not not_edited_config_guilds == []:
78            self.stop(reason=f"Guild configs MUST be edited! These guilds have not had their config's edited: {not_edited_config_guilds}")
79
80        GoldyBot.logging.log(f"[{MODULE_NAME}] Guilds Setup Done!")
81
82    def stop(self, reason="Unknown"):
83        """Safely shutdowns Goldy Bot and stops her from performing anymore actions, incase you know, things get weird. ๐Ÿ˜ณ"""
84
85        GoldyBot.log("warn", f"[{MODULE_NAME}] Goldy is Shuting down...")
86        GoldyBot.log("info", f"[{MODULE_NAME}] Here's the reason why I was requested to shutdown for >>> {reason}")
87
88        GoldyBot.cache.main_cache_dict["bot_stop"] = True
89
90        sys.exit(reason)

๐Ÿ’› Goldy herself. More precisely the main class to control the whole of the Bot.

Goldy()
14    def __init__(self):
15        self.nextcord_thread:threading.Thread = None
def start(self):
17    def start(self):
18        """
19        Awakens Goldy Bot! ๐Ÿ‘€๐Ÿ’กโฐ
20        ---------------
21        ### ***``Example:``***
22
23        ```python
24        import GoldyBot
25
26        goldy = GoldyBot.Goldy()
27
28        goldy.start()
29        ```
30        """
31        GoldyBot.log("warn", f"[{MODULE_NAME}] Goldy Bot is awakening...")
32
33        file_setup() # Run file setup.
34        
35        # Fixes some weird as fu#k bug when stopping the bot on windows.
36        if GoldyBot.system.platform.system() == 'Windows':
37            GoldyBot.asyncio.set_event_loop_policy(GoldyBot.asyncio.WindowsSelectorEventLoopPolicy())
38
39        print("")
40
41        # Start goldy input console.
42        input_thread = threading.Thread(target=input_loop)
43        input_thread.setDaemon(True)
44        input_thread.start()
45
46        # Start V4
47        from . import bot
48        self.nextcord_thread = threading.Thread(target=bot.start)
49        self.nextcord_thread.setDaemon(True)
50        self.nextcord_thread.start()
51
52        # Cache goldy class.
53        GoldyBot.cache.main_cache_dict["goldy_class"] = self
54
55        try: self.nextcord_thread.join()
56        except KeyboardInterrupt: pass # Stops KeyboardInterrupt traceback.

Awakens Goldy Bot! ๐Ÿ‘€๐Ÿ’กโฐ

Example:

import GoldyBot

goldy = GoldyBot.Goldy()

goldy.start()
async def setup(self, client: nextcord.client.Client):
58    async def setup(self, client:nextcord.Client):
59        """Notifies Goldy Bot that the client is ready and it can do it's setup."""
60
61        #  Run setup on all allowed guilds.
62        #------------------------------
63        for guild in client.guilds:
64            goldy_bot_guild = GoldyBot.utility.guilds.guild.Guild(guild)
65
66            if goldy_bot_guild.is_allowed:
67                await goldy_bot_guild.setup()
68
69        #  Check if the config files have been edited for the guilds.
70        not_edited_config_guilds = []
71        for guild_ in GoldyBot.cache.main_cache_dict["guilds"]:
72            guild:GoldyBot.utility.guilds.guild.Guild = GoldyBot.cache.main_cache_dict["guilds"][guild_]["object"]
73
74            if not guild.has_config_been_edited:
75                not_edited_config_guilds.append(guild.code_name)
76
77        if not not_edited_config_guilds == []:
78            self.stop(reason=f"Guild configs MUST be edited! These guilds have not had their config's edited: {not_edited_config_guilds}")
79
80        GoldyBot.logging.log(f"[{MODULE_NAME}] Guilds Setup Done!")

Notifies Goldy Bot that the client is ready and it can do it's setup.

def stop(self, reason='Unknown'):
82    def stop(self, reason="Unknown"):
83        """Safely shutdowns Goldy Bot and stops her from performing anymore actions, incase you know, things get weird. ๐Ÿ˜ณ"""
84
85        GoldyBot.log("warn", f"[{MODULE_NAME}] Goldy is Shuting down...")
86        GoldyBot.log("info", f"[{MODULE_NAME}] Here's the reason why I was requested to shutdown for >>> {reason}")
87
88        GoldyBot.cache.main_cache_dict["bot_stop"] = True
89
90        sys.exit(reason)

Safely shutdowns Goldy Bot and stops her from performing anymore actions, incase you know, things get weird. ๐Ÿ˜ณ

def file_setup():
 92def file_setup():
 93    """Makes sure all files and directories are setup and ready to go."""
 94    GoldyBot.log(f"[{MODULE_NAME}] Setup is running...")
 95
 96    # Directories
 97    for dir in GoldyBot.settings.directories_to_check:
 98        if os.path.exists(dir) == False: # If the directory doesn't exist create it.
 99            GoldyBot.files.File(dir)
100
101    # Create goldy.json if it doesn't exist already.
102    if not "goldy.json" in os.listdir(GoldyBot.paths.CONFIG):
103        goldy_config = GoldyBot.files.File(GoldyBot.paths.GOLDY_CONFIG_JSON).write(GoldyBot.files.File(GoldyBot.paths.GOLDY_CONFIG_JSON_TEMPLATE).read())
104
105    GoldyBot.log("info_2", f"[{MODULE_NAME}] File Setup Done!")

Makes sure all files and directories are setup and ready to go.

def input_loop():
107def input_loop():
108    goldy = Goldy()
109
110    time.sleep(7)
111
112    GoldyBot.logging.log()
113    GoldyBot.logging.log("info", "Available Console Commands -> [stop] [extensions]")
114    GoldyBot.logging.log()
115
116    try:
117        while True:
118            command = input("")
119
120            if command.lower() == "stop":
121                raise EOFError
122
123            if command.lower() == "extensions":
124                all_modules = GoldyBot.utility.misc.merge_dict(
125                    GoldyBot.cache.main_cache_dict["modules"], 
126                    GoldyBot.cache.main_cache_dict["internal_modules"]
127                )
128
129                print("")
130
131                for module in all_modules:
132                    for extension in all_modules[module]["extensions"]:
133                        print(devgoldyutils.Console().BLUE(extension))
134
135                print("")
136
137            time.sleep(0.1)
138            
139    except EOFError:
140        print("\n")
141        _thread.interrupt_main()
142        goldy.stop("Master commanded me to stop!")