How to use the cogs.utils.translation._ function in Cogs

To help you get started, we’ve selected a few Cogs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github henry232323 / RPGBot / cogs / pets.py View on Github external
key = key.strip().casefold()
                            value = value.strip()
                            pet["stats"][key] = int(value)
                        else:
                            break
                    except:
                        await ctx.send(await _(ctx, "Invalid formatting! Try again"))
                        count += 1
                        if count >= 3:
                            await ctx.send(await _(ctx, "Too many failed attempts, cancelling!"))
                            return
                        continue
                    continue

            pet["meta"] = dict()
            await ctx.send(await _(ctx, "Any additional data? (Format like the above, for example "
                                        "nature: hasty, color: brown)"))
            count = 0
            while True:
                response = await self.bot.wait_for("message", check=check, timeout=120)
                if response.content.lower() == "cancel":
                    await ctx.send(await _(ctx, "Cancelling!"))
                    return
                elif response.content.lower() == "skip":
                    await ctx.send(await _(ctx, "Skipping!"))
                    break
                else:
                    try:
                        if "\n" in response.content:
                            res = response.content.split("\n")
                        else:
                            res = response.content.split(",")
github henry232323 / RPGBot / cogs / settings.py View on Github external
async def loadstarwarsshop(self, ctx):
        """This command will pre-load all Star Wars items and make them available in shop
        Requires Bot Moderator or Bot Admin"""
        items = {}
        for item, value in self.bot.switems.items():
            try:
                items[item] = dict(buy=int("".join(filter(str.isdigit, value["meta"]["Cost"].split(" ")[0]))), sell=0, level=0)
            except:
                continue

        await self.bot.di.add_shop_items(ctx.guild, items)
        await ctx.send(await _(ctx, "Successfully added all Star Wars items to shop!"))
github henry232323 / RPGBot / cogs / map.py View on Github external
return
            elif level < 1:
                await ctx.send(
                    await _(ctx, "Only Patrons may make more than 3 maps! See https://www.patreon.com/henry232323"))
                return

        await ctx.send(await _(ctx,
                               "What available tiles will there be? Say `done` when done. Use the * tile to describe all tiles "
                               "when adding what will spawn. One at a time send the name of the tile. i.e. grassland"))

        generators = []
        spawners = {}

        check = lambda x: x.channel.id == ctx.channel.id and x.author.id == ctx.author.id
        while True:
            await ctx.send(await _(ctx, "What kind of tile is it? Say `done` when done"))
            msg = await self.bot.wait_for("message", check=check, timeout=60)
            tile = msg.content.strip()
            if tile == "done":
                break
            elif tile != "*":
                generators.append(tile)
            await ctx.send(await _(ctx,
                                   "What things might spawn in those tiles? Split terms with commas. (Equal chance of each, repeat a term "
                                   "for greater chance) `skip` to skip"
                                   ))
            msg = await self.bot.wait_for("message", check=check, timeout=60)
            if msg.content.lower() == "skip":
                continue
            spawners[(len(generators) - 1) if tile != "*" else -1] = Counter(x.strip() for x in msg.content.split(","))

        new_map = self.create_map(xsize, ysize, generators, spawners)
github henry232323 / RPGBot / cogs / characters.py View on Github external
return
            elif response.content.lower() == "skip":
                await ctx.send(await _(ctx, "Skipping!"))
                break
            else:
                try:
                    if "\n" in response.content:
                        res = response.content.split("\n")
                    else:
                        res = response.content.split(",")
                    for val in res:
                        key, value = val.split(": ")
                        key = key.strip()
                        value = value.strip()
                        if len(key) + len(value) > 1024:
                            await ctx.send(await _(ctx, "Can't have an attribute longer than 1024 characters!"))
                            return
                        character["meta"][key] = value
                    else:
                        break
                except:
                    await ctx.send(await _(ctx, "Invalid formatting! Try again"))
                    count += 1
                    if count >= 3:
                        await ctx.send(await _(ctx, "Too many failed attempts, cancelling!"))
                        return
                    continue

        character["level"] = character["meta"].pop("level", None)
        if (len(ctx.message.mentions) > 0 and ouser is None) or (len(ctx.message.mentions) > 1 and ouser is not None):
            newname = character["name"].replace("!", "")
            data = await self.bot.db.get_guild_data(ctx.guild)
github henry232323 / RPGBot / cogs / economy.py View on Github external
async def _sell(self, ctx, item: str, amount: IntConverter):
        """Sell an item to the shop
        Example: rp!shop sell Apple 5"""
        amount = abs(amount)
        shop = await self.bot.di.get_guild_shop(ctx.guild)
        iobj = shop.get(item)
        if not iobj or not iobj["sell"]:
            await ctx.send(await _(ctx, "This item cannot be sold!"))
            return

        async with self.bot.di.rm.lock(ctx.author.id):
            try:
                await self.bot.di.take_items(ctx.author, (item, amount))
            except ValueError:
                await ctx.send(await _(ctx, "You don't have enough to sell"))
                return

            await self.bot.di.add_eco(ctx.author, iobj["sell"] * amount)
        await ctx.send((await _(ctx, "Successfully sold {} {}s")).format(amount, item))
github henry232323 / RPGBot / cogs / misc.py View on Github external
embed.add_field(name=await _(ctx, "Uptime"), value=await self.bot.get_bot_uptime())
        embed.add_field(name=await _(ctx, "Servers"), value=(await _(ctx, "{} servers")).format(len(self.bot.guilds)))
        embed.add_field(name=await _(ctx, "Commands Run"),
                        value=(await _(ctx, '{} commands')).format(sum(self.bot.commands_used.values())))

        total_members = sum(len(s.members) for s in self.bot.guilds)
        total_online = sum(1 for m in self.bot.get_all_members() if m.status != discord.Status.offline)
        unique_members = set(map(lambda x: x.id, self.bot.get_all_members()))
        channel_types = Counter(isinstance(c, discord.TextChannel) for c in self.bot.get_all_channels())
        voice = channel_types[False]
        text = channel_types[True]
        embed.add_field(name=await _(ctx, "Total Members"),
                        value=(await _(ctx, '{} ({} online)')).format(total_members, total_online))
        embed.add_field(name=await _(ctx, "Unique Members"), value='{}'.format(len(unique_members)))
        embed.add_field(name=await _(ctx, "Channels"),
                        value=(await _(ctx, '{} text channels, {} voice channels')).format(text, voice))
        embed.add_field(name=await _(ctx, "Shards"),
                        value=(await _(ctx, 'Currently running {} shards. This server is on shard {}')).format(
                            ctx.bot.shard_count, getattr(ctx.guild, "shard_id", 0)))

        # a = monotonic()
        # await (await ctx.bot.shards[getattr(ctx.guild, "shard_id", 0)].ws.ping())
        # b = monotonic()
        # ping = "{:.3f}ms".format((b - a) * 1000)

        embed.add_field(name=await _(ctx, "CPU Percentage"), value="{}%".format(psutil.cpu_percent()))
        embed.add_field(name=await _(ctx, "Memory Usage"), value=self.bot.get_ram())
        embed.add_field(name=await _(ctx, "Observed Events"), value=sum(self.bot.socket_stats.values()))
        # embed.add_field(name=await _(ctx, "Ping"), value=ping)

        embed.add_field(name=await _(ctx, "Source"), value="[Github](https://github.com/henry232323/RPGBot)")
github henry232323 / RPGBot / cogs / settings.py View on Github external
async def setdefaultmap(self, ctx, value: str):
        """Set the server's custom prefix. The default prefix will continue to work.
        Example:
            rp!setprefix ! --> !setprefix rp!

        Requires Bot Moderator or Bot Admin"""
        await self.bot.di.set_default_map(ctx.guild, value)
        await ctx.send(await _(ctx, "Updated default map"))
github henry232323 / RPGBot / cogs / map.py View on Github external
await attachment.save(file)
        file.seek(0)
        mapspace, mapdata = self.parsemap(file)
        xsize, ysize = len(mapspace[0]), len(mapspace)
        level = self.bot.patrons.get(ctx.guild.id, 0)

        if xsize > 64 or ysize > 64:
            if level == 0:
                await ctx.send(await _(ctx, "Only Patrons may make maps larger than 64x64 tiles!"))
                return
            elif level > 0:
                if xsize > 256 or ysize > 256:
                    if level > 5:
                        if xsize > 2048 or ysize > 2048:
                            await ctx.send(
                                await _(ctx, "You may not make maps greater than 2048x2048 unless they are infinite!"))
                            return
                    else:
                        await ctx.send(await _(ctx, "Only higher tier Patrons may make maps greater than 256x256"))
                        return

        maps = await self.bot.di.get_maps(ctx.guild)
        if len(maps) >= 3:
            if len(maps) >= 5:
                if len(maps) >= 10:
                    await ctx.send(
                        await _(ctx, "You cannot make more than 10 maps as of now! (Ask Henry if you really want it)"))
                    return
                elif level < 5:
                    await ctx.send(
                        await _(ctx, "You cannot make more than 5 maps unless you are a higher level Patron!"))
                    return
github henry232323 / RPGBot / cogs / settings.py View on Github external
embed.add_field(name=await _(ctx, "Starting Money"),
                        value=f"{settings['start']} {settings.get('currency', 'dollars')}")
        embed.add_field(name=await _(ctx, "Items"), value="{} {}".format(len(settings['items']), await _(ctx, "items")))
        embed.add_field(name=await _(ctx, "Characters"),
                        value="{} {}".format(len(settings['characters']), await _(ctx, "characters")))
        embed.add_field(name=await _(ctx, "Maps"),
                        value=await _(ctx, "None") if not settings.get("maps") else "\n".join(
                            (x if x != settings.get("default_map") else f"**{x}**") for x in settings["maps"]))
        embed.add_field(name=await _(ctx, "Currency"), value=f"{settings.get('currency', 'dollars')}")
        embed.add_field(name=await _(ctx, "Language"), value=f"{settings.get('language', 'en')}")
        embed.add_field(name=await _(ctx, "Experience Enabled"), value=f"{settings.get('exp', True)}")
        embed.add_field(name=await _(ctx, "Prefix"), value=f"{settings.get('prefix', 'rp!')}")
        embed.add_field(name=await _(ctx, "Hide Inventories"), value=f"{settings.get('hideinv', False)}")
        embed.add_field(name=await _(ctx, "Wipe Userdata on Leave"), value=f"{settings.get('wipeonleave', False)}")
        time = settings.get('msgdel', 0)
        embed.add_field(name=await _(ctx, "Message Auto Delete Time"), value=f"{time if time is not 0 else 'Never'}")
        await ctx.send(embed=embed)
github henry232323 / RPGBot / cogs / economy.py View on Github external
async def search(self, ctx, *, item: str):
        """Search the market for an item.
        Example: rp!market search Banana"""
        um = await self.bot.di.get_guild_market(ctx.guild)
        market = [i for i in um.values() if i['item'] == item]
        desc = await _(ctx, """
        \u27A1 to see the next page
        \u2B05 to go back
        \u274C to exit
        """)
        if not market:
            await ctx.send(await _(ctx, "No items on the market to display."))
            return

        emotes = ("\u2B05", "\u27A1", "\u274C")
        embed = discord.Embed(description=desc, title=await _(ctx, "Player Market"), color=randint(0, 0xFFFFFF), )
        embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url)

        chunks = []
        for i in range(0, len(market), 25):
            chunks.append(market[i:i + 25])

        i = 0
        try:
            users = get(ctx.guild.members, id=[x['user'] for x in chunks[i]])
        except Exception:
            br = []
            fr = dict()
            for listing, data in um.items():
                for datum in data:
                    if 'item' not in listing:
                        id = self.bot.randsample()