Example #1
0
    async def latest(self, ctx: commands.Context, version=None):
        if version is None:
            version = VersionInfo.getLatest(self.BC_VERSION_LIST.keys())
        if version not in self.BC_VERSION_LIST.keys():
            await ctx.send(
                f"Sorry but `{version}` does not seem to be a valid MC version that has BuildCraft releases."
            )
        else:
            async with ctx.typing():
                latestBC = VersionInfo.getLatest(self.BC_VERSION_LIST[version])
                latestBCinfo = await self.getVersionDetails(
                    "BuildCraft", latestBC)

                info = f"Buildcraft {latestBC}:\n[Changelog](https://www.mod-buildcraft.com/pages/buildinfo/BuildCraft/changelog/{latestBC}.html) | [Blog]({latestBCinfo['blog_entry'] if 'blog_entry' in latestBCinfo else 'https://www.mod-buildcraft.com'}) | [Direct download]({latestBCinfo['downloads']['main']})"
                if version in self.BCC_VERSION_LIST.keys():
                    latestBCC = VersionInfo.getLatest(
                        self.BCC_VERSION_LIST[version])
                    latestBCCinfo = await self.getVersionDetails(
                        "BuildCraftCompat", latestBCC)
                    info = f"{info}\n\nBuildcraft Compat {latestBCC}:\n[Changelog](https://www.mod-buildcraft.com/pages/buildinfo/BuildCraftCompat/changelog/{latestBCC}.html) | [Blog]({latestBCCinfo['blog_entry'] if 'blog_entry' in latestBCCinfo else 'https://www.mod-buildcraft.com'}) | [Direct download]({latestBCCinfo['downloads']['main']})"

                embed = disnake.Embed(
                    colour=disnake.Colour(0x54d5ff),
                    timestamp=datetime.datetime.utcfromtimestamp(time.time()),
                    description=info)
                embed.set_author(
                    name=f"BuildCraft releases for {version}",
                    url="https://www.mod-buildcraft.com/pages/download.html",
                    icon_url="https://i.imgur.com/YKGkDDZ.png")
                await ctx.send(embed=embed)
Example #2
0
 async def apexstats(self, ctx, platform: ApexPlatform, *, username):
     """about_apexstats"""
     headers = {"TRN-Api-Key": Configuration.get_master_var("APEX_KEY")}
     url = "https://public-api.tracker.gg/apex/v1/standard/profile/" + platform + "/" + (
         username)
     async with self.bot.aiosession.get(url, headers=headers) as resp:
         if resp.status == 404:
             await MessageUtils.send_to(ctx, "NO",
                                        "apexstats_user_not_found")
             return
         elif not resp.status == 200:
             await MessageUtils.send_to(ctx, "NO", "apexstats_api_error")
             return
         else:
             responsejson = await resp.json()
             embed = disnake.Embed(
                 colour=disnake.Colour(0x00cea2),
                 timestamp=datetime.datetime.utcfromtimestamp(
                     time.time()).replace(tzinfo=datetime.timezone.utc))
             embed.add_field(
                 name=Translator.translate('apexstats_username', ctx),
                 value=await Utils.clean(
                     responsejson["data"]["metadata"]["platformUserHandle"]
                 ))
             for stat_type in responsejson["data"]["stats"]:
                 type_key_name = stat_type["metadata"]["key"]
                 type_key_value = stat_type["displayValue"]
                 embed.add_field(name=Translator.translate(
                     f'apexstats_key_{type_key_name}', ctx),
                                 value=type_key_value)
             await ctx.send(embed=embed)
Example #3
0
 def load(self):
     self.config.read(f"{self.directory}/config.ini")
     self.token = str(self.config.get("server", "token"))
     self.botname = str(self.config.get("server", "name", fallback="Reaction Light"))
     # We are leaving prefix as a dummy variable for now since it is still a positional argument of commands.Bot
     self.prefix = str(self.config.get("server", "prefix", fallback="rl!"))
     self.botcolour = disnake.Colour(
         int(self.config.get("server", "colour", fallback="0xffff00"), 16)
     )
     system_channel = self.config.get("server", "system_channel", fallback=None)
     self.system_channel = int(system_channel) if system_channel else None
     self.logo = str(self.config.get("server", "logo", fallback=None))
Example #4
0
    async def set_colour(
        self,
        inter,
        colour: str = commands.Param(
            description=response.get("settings-colour-option-colour")),
    ):
        await inter.response.defer()
        try:
            self.bot.config.botcolour = disnake.Colour(int(colour, 16))
            self.bot.config.update("server", "colour", colour)
            example = disnake.Embed(
                title=response.get("example-embed"),
                description=response.get("example-embed-new-colour"),
                colour=self.bot.config.botcolour,
            )
            await inter.edit_original_message(
                content=response.get("colour-changed"), embed=example)

        except ValueError:
            await inter.edit_original_message(
                content=response.get("colour-hex-error"))
Example #5
0
 async def setup(self, ctx):
     post = {'_id': ctx.author.id, 'locale': 'ru'}
     if collection.count_documents({'_id': ctx.author.id}) == 0:
         collection.insert_one(post)
     role1 = disnake.utils.get(ctx.guild.roles, name='Deafened')
     role = disnake.utils.get(ctx.guild.roles, name='Muted')
     if role and role1 != None:
         emb = disnake.Embed(
             description='Все нужные роли уже присутсвуют на сервере.',
             color=disnake.Color.orange())
         return await ctx.send(embed=emb)
     emb = disnake.Embed(
         description=
         'С написанием этой команды на сервер добавлены роли, если их нет. Они будут созданы автоматически, если будут вызваны команды `mute` или `deaf`',
         color=disnake.Color.orange())
     await ctx.send(embed=emb)
     if role == None:
         await ctx.guild.create_role(name='Muted',
                                     colour=disnake.Colour(0x000001),
                                     reason='Создано командой setup.')
     if role1 == None:
         await ctx.guild.create_role(name='Deafened',
                                     color=disnake.Color(0x000001),
                                     reason='Создано командой setup.')
Example #6
0
    async def about(self, ctx):
        """about_help"""
        uptime = datetime.datetime.utcnow().replace(
            tzinfo=datetime.timezone.utc) - self.bot.start_time
        hours, remainder = divmod(int(uptime.total_seconds()), 3600)
        days, hours = divmod(hours, 24)
        minutes, seconds = divmod(remainder, 60)
        tacos = str(round(self.bot.eaten))
        user_messages = str(self.bot.user_messages)
        bot_messages = str(self.bot.bot_messages)
        self_messages = str(self.bot.self_messages)
        total = str(sum(len(guild.members) for guild in self.bot.guilds))
        unique = str(len(self.bot.users))
        embed = disnake.Embed(
            colour=disnake.Colour(0x00cea2),
            timestamp=datetime.datetime.utcfromtimestamp(
                time.time()).replace(tzinfo=datetime.timezone.utc),
            description=f"Stats for cluster {self.bot.cluster}\n" +
            MessageUtils.assemble(ctx,
                                  'DIAMOND',
                                  'about_spinning_gears',
                                  duration=Translator.translate(
                                      'dhms',
                                      ctx,
                                      days=days,
                                      hours=hours,
                                      minutes=minutes,
                                      seconds=seconds)) + "\n" +
            MessageUtils.assemble(ctx,
                                  'GOLD',
                                  'about_messages',
                                  user_messages=user_messages,
                                  bot_messages=bot_messages,
                                  self_messages=self_messages) + "\n" +
            MessageUtils.assemble(
                ctx, 'IRON', 'about_grinders', errors=self.bot.errors) + "\n" +
            MessageUtils.assemble(
                ctx,
                'STONE',
                'about_commands',
                commandCount=self.bot.commandCount,
                custom_command_count=self.bot.custom_command_count) + "\n" +
            MessageUtils.assemble(
                ctx, 'WOOD', 'about_guilds', guilds=len(self.bot.guilds)) +
            "\n" + MessageUtils.assemble(
                ctx, 'INNOCENT', 'about_users', total=total, unique=unique) +
            "\n" +
            MessageUtils.assemble(ctx, 'TACO', 'about_tacos', tacos=tacos) +
            "\n" + MessageUtils.assemble(
                ctx, 'ALTER', 'commit_hash', hash=self.bot.version) + '\n' +
            MessageUtils.assemble(ctx, 'TODO', 'about_stats'))

        click_here = Translator.translate('click_here', ctx)
        embed.add_field(name=Translator.translate('support_server', ctx),
                        value=f"[{click_here}](https://disnake.gg/vddW3D9)")
        embed.add_field(name=Translator.translate('website', ctx),
                        value=f"[{click_here}](https://gearbot.rocks)")
        embed.add_field(
            name=f"Github",
            value=f"[{click_here}](https://github.com/gearbot/GearBot)")
        embed.set_footer(text=self.bot.user.name,
                         icon_url=self.bot.user.display_avatar.url)

        await ctx.send(embed=embed)
Example #7
0
async def updater(cog: BCVersionChecker):
    GearbotLogging.info("Started BC version checking background task")
    session: aiohttp.ClientSession = cog.bot.aiosession
    lastUpdate = 0
    while cog.running:
        try:
            # check for a newer bc version
            async with session.get(
                    'https://www.mod-buildcraft.com/build_info_full/last_change.txt'
            ) as reply:
                stamp = await reply.text()
                stamp = int(stamp[:-1])
                if stamp > lastUpdate:
                    GearbotLogging.info("New BC version somewhere!")
                    lastUpdate = stamp
                    cog.BC_VERSION_LIST = await getList(session, "BuildCraft")
                    cog.BCC_VERSION_LIST = await getList(
                        session, "BuildCraftCompat")
                    highestMC = VersionInfo.getLatest(
                        cog.BC_VERSION_LIST.keys())
                    latestBC = VersionInfo.getLatest(
                        cog.BC_VERSION_LIST[highestMC])
                    generalID = 309218657798455298
                    channel: disnake.TextChannel = cog.bot.get_channel(
                        generalID)
                    old_latest = Configuration.get_persistent_var(
                        "latest_bc", "0.0.0")
                    Configuration.set_persistent_var(
                        "latest_bc", latestBC
                    )  # save already so we don't get stuck and keep trying over and over if something goes wrong
                    if channel is not None and latestBC != old_latest:
                        GearbotLogging.info(
                            f"New BuildCraft version found: {latestBC}")
                        notify_channel = cog.bot.get_channel(
                            349517224320565258)
                        await notify_channel.send(
                            f"{Emoji.get_chat_emoji('WRENCH')} New BuildCraft version detected ({latestBC})"
                        )
                        GearbotLogging.info(
                            f"Fetching metadata for BuildCraft {latestBC}")
                        message = await notify_channel.send(
                            f"{Emoji.get_chat_emoji('REFRESH')} Fetching metadata..."
                        )
                        info = await cog.getVersionDetails(
                            "BuildCraft", latestBC)
                        GearbotLogging.info(f"Metadata acquired: {info}")
                        await message.edit(
                            content=
                            f"{Emoji.get_chat_emoji('YES')} Metadata acquired")
                        if 'blog_entry' in info:
                            message = await notify_channel.send(
                                f"{Emoji.get_chat_emoji('REFRESH')} Updating general topic..."
                            )
                            newTopic = f"General discussions about BuildCraft.\n" \
                                f"Latest version: {latestBC}\n" \
                                f"Full changelog and download: {info['blog_entry']}"
                            await channel.edit(topic=newTopic)
                            await message.edit(
                                content=
                                f"{Emoji.get_chat_emoji('YES')} Topic updated")
                        else:
                            notify_channel.send(
                                f"{Emoji.get_chat_emoji('WARNING')} No blog post data found, notifying <@180057061353193472>"
                            )

                        # message = await notify_channel.send(f"{Emoji.get_chat_emoji('REFRESH')} Uploading files to CurseForge...")
                        # code, output, errors = await Utils.execute(f'cd BuildCraft/uploader && gradle curseforge -Pnew_version="{latestBC}"')
                        # GearbotLogging.info(f"Upload to CF complete\n)------stdout------\n{output}\n------stderr------\n{errors}")
                        # if code is 0:
                        #     content = f"{Emoji.get_chat_emoji('YES')} All archives successfully uploaded"
                        #     await message.edit(content=content)
                        # else:
                        #     content = f"{Emoji.get_chat_emoji('NO')} Upload failed with code {code}, notifying <@106354106196570112>"
                        #     await notify_channel.send(content)

            # update FAQs if needed
            async with session.get(
                    'https://mod-buildcraft.com/website_src/faq.md') as reply:
                data = await reply.text()
                h = hashlib.md5(data.encode('utf-8')).hexdigest()
                old = Configuration.get_persistent_var("BCFAQ", "")
                channel = cog.bot.get_channel(361557801492938762)  # FAQs
                if channel is not None and h != old:
                    Configuration.set_persistent_var("BCFAQ", h)
                    #clean the old stuff
                    await channel.purge()

                    #send banner
                    with open("BuildCraft/FAQs.png", "rb") as file:
                        await channel.send(file=File(file, filename="FAQs.png")
                                           )
                    #send content
                    out = ""
                    parts = [
                        d.strip("#").strip() for d in data.split("##")[1:]
                    ]
                    for part in parts:
                        lines = part.splitlines()
                        content = '\n'.join(lines[1:])
                        out += f"**```{lines[0].strip()}```**{content}\n"
                    for page in Pages.paginate(out,
                                               max_chars=2048,
                                               max_lines=50):
                        embed = Embed(description=page)
                        await channel.send(embed=embed)

                pass
        except CancelledError:
            pass  # bot shutdown
        except Exception as ex:
            cog.bot.errors = cog.bot.errors + 1
            GearbotLogging.error(
                "Something went wrong in the BC version checker task")
            GearbotLogging.error(traceback.format_exc())
            embed = disnake.Embed(colour=disnake.Colour(0xff0000),
                                  timestamp=datetime.datetime.utcfromtimestamp(
                                      time.time()))
            embed.set_author(
                name="Something went wrong in the BC version checker task:")
            embed.add_field(name="Exception", value=str(ex))
            v = ""
            for line in traceback.format_exc().splitlines():
                if len(v) + len(line) >= 1024:
                    embed.add_field(name="Stacktrace", value=v)
                    v = ""
                v = f"{v}\n{line}"
            if len(v) > 0:
                embed.add_field(name="Stacktrace", value=v)
            await GearbotLogging.bot_log(embed=embed)
        for i in range(1, 60):
            if cog.force or not cog.running:
                break
            await asyncio.sleep(10)

    GearbotLogging.info("BC version checking background task terminated")