<gh_stars>1-10
import os
import logging
from datetime import datetime

from discord import (
    Intents,
    Activity,
    ActivityType
    )
from discord.ext import commands
from discord.ext.commands import (
    ExtensionNotFound,
    ExtensionAlreadyLoaded,
    NoEntryPointError,
    ExtensionFailed,
    ExtensionNotLoaded
)
from motor.motor_asyncio import AsyncIOMotorClient

from bot.utils import config


__all__ = (
    'Astro',
)

log = logging.getLogger(__name__)

TOKEN = config()['token']

DESCRIPTION = "A bot for Dimension MC's Discord server."

STICKY_EXTENSIONS = (
    'admin',
    'handler'
)


def _get_prefix(bot, msg):
    return config()['prefixes']

def _get_status():
    conf = config()

    type_ = conf['status_type']
    name = conf['status_name']
    url = conf['status_url']

    return Activity(type=getattr(ActivityType, type_, ActivityType.playing), name=name, url=url)


class Astro(commands.Bot):
    def __init__(self):
        self.db = AsyncIOMotorClient('mongodb://localhost:27017/astro')['astro']
        self._socket_receive = {}
        super().__init__(
            command_prefix=_get_prefix,
            help_command=None,
            description=DESCRIPTION,
            case_insensitive=True,
            activity=_get_status(),
            intents=Intents.all())

    def _load_extension(self, name, *, package=None):
        try:
            super().load_extension(f'bot.extensions.{name}', package=package)
        except ExtensionNotFound:
            return f'Extension `{name}` not found'
        except ExtensionAlreadyLoaded:
            return f'Extension `{name}` is already loaded'
        except NoEntryPointError:
            return f'Extension `{name}` has no setup function'
        except ModuleNotFoundError:
            return f'Extension `{name}` not found'
        except ExtensionFailed as e:
            return f'Extension `{name}` couldn\'t be loaded:\n```{e}```'

    def _reload_extension(self, name, *, package=None):
        try: 
            super().reload_extension(f'bot.extensions.{name}', package=package)
        except ExtensionNotFound:
            return f'Extension `{name}` not found'
        except ExtensionNotLoaded:
            return f'Extension `{name}` not loaded'
        except NoEntryPointError:
            return f'Extension `{name}` has no setup function'
        except ModuleNotFoundError:
            return f'Extension `{name}` not found'
        except ExtensionFailed as e:
            return f'`{name}`:\n```{e.original}```'
    
    def _unload_extension(self, name, *, package=None):
        if any(_ for _ in STICKY_EXTENSIONS if (_ in name)): # im clumsy lol
            return f'Extension {name} is protected from unloads.'
        try:
            super().unload_extension(f'bot.extensions.{name}', package=package)
        except:
            return f'Extension `{name}` not found/loaded'
        
    def _load_all_extensions(self):
        ret = ''

        for ext in os.listdir('bot/extensions'):
            if ext.endswith('.py'):
                _ = self._load_extension(ext[:-3])
                if _:
                    ret = f'{ret}\n{_}'
    
        return ret
    
    def _reload_all_extensions(self):
        ret = ''

        for ext in os.listdir('bot/extensions'):
            if ext.endswith('.py'):
                _ = self._reload_extension(ext[:-3])
                if _:
                    ret = f'{ret}\n{_}'
    
        return ret

    def _unload_all_extensions(self):
        ret = ''

        for ext in os.listdir('bot/extensions'):
            if ext.endswith('.py'):
                _ = self._unload_extension(ext[:-3])
                if _: 
                    ret = f'{ret}\n{_}'

        return ret
    
    async def on_message(self, message):
        if not message.guild:
            return
        return await super().on_message(message)

    async def on_connect(self):
        print(f'Connected to Discord. Latency: {(self.latency * 1000):.2f}ms')

    async def on_disconnect(self):
        print('Disconnected. Attempting to reconnect...')

    async def on_resume(self):
        print('Connection restored.')

    async def on_ready(self):
        print('Internal cache ready.')
        self.uptime = datetime.utcnow()

    async def on_error(self, event_method, *args, **kwargs):
        log.exception(f'Ignoring exception in event {event_method}')
        super().on_error(event_method, *args, **kwargs)

    def run(self):
        print('Starting...')
        _ = self._load_all_extensions()
        if _:
            print(_)
        loop = self.loop
        loop.run_until_complete(super().start(TOKEN))
import os
import logging
from datetime import datetime

from discord import (
    Intents,
    Activity,
    ActivityType
    )
from discord.ext import commands
from discord.ext.commands import (
    ExtensionNotFound,
    ExtensionAlreadyLoaded,
    NoEntryPointError,
    ExtensionFailed,
    ExtensionNotLoaded
)
from motor.motor_asyncio import AsyncIOMotorClient

from bot.utils import config


__all__ = (
    'Astro',
)

log = logging.getLogger(__name__)

TOKEN = config()['token']

DESCRIPTION = "A bot for Dimension MC's Discord server."

STICKY_EXTENSIONS = (
    'admin',
    'handler'
)


def _get_prefix(bot, msg):
    return config()['prefixes']

def _get_status():
    conf = config()

    type_ = conf['status_type']
    name = conf['status_name']
    url = conf['status_url']

    return Activity(type=getattr(ActivityType, type_, ActivityType.playing), name=name, url=url)


class Astro(commands.Bot):
    def __init__(self):
        self.db = AsyncIOMotorClient('mongodb://localhost:27017/astro')['astro']
        self._socket_receive = {}
        super().__init__(
            command_prefix=_get_prefix,
            help_command=None,
            description=DESCRIPTION,
            case_insensitive=True,
            activity=_get_status(),
            intents=Intents.all())

    def _load_extension(self, name, *, package=None):
        try:
            super().load_extension(f'bot.extensions.{name}', package=package)
        except ExtensionNotFound:
            return f'Extension `{name}` not found'
        except ExtensionAlreadyLoaded:
            return f'Extension `{name}` is already loaded'
        except NoEntryPointError:
            return f'Extension `{name}` has no setup function'
        except ModuleNotFoundError:
            return f'Extension `{name}` not found'
        except ExtensionFailed as e:
            return f'Extension `{name}` couldn\'t be loaded:\n```{e}```'

    def _reload_extension(self, name, *, package=None):
        try: 
            super().reload_extension(f'bot.extensions.{name}', package=package)
        except ExtensionNotFound:
            return f'Extension `{name}` not found'
        except ExtensionNotLoaded:
            return f'Extension `{name}` not loaded'
        except NoEntryPointError:
            return f'Extension `{name}` has no setup function'
        except ModuleNotFoundError:
            return f'Extension `{name}` not found'
        except ExtensionFailed as e:
            return f'`{name}`:\n```{e.original}```'
    
    def _unload_extension(self, name, *, package=None):
        if any(_ for _ in STICKY_EXTENSIONS if (_ in name)): # im clumsy lol
            return f'Extension {name} is protected from unloads.'
        try:
            super().unload_extension(f'bot.extensions.{name}', package=package)
        except:
            return f'Extension `{name}` not found/loaded'
        
    def _load_all_extensions(self):
        ret = ''

        for ext in os.listdir('bot/extensions'):
            if ext.endswith('.py'):
                _ = self._load_extension(ext[:-3])
                if _:
                    ret = f'{ret}\n{_}'
    
        return ret
    
    def _reload_all_extensions(self):
        ret = ''

        for ext in os.listdir('bot/extensions'):
            if ext.endswith('.py'):
                _ = self._reload_extension(ext[:-3])
                if _:
                    ret = f'{ret}\n{_}'
    
        return ret

    def _unload_all_extensions(self):
        ret = ''

        for ext in os.listdir('bot/extensions'):
            if ext.endswith('.py'):
                _ = self._unload_extension(ext[:-3])
                if _: 
                    ret = f'{ret}\n{_}'

        return ret
    
    async def on_message(self, message):
        if not message.guild:
            return
        return await super().on_message(message)

    async def on_connect(self):
        print(f'Connected to Discord. Latency: {(self.latency * 1000):.2f}ms')

    async def on_disconnect(self):
        print('Disconnected. Attempting to reconnect...')

    async def on_resume(self):
        print('Connection restored.')

    async def on_ready(self):
        print('Internal cache ready.')
        self.uptime = datetime.utcnow()

    async def on_error(self, event_method, *args, **kwargs):
        log.exception(f'Ignoring exception in event {event_method}')
        super().on_error(event_method, *args, **kwargs)

    def run(self):
        print('Starting...')
        _ = self._load_all_extensions()
        if _:
            print(_)
        loop = self.loop
        loop.run_until_complete(super().start(TOKEN))
# im clumsy lol