示例#1
0
    async def initialize(self, audio: Audio, enabled=True) -> None:
        _pass_config_to_api(self.config)
        global old_audio_cache
        if old_audio_cache is None and enabled is True:
            old_audio_cache = audio.music_cache

        if enabled is True:
            audio.music_cache = MusicCache(
                audio.bot,
                audio.session,
                path=str(cog_data_path(raw_name="Audio")))
            await audio.music_cache.initialize(audio.config)
        elif enabled is False:
            audio.music_cache = old_audio_cache
示例#2
0
    def __init__(self, bot):
        super().__init__()
        self.bot = bot
        self.config = Config.get_conf(self, identifier=736144321857978388, force_registration=True)
        
        default_guild = {'canvas': {}}
        
        self.config.register_guild(**default_guild)

        self.temp = cog_data_path(self) / "temp"
        self.temp.mkdir(exist_ok=True, parents=True)
        
        self.image_mimes = ["image/png", "image/pjpeg", "image/jpeg", "image/x-icon"]
        self.gif_mimes = ["image/gif"]
示例#3
0
    async def _load_machine(self, source, filename):

        if source == "local":
            machine = yaml.safe_load(open(data_manager.bundled_data_path(self) / filename))
        else:
            machine = yaml.safe_load(open(data_manager.cog_data_path(self) / filename))
        errors = await self._validate_machine(machine)
        if errors == []:
            self.slot_machines[machine["name"].lower()] = machine
        else:
            log.info(f"Failed to parse slot machine {filename}")
            log.debug(errors)

        return errors
示例#4
0
    async def themeset_add_monster(self, ctx: commands.Context, *, theme_data: ThemeSetMonterConverter):
        """[Owner] Add/Update a monster object in the specified theme.

        Usage: `[p]themeset add monster theme++name++hp++dipl++pdef++mdef++cdef++boss++image`

        `theme` is the one-word theme folder name. The default is `default`.
        `name` is the name of the monster.
        `hp` is the base amount of hp the monster has.
        `dipl` is the base amount of charisma/diplomacy the monster has.
        `pdef` is the percentage of physical resistance, `0.0` to `100.0`.
        `mdef` is the percentage of magic resistance, `0.0` to `100.0`.
        `cdef` is the percentage of charisma/diplomacy resistance, `0.0` to `100.0`.
        `boss` is whether the monster is a boss, determined with `True` or `False`.
        `image` is a URL for an image of the monster.
        """
        assert isinstance(theme_data, dict)
        theme = theme_data.pop("theme", None)
        if theme != "default" and theme not in os.listdir(cog_data_path(self)):
            await smart_embed(ctx, _("That theme pack does not exist!"))
            return
        updated = False
        monster = theme_data.pop("name", None)
        async with self.config.themes.all() as config_data:
            if theme not in config_data:
                config_data[theme] = {"monsters": {}}
            if "monsters" not in config_data[theme]:
                config_data[theme]["monsters"] = {}
            if monster in config_data[theme]["monsters"]:
                updated = True
            config_data[theme]["monsters"][monster] = theme_data
        image = theme_data.pop("image", None)
        text = _(
            "Monster: `{monster}` has been {status} the `{theme}` theme\n"
            "```ini\n"
            "HP:                  [{hp}]\n"
            "Diplomacy:           [{dipl}]\n"
            "Physical defence:    [{pdef}]\n"
            "Magical defence:     [{mdef}]\n"
            "Persuasion defence:  [{cdef}]\n"
            "Is a boss:           [{boss}]```"
        ).format(
            monster=monster,
            theme=theme,
            status=_("added to") if not updated else _("updated in"),
            **theme_data,
        )

        embed = discord.Embed(description=text, colour=await ctx.embed_colour())
        embed.set_image(url=image)
        await ctx.send(embed=embed)
示例#5
0
 def __init__(self, bot: Red):
     self.bot = bot
     self._connection = apsw.Connection(
         str(cog_data_path(self) / "MartTools.db"))
     self.cursor = self._connection.cursor()
     self.cursor.execute(PRAGMA_journal_mode)
     self.cursor.execute(PRAGMA_wal_autocheckpoint)
     self.cursor.execute(PRAGMA_read_uncommitted)
     self.cursor.execute(CREATE_TABLE_PERMA)
     self.cursor.execute(DROP_TEMP)
     self.cursor.execute(CREATE_TABLE_TEMP)
     self.uptime = datetime.utcnow()
     self.cursor.execute(INSERT_PERMA_DO_NOTHING,
                         (-1000, "creation_time", time.time()))
示例#6
0
 def __init__(self, bot: Red) -> None:
     self.bot = bot
     self.config = Config.get_conf(self,
                                   identifier=176070082584248320,
                                   force_registration=True)
     self.config.register_guild(
         role_id=None,
         channel_id=None,
         message_templates=[],
         unassign_on_boost_end=False,
     )
     self.message_images = cog_data_path(self) / "message_images"
     self.message_images.mkdir(parents=True, exist_ok=True)
     self.guild_cache: Dict[int, GuildData] = {}
示例#7
0
    def make_crab(self, t, u_id):
        """Non blocking crab rave video generation from DankMemer bot

        https://github.com/DankMemer/meme-server/blob/master/endpoints/crab.py
        """
        fp = str(cog_data_path(self) / f"Verdana.ttf")
        clip = VideoFileClip(str(cog_data_path(self)) + "/template.mp4")
        # clip.volume(0.5)
        text = TextClip(t[0], fontsize=48, color="white", font=fp)
        text2 = (
            TextClip("____________________", fontsize=48, color="white", font=fp)
            .set_position(("center", 210))
            .set_duration(15.4)
        )
        text = text.set_position(("center", 200)).set_duration(15.4)
        text3 = (
            TextClip(t[1], fontsize=48, color="white", font=fp)
            .set_position(("center", 270))
            .set_duration(15.4)
        )

        video = CompositeVideoClip(
            [clip, text.crossfadein(1), text2.crossfadein(1), text3.crossfadein(1)]
        ).set_duration(15.4)
        video = video.volumex(0.1)
        video.write_videofile(
            str(cog_data_path(self)) + f"/{u_id}crabrave.mp4",
            threads=1,
            preset="superfast",
            verbose=False,
            logger=None,
            temp_audiofile=str(cog_data_path(self) / f"{u_id}crabraveaudio.mp3")
            # ffmpeg_params=["-filter:a", "volume=0.5"]
        )
        clip.close()
        video.close()
        return True
示例#8
0
 def __init__(self, bot: Red) -> None:
     self.bot = bot
     self.config = Config.get_conf(self,
                                   176070082584248320,
                                   force_registration=True)
     self.config.register_global(execution_key=None, ports=None)
     self.env = {
         "bot": bot,
         "aiohttp": aiohttp,
         "asyncio": asyncio,
         "discord": discord,
         "commands": commands,
     }
     self.connection_file = cog_data_path(self) / "kernel.json"
     self.app: Optional[RedIPKernelApp] = None
示例#9
0
    def __init__(self, bot: Red):
        super().__init__()
        self.bot = bot
        self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)

        default_guild = {"enabled": False, "channel_id": None}

        self.config.register_guild(**default_guild)

        # self.detector = NudeDetector()
        self.classifier = NudeClassifier()

        self.data_path: pathlib.Path = cog_data_path(self)

        self.current_processes = 0
示例#10
0
    def __init__(self, bot):
        super().__init__()
        self.bot = bot
        self.config = Config.get_conf(self, identifier=736144321857978388, force_registration=True)
        default_global = {"INSTALOADER_LOGIN": "",
                          "INSTALOADER_PASSWORD": ""}
        default_guild = {"fav_channel": None}
        self.config.register_global(**default_global)
        self.config.register_guild(**default_guild)

        self.instaload = instaloader.Instaloader()
        self.cache = {"_instagram": {}, "instaload": False, "tales": {}, "fav_msg": []}

        self.temp = cog_data_path(self) / "temp"
        self.temp.mkdir(exist_ok=True, parents=True)
示例#11
0
	async def wordlist(self, ctx, value: str):
		"""
		Change the wordlist used.
		
		Extra wordlists can be put in the data folder.
		Wordlists are a .txt file with every new line being a new word.
		This value is server specific.
		"""
		wordlists = [p.resolve() for p in cog_data_path(self).glob("*.txt")]
		try:
			fp = next(p for p in wordlists if p.stem == value)
			await self.config.guild(ctx.guild).fp.set(str(fp))
			await ctx.send(f'The wordlist is now set to `{value}`.')
		except StopIteration:
			await ctx.send(f'Wordlist `{value}` not found.')
示例#12
0
    async def rusteval(self,ctx, *, body: str):
        if not self.initialized:
            return
        body = self.cleaninput(body)
        if "fn main()" not in body:
            #We need to wrap the code in a main function
            body = f"fn main(){{\n{body}\n}}"

        with open(cog_data_path(self)/"internalproj"/"src"/"main.rs", "w") as outputfile:
            outputfile.write(body)
        compilerrun = self.subprocessrun(["cargo", "build"])
        if len(compilerrun.stdout):
            await ctx.send(f"```\n{compilerrun.stdout}```")
        if len(compilerrun.stderr):
            cleaned = compilerrun.stderr.replace(f"({str(cog_data_path(self)/'internalproj')})", '')
            await ctx.send(f"```\n{cleaned}```")
        if compilerrun.returncode != 0:
            return await ctx.send("Failed to execute...")

        progrun = subprocess.run([cog_data_path(self)/"internalproj"/"target"/"debug"/"internalproj"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        if len(progrun.stdout):
            await ctx.send(f"```\n{progrun.stdout}```")
        if len(progrun.stderr):
            await ctx.send(f"```\n{progrun.stderr}```")
示例#13
0
 async def clean_deleted_images(self, ctx: commands.Context) -> None:
     """
         Cleanup deleted images that are not supposed to be saved anymore
     """
     images = await self.config.guild(ctx.guild).images()
     directory = cog_data_path(self) / str(ctx.guild.id)
     saved = os.listdir(str(directory))
     for file in images:
         if file["image_loc"] in saved:
             continue
         try:
             os.remove(str(directory / file))
         except Exception:
             log.error(_("Error deleting image {image}").format(image=file), exc_info=True)
     await ctx.tick()
示例#14
0
    def __init__(self, bot):
        super().__init__()
        self.bot = bot
        self.path = cog_data_path(self) / "packs"
        self.path.mkdir(exist_ok=True, parents=True)
        self.config = Config.get_conf(self, identifier=736144321857978388, force_registration=True)

        default_guild = {"default_mode": DEFAULT_MODE,
                         "original_win": 5,
                         "plus_win": 5,
                         "course_start": 5,
                         "packs": []}
        self.config.register_guild(**default_guild)
        self.packs = {}
        self.load_packs()
示例#15
0
    def __init__(self, bot: Red):
        self.bot = bot
        self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
        default_global = {"lint": True}
        default_guild = {}

        self.path = str(cog_data_path(self)).replace("\\", "/")

        self.do_lint = None
        self.counter = 0

        # self.answer_path = self.path + "/tmpfile.py"

        self.config.register_global(**default_global)
        self.config.register_guild(**default_guild)
示例#16
0
文件: avatar.py 项目: SFUAnime/Ren
 def __init__(self, bot: Red):
     self.bot = bot
     self.saveFolder = data_manager.cog_data_path(cog_instance=self)
     self.logger = logging.getLogger("red.luicogs.Avatar")
     if self.logger.level == 0:
         # Prevents the self.logger from being loaded again in case of module reload.
         self.logger.setLevel(logging.INFO)
         logPath = os.path.join(self.saveFolder, "info.log")
         handler = logging.FileHandler(filename=logPath,
                                       encoding="utf-8",
                                       mode="a")
         handler.setFormatter(
             logging.Formatter("%(asctime)s %(message)s",
                               datefmt="[%d/%m/%Y %H:%M:%S]"))
         self.logger.addHandler(handler)
示例#17
0
 def __init__(self, bot):
     super().__init__()
     self.bot = bot
     self.config = Config.get_conf(self,
                                   identifier=95932766180343808,
                                   force_registration=True)
     self.config.register_global(
         isglobal=True,
         hashed=False,
         hashes={},
         spawnchance=[20, 120],
         hintcost=1000,
         spawnloop=False,
         migration=1,
     )
     defaults_guild = {
         "activechannels": [],
         "toggle": False,
         "whitelist": [],
         "blacklist": [],
         "levelup_messages": False,
     }
     self.config.register_guild(**defaults_guild)
     defaults_user = {
         "pokeids": {},
         "silence": False,
         "timestamp": 0,
         "pokeid": 1,
         "has_starter": False,
         "locale": "en",
     }
     self.config.register_user(**defaults_user)
     self.config.register_member(**defaults_user)
     self.config.register_channel(pokemon=None)
     self.datapath = f"{bundled_data_path(self)}"
     self.maybe_spawn = {}
     self.guildcache = {}
     self.usercache = {}
     self.spawnchance = []
     self._connection = apsw.Connection(
         str(cog_data_path(self) / "pokemon.db"))
     self.cursor = self._connection.cursor()
     self.cursor.execute(PRAGMA_journal_mode)
     self.cursor.execute(PRAGMA_wal_autocheckpoint)
     self.cursor.execute(PRAGMA_read_uncommitted)
     self.cursor.execute(POKECORD_CREATE_POKECORD_TABLE)
     self._executor = concurrent.futures.ThreadPoolExecutor(1)
     self.bg_loop_task = None
示例#18
0
    def __init__(self, bot: Red):
        self.bot = bot
        self.path = str(cog_data_path(self)).replace("\\", "/")

        self.image_path = self.path + "/"

        self.config = Config.get_conf(self, identifier=9811198108111121, force_registration=True)
        default_global = {
            "messages": [],
            "images": [],
            "time": {"hour": 0, "minute": 0, "second": 0},
        }
        default_guild = {"channelid": None}

        self.config.register_global(**default_global)
        self.config.register_guild(**default_guild)
 async def on_voice_state_update(self, member, before, after):
     user_list = await self.config.get_raw('users')
     if str(member.id) in user_list:
         volume = user_list[str(member.id)]['volume']
         file_name = user_list[str(member.id)]['sfx']
         file_path = str(data_manager.cog_data_path(self)) + '/' + file_name
         if after.channel is not None and after.channel != member.guild.afk_channel and not await self.isrestricted(
                 after.channel.id):
             if before.channel is not None:
                 if before.channel.id != after.channel.id:
                     if os.path.isfile(file_path):
                         await self.playsound(file_path, volume,
                                              after.channel)
             else:
                 if os.path.isfile(file_path):
                     await self.playsound(file_path, volume, after.channel)
示例#20
0
    def __init__(self, bot: Red):
        super().__init__()
        self.bot = bot
        self.config = Config.get_conf(self, identifier=5842647, force_registration=True)
        self.config.register_guild(**BASE_GUILD)
        self.loop = asyncio.get_running_loop()

        saveFolder = data_manager.cog_data_path(cog_instance=self)
        self.logger = logging.getLogger("red.luicogs.YOURLS")
        if not self.logger.handlers:
            logPath = os.path.join(saveFolder, "info.log")
            handler = logging.FileHandler(filename=logPath, encoding="utf-8", mode="a")
            handler.setFormatter(
                logging.Formatter("%(asctime)s %(message)s", datefmt="[%d/%m/%Y %H:%M:%S]")
            )
            self.logger.addHandler(handler)
示例#21
0
    def cog_unload(self):
        datapath = cog_data_path(self)
        for guild in self.fridges.keys():
            fridge = self.fridges[guild]
            storeditems = list()
            for key in fridge.keys():
                count = fridge[key]
                for _ in range(count):
                    storeditems.append(key)
            filename = Path(datapath, f"{guild.id}.json")

            log.info(f"Writing backing store {filename}")
            with open(filename, 'w') as backingstore:
                json.dump(storeditems, backingstore)

        log.info("Unloading")
示例#22
0
文件: ewit.py 项目: IanPlu/Quotebot
    def __init__(self):
        super().__init__()

        # Get the path to the local quote csv file
        base_path = str(data_manager.cog_data_path(self)).replace("\\", "/")
        self.quotes_file = base_path + "/" + QUOTES_FILE_NAME

        # Set up the quotes csv file if it doesn't already exist
        Path(self.quotes_file).touch()
        if not os.path.isfile(self.quotes_file):
            with open(self.quotes_file, "w") as new_csv:
                logger.info("Quotes csv file not found. Creating a new one.")
                # Write quote 0 on init, so real quotes start at 1
                self.register_quote(
                    "\"Hi mortals, I'm buddy!\" - Buddy, at the dawn of time")
        logger.info("EWit Online")
示例#23
0
 async def cogpath(self, ctx: commands.Context, cog: str):
     """Get the paths for a cog."""
     cog_obj = self.bot.get_cog(cog)
     if cog_obj is None:
         await ctx.send("Could not find a cog with this name.")
         return
     cog_path = pathlib.Path(inspect.getfile(cog_obj.__class__)).parent.resolve()
     cog_data_path = pathlib.Path(data_manager.cog_data_path() / cog_obj.qualified_name).resolve()
     if not os.path.exists(cog_data_path):
         cog_data_path = None
         if not isinstance(getattr(cog_obj, "config", None), Config):
             reason = "This cog does not store any data."
         else:
             reason = "This cog had its data directory removed."
     message = "Cog path: {}\nData path: {}".format(cog_path, cog_data_path or reason)
     await ctx.send(box(message, lang="yaml"))
示例#24
0
 def __init__(self):
     self.tts_languages = list(gtts.lang.tts_langs().keys())
     self.last_track_info = None
     self.current_sfx = None
     self.config = Config.get_conf(self, identifier=134621854878007296)
     self.sound_base = (data_manager.cog_data_path(self) / 'sounds').as_posix()
     self.session = aiohttp.ClientSession()
     default_config = {
         'padding': 700,
         'tts_lang': 'en',
         'sounds': {}
     }
     self.config.register_guild(**default_config)
     lavalink.register_event_listener(self.ll_check)
     if not os.path.exists(self.sound_base):
         os.makedirs(self.sound_base)
示例#25
0
    def __init__(self, bot):
        self.bot = bot

        self.path = str(datam.cog_data_path(self)).replace('\\', '/')
        self.settings_file = 'settings'

        self.check_folder()
        self.check_file()

        self.bot.loop.create_task(self.load_settings())

        self.lf_gateway = 'http://ws.audioscrobbler.com/2.0/'

        self.payload = {}
        self.payload['api_key'] = 'c44979d5d86ff515ba9fba378c610474'
        self.payload['format'] = 'json'
示例#26
0
class Userdata:
    users = {}
    fp = cog_data_path(
        None, "gobcog"
    ) / 'users.json'  # this looks for users.json inside your RedBot/cogs/gobcog folder. Needs to be setup once: create the folder, make a users.json with just an empty {} inside.
    with fp.open('r') as f:
        users = json.load(f)

    @staticmethod
    async def save():
        with Userdata.fp.open('w') as f:
            json.dump(Userdata.users,
                      f,
                      indent=4,
                      default=lambda o: '<not serializable>',
                      sort_keys=True)
示例#27
0
    def __init__(self, bot):
        self.bot = bot
        self.session = aiohttp.ClientSession()
        self.conf = Config.get_conf(self, identifier=3271169074)
        default_guild_settings = {
            "bg_color": "black",
            "maxwords": 200,
            "excluded": [],
            "mask": None,
            "colormask": False,
        }
        self.conf.register_guild(**default_guild_settings)
        self.mask_folder = str(cog_data_path(raw_name="WordClouds")) + "/masks"

        if not os.path.exists(self.mask_folder):
            os.mkdir(self.mask_folder)
示例#28
0
 async def orly(self, ctx, box_text, title_text, small_text, image_url,
                hex):
     """O Rly?"""
     data_path = cog_data_path()
     orly_logo = os.path.join(data_path, 'orly', 'data', 'orly-logo.png')
     gara_font = os.path.join(data_path, 'orly', 'data', 'garamond.otf')
     gara_italic_font = os.path.join(data_path, 'orly', 'data',
                                     'garamond_italic.otf')
     W, H = (500, 700)
     try:
         hex = hex.replace("#", "")
     except:
         return await ctx.send("Invalid hex.")
     colour = tuple(int(hex[i:i + 2], 16) for i in (0, 2, 4)) + (255, )
     im = Image.new("RGBA", (W, H), (255, 255, 255, 255))
     draw = ImageDraw.Draw(im)
     box_font = ImageFont.truetype(gara_font, 80)
     box_size_w, box_size_h = draw.textsize(box_text, font=box_font)
     title_font = ImageFont.truetype(gara_italic_font, 18)
     title_size_w, title_size_h = draw.textsize(title_text, font=title_font)
     small_font = ImageFont.truetype(gara_italic_font, 24)
     small_size_w, small_size_h = draw.textsize(small_text, font=small_font)
     draw.line((20, 0, 480, 0), width=20, fill=colour)
     draw.line((20, 515, 480, 515), width=175, fill=colour)
     logo = Image.open(orly_logo).resize((100, 40), Image.ANTIALIAS)
     im.paste(logo, (30, 635), mask=logo)
     inp_im = (Image.open(await self.getimage(image_url)).resize(
         (350, 350), Image.ANTIALIAS)).convert("RGBA")
     im.paste(inp_im, (75, 70), mask=inp_im)
     draw.text(((W - title_size_w) / 2, 15),
               title_text,
               font=title_font,
               fill="black")
     draw.text((480 - small_size_w, 605),
               small_text,
               font=small_font,
               fill="black")
     lines = textwrap.wrap(box_text, width=10)[:2]
     line_h, pad = 443, 10
     for line in lines:
         lw, lh = draw.textsize(line, font=box_font)
         draw.text((25, line_h), line, font=box_font)
         line_h += lh + pad
     img = BytesIO()
     im.save(img, "png")
     img.seek(0)
     await ctx.send(file=discord.File(img, "orly.png"))
示例#29
0
    def __init__(self, bot: Red) -> None:
        super().__init__()
        self.bot = bot
        self.loop: asyncio.AbstractEventLoop = bot.loop
        self._executor = ThreadPoolExecutor()
        self.config = Config.get_conf(
            self, identifier=6672039729, force_registration=True
        )
        self.config.register_global(
            tier_breakdown={}, competitive_overlay=40, extramodes_overlay=70
        )
        self.config.register_user(player_id=None, platform=None)

        self.rlapi_client: rlapi.Client = None  # assigned in initialize()
        self.bundled_data_path = bundled_data_path(self)
        self.cog_data_path = cog_data_path(self)
        self._prepare_templates()
示例#30
0
 def __init__(self, bot: Red):
     super().__init__()
     self.bot = bot
     self.FOLDER = str(data_manager.cog_data_path(self))
     self.PATH_DB = self.FOLDER + "/account_registrations.db"
     self.config = Config.get_conf(self,
                                   identifier=80590423,
                                   force_registration=True)
     self.config.register_global(psy_token=None, steam_token=None)
     # Structure of rankrole_dict: {tier_n: role_id}
     self.config.register_guild(rankrole_enabled=False,
                                rankrole_dict={},
                                ignore_special=False)
     self.psy_api = PsyonixCalls(self.config)
     self.steam_api = SteamCalls(self.config)
     self.link_db = DbQueries(self.PATH_DB)
     self.json_conv = GetJsonData()
示例#31
0
    def __init__(self, bot: Red):
        super().__init__()
        self.bot = bot

        self.conf = Config.get_conf(self, identifier=998240343, force_registration=True)

        self.conf.register_global(installed=[])

        self.already_agreed = False

        self.LIB_PATH = cog_data_path(self) / "lib"
        self.SHAREDLIB_PATH = self.LIB_PATH / "cog_shared"
        self.SHAREDLIB_INIT = self.SHAREDLIB_PATH / "__init__.py"

        self.LIB_PATH.mkdir(parents=True, exist_ok=True)
        self.SHAREDLIB_PATH.mkdir(parents=True, exist_ok=True)
        if not self.SHAREDLIB_INIT.exists():
            with self.SHAREDLIB_INIT.open(mode="w", encoding="utf-8") as _:
                pass

        if str(self.LIB_PATH) not in syspath:
            syspath.insert(1, str(self.LIB_PATH))

        self._repo_manager = RepoManager()
示例#32
0
文件: core.py 项目: muddyfish/079COGS
    def __init__(self, bot):
        self.bot = bot

        self.path = str(datam.cog_data_path(self)).replace("\\", "/")
        self.attachment_path = self.path + "/attachments"

        self.check_folder()

        self.event_types = [
            "on_member_update",
            "on_voice_state_update",
            "on_message_edit",
            "on_message_delete",
            "on_raw_bulk_message_delete",
            "on_guild_channel_create",
            "on_guild_channel_delete",
            "on_guild_channel_update",
            "on_guild_update",
            "on_guild_role_create",
            "on_guild_role_delete",
            "on_guild_role_update",
            "on_member_ban",
            "on_member_unban",
            "on_member_kick",
            "on_member_remove",
            "on_member_join",
        ]

        self.config = Config.get_conf(self, identifier=6198483584)
        default_guild = {
            "enabled": False,
            "compact": False,
            "events": {},
            "ignore": {"channels": {}, "members": {}},
        }
        self.config.register_guild(**default_guild)
示例#33
0
from pathlib import Path
import logging

from .audio import Audio
from .manager import start_lavalink_server, maybe_download_lavalink
from redbot.core import commands
from redbot.core.data_manager import cog_data_path
import redbot.core

log = logging.getLogger("red.audio")

LAVALINK_DOWNLOAD_URL = (
    "https://github.com/Cog-Creators/Red-DiscordBot/releases/download/{}/Lavalink.jar"
).format(redbot.core.__version__)

LAVALINK_DOWNLOAD_DIR = cog_data_path(raw_name="Audio")
LAVALINK_JAR_FILE = LAVALINK_DOWNLOAD_DIR / "Lavalink.jar"

APP_YML_FILE = LAVALINK_DOWNLOAD_DIR / "application.yml"
BUNDLED_APP_YML_FILE = Path(__file__).parent / "data/application.yml"


async def setup(bot: commands.Bot):
    cog = Audio(bot)
    if not await cog.config.use_external_lavalink():
        await maybe_download_lavalink(bot.loop, cog)
        await start_lavalink_server(bot.loop)

    await cog.initialize()

    bot.add_cog(cog)