Beispiel #1
0
async def city_cost(ctx: lightbulb.Context) -> None:
    city = ctx.options.city

    if city >= 2:
        prev_city = city - 1
        cost = pwpy.utils.city_cost(city)

        output = f"The cost to go from city {prev_city} to {city} are as follows"
        embed = hikari.Embed(description=output)
        embed.add_field(name="Base", value=f"${cost:,.2f}")
        embed.add_field(name="5% Off", value=f"${cost * .95:,.2f}")

        if city >= 12:
            embed.add_field(name="UP + 5% Off",
                            value=f"${(cost - 50000000) * .95:,.2f}")

        if city >= 17:
            embed.add_field(name="AUP + 5% Off",
                            value=f"${(cost - 150000000) * .95:,.2f}")

        await ctx.respond(embed=embed)

    else:
        output = "You must specify a city greater than 1 to be purchased!"
        embed = hikari.Embed(description=output)
        await ctx.respond(embed=embed)
    async def on_serverplayers_error(self, event):
        conn = mysql.connector.connect(host=HOST,
                                       user=USER,
                                       passwd=PASSWD,
                                       database=DATABASE)
        c = conn.cursor()

        c.execute(
            f"SELECT lan FROM language WHERE guild_id = '{event.message.guild_id}'"
        )
        result = c.fetchone()
        if isinstance(event.exception, lightbulb.errors.NotEnoughArguments):
            if result is None:
                embed = hikari.Embed(
                    title="❌ **Error**",
                    description="You need to write ip or ipname",
                    color=COLOR)
                message = await event.message.respond(embed=embed)
                return message
            else:
                embed = hikari.Embed(title=get_lang(result[0], "error"),
                                     description=get_lang(
                                         result[0], "setname_error"),
                                     color=COLOR)
                message = await event.message.respond(embed=embed)
                return message
Beispiel #3
0
    async def code(self, ctx) -> None:
        start = time.monotonic()
        command = ctx.message.content[:7]
        channel = self.bot.cache.get_guild_channel(ctx.message.channel_id)
        code = ctx.message.content[len(command) + 1:]
        await self.bot.rest.trigger_typing(channel)
        if code.startswith('```') and code.endswith('```'):
            code = '\n'.join(code.split('\n')[1:-1])
        else:
            code = code.strip('` \n')
        env = {
				"bot": self.bot,
				"client": self.bot,
				"msg": ctx.message,
				"message": ctx.message,
				"server_id": ctx.message.guild_id,
				"guild_id": ctx.message.guild_id,
				"channel_id": ctx.message.channel_id,
				"author": ctx.message.author,
				"eprint": self.eprint,
				"ctx": ctx
		}
        env.update(globals())
        stdout = io.StringIO()

        new_forced_async_code = f"async def code():\n{textwrap.indent(code, '    ')}"
        try:
            exec(new_forced_async_code, env)
        except Exception as error:
            embed = hikari.Embed(
				title="Failed to execute.",
				description=f"{error} ```py\n{traceback.format_exc()}\n```\n```py\n{error.__class__.__name__}\n```",
				colour=(255, 10, 40)
			)
            await ctx.reply(embed=embed)
            await ctx.message.add_reaction("❌")
            return
        code = env["code"]
        try:
            with redirect_stdout(stdout):
                result = await code()
        except Exception as error:
            value = stdout.getvalue()
            embed = hikari.Embed(
				title="Failed to execute.",
				description=f"{error} ```py\n{traceback.format_exc()}\n```",
				colour=(255, 10, 40)
			)
            await ctx.reply(embed=embed)
            await ctx.message.add_reaction("❌")
            return
        value = stdout.getvalue()
        millis = (time.monotonic() - start) * 1000
        em = hikari.Embed(
			title=f"Executed in {int(millis):,.2f}ms",
			description=f"\n\nStdout:\n```py\n# Python {platform.python_version()} - Hikari {hikari.__version__} - lightbulb {lightbulb.__version__} \n\n{value if value != '' else None}```\nReturned:\n```py\n{result}\n```",
			color=(40, 255, 10)
		)
        await ctx.message.add_reaction("✅")
        await ctx.reply(embed=em)
 async def playertime(self, ctx, ip: str, *, name: str):
     conn = mysql.connector.connect(host=HOST,
                                    user=USER,
                                    passwd=PASSWD,
                                    database=DATABASE)
     c = conn.cursor()
     c.execute(
         f"SELECT ip FROM costumers WHERE guild_id = '{ctx.get_guild().id}' AND ipname = '{ip}'"
     )
     mgeli = c.fetchone()
     c.execute(
         f"SELECT lan FROM language WHERE guild_id = '{ctx.get_guild().id}'"
     )
     lang = c.fetchone()
     conn.commit()
     if mgeli is not None:
         core = scraper.GTcore(mgeli[0])
         graph_player_time = core.player_time(name)
         embed = hikari.Embed(title=name, color=COLOR)
         embed.set_image(f"https:{graph_player_time}")
         await ctx.respond(embed=embed)
     else:
         core = scraper.GTcore(ip)
         if core.checkip() == False:
             await ctx.respond(
                 get_lang("en", "player_response_error") if lang is None
                 else get_lang(lang[0], "player_response_error"))
         else:
             graph_player_time = core.player_time(name)
             embed = hikari.Embed(title=name, color=COLOR)
             embed.set_image(f"https:{graph_player_time}")
             await ctx.respond(embed=embed)
Beispiel #5
0
 async def code(self, ctx) -> None:
     if str(ctx.message.author.id) in self.bot.owner_ids:
         channel = self.bot.cache.get_guild_channel(ctx.message.channel_id)
         code = ctx.message.content[len(command) + 1:]
         await self.bot.rest.trigger_typing(channel)
         if code.startswith('```') and code.endswith('```'):
             code = '\n'.join(code.split('\n')[1:-1])
         else:
             code = code.strip('` \n')
         env = {
             "bot": self.bot,
             "client": self.bot,
             "msg": ctx.message,
             "message": ctx.message,
             "server_id": ctx.message.guild_id,
             "guild_id": ctx.message.guild_id,
             "channel_id": ctx.message.channel_id,
             "author": ctx.message.author,
             "eprint": self.eprint,
             "ctx": ctx
         }
         env.update(globals())
         stdout = io.StringIO()
         new_forced_async_code = f"async def code():\n{textwrap.indent(code, '    ')}"
         try:
             exec(new_forced_async_code, env)
         except Exception as error:
             embed = hikari.Embed(
                 title="Failed to execute.",
                 description=
                 f"{error} ```py\n{traceback.format_exc()}\n```\n```py\n{error.__class__.__name__}\n```",
                 colour=(255, 10, 40))
             await ctx.reply(embed=embed)
             await ctx.message.add_reaction("❌")
             return
         code = env["code"]
         try:
             with redirect_stdout(stdout):
                 result = await code()
         except Exception as error:
             value = stdout.getvalue()
             embed = hikari.Embed(
                 title="Failed to execute.",
                 description=f"{error} ```py\n{traceback.format_exc()}\n```",
                 colour=(255, 10, 40))
             await ctx.reply(embed=embed)
             await ctx.message.add_reaction("❌")
             return
         value = stdout.getvalue()
         em = hikari.Embed(title="Output",
                           description=f"```py\n{result}\n```",
                           color=(40, 255, 10))
         await ctx.reply(embed=em)
         await ctx.message.add_reaction("✅")
Beispiel #6
0
async def pokemon_route(ctx:tanjun.abc.SlashContext, pokemon:str, version:str):

    try:
        possibilities = ["red","blue","diamond","pearl","platinum","yellow","gold","silver","crystal","firered","leafgreen","heartgold","soulsilver","ruby","sapphire","emerald","x","y","omega-ruby","alpha-sapphire","black","white"]

        matches = difflib.get_close_matches(
            version.lower(), possibilities, n=1, cutoff=0.3)

        pokemondata = (requests.get("https://pokeapi.co/api/v2/pokemon/{}/encounters".format(pokemon.lower()))).json()

        vlist = []
        dlist = []
        

        for x in pokemondata:
            version = x["version_details"][0]
            if version["version"]["name"] == matches[0]:
                vlist.append(x)
            else:
                if version["version"]["name"]:
                    dlist.append(version["version"]["name"])
                    dlist = list(set(dlist))

        if len(vlist) > 0:
            embed = hikari.Embed(
                title = pokemon.title() + " Routes " "- Version: " + matches[0].title(),
                color = hikari.Color(0xee1515)
                )

            for y in vlist:
                version = y["version_details"][0]
                name = y["location_area"]["name"].replace("-", " ")
                embed.add_field(name=name.title(), value="Encounter Potential: " + str(version["max_chance"]) + "%", inline=False)

            await ctx.respond(embed)
            
        elif len(vlist) <= 1 and dlist == []:
            await ctx.respond("This pokemon cannot be found in wild grass.")
            
        elif vlist == [] and len(dlist) > 0:
            embed = hikari.Embed(
                title = pokemon.title() + " can be found in these versions!",
                color = hikari.Color(0xee1515)
                )
            for x in dlist:
                embed.add_field(name=x.title(), value="\u200b", inline=True)

            await ctx.respond(embed)   
            
    except JSONDecodeError:
        await ctx.respond("Make sure the pokemon's name is typed correctly!")
Beispiel #7
0
async def whois(ctx):
    member = ctx.options.member
    handle = ctx.options.handle

    query = Query()
    username, linked_username, pfp = None, None, None
    if handle:
        user = None
        try:
            user = await query.get_user(handle)
        except ObjectNotFound:
            username = None
        if user:
            handle = user.username
            author_id = query.get_handle_user(handle, ctx.get_guild().id)
            username = handle
            if author_id:
                member = ctx.get_guild().get_member(author_id)
                linked_username = member.nickname or member.username
                pfp = member.avatar_url
    elif member:
        handle = query.get_handle(member.id, ctx.get_guild().id)
        username = member.nickname or member.username
        if handle:
            linked_username = handle
            pfp = await query.get_pfp(handle)
    if linked_username:
        embed = hikari.Embed(
            color=0xFCDB05,
            title=escape_markdown(f"{username} is {linked_username}"),
        )
        embed.set_thumbnail(pfp)
        return await ctx.respond(embed=embed)
    elif username:
        embed = hikari.Embed(
            title=escape_markdown(f"{username} is not linked with any account here"),
            color=0xFCDB05,
        )
        return await ctx.respond(embed=embed)

    name = None
    if member:
        name = member.nickname or member.username
    embed = hikari.Embed(
        title=escape_markdown(f"Nothing found on {handle or name}"),
        color=0xFCDB05,
    )
    await ctx.respond(embed=embed)
Beispiel #8
0
    async def about(self, ctx):
        """Tells you about the bot itself."""
        now = datetime.datetime.utcnow(
        )  # Timestamp of when uptime function is run
        delta = now - start_time
        hours, remainder = divmod(int(delta.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)
        if days:
            time_format = (
                "**{d}** days, **{h}** hours, **{m}** minutes, and **{s}** seconds."
            )
        else:
            time_format = "**{h}** hours, **{m}** minutes, and **{s}** seconds."
        uptime_stamp = time_format.format(d=days,
                                          h=hours,
                                          m=minutes,
                                          s=seconds)
        embed = hikari.Embed(
            title=f"About {self.bot.me.username}",
            color="#326fa8",
            url="https://github.com/ahnaf-zamil/shikamaru-bot",
        )
        owner = await self.bot.rest.fetch_user(int(self.bot.owner_ids[0]))
        embed.set_thumbnail(self.bot.me.avatar_url)
        embed.add_field(name="Owner",
                        value=f":point_right: {owner} :point_left:")
        # Statistics
        t = t = f"""```py
Python Version: {platform.python_version()}
Hikari Version: {hikari.__version__}
```
        """
        osinfo = platform.uname()
        pid = os.getpid()
        py = psutil.Process(pid)
        loop = asyncio.get_running_loop()
        ram_usage = await loop.run_in_executor(None,
                                               self.process.memory_full_info)
        ram_usage = ram_usage.rss / 1024**2
        cpu_usage = await loop.run_in_executor(
            None, self.process.cpu_percent) / await loop.run_in_executor(
                None, psutil.cpu_count)
        embed.add_field(
            name="OS",
            value=f"{osinfo.system} {osinfo.version} {osinfo.machine}")

        embed.add_field(name="Uptime", value=uptime_stamp)
        embed.add_field(name="Commands loaded",
                        value=len(list(self.bot.commands)))
        embed.add_field(
            name="Process",
            value=
            f"```Memory: {ram_usage:.2f} MB\nCPU: {psutil.cpu_percent(interval=None, percpu=False)}%```",
            inline=True,
        )
        embed.add_field(name="Libraries", value=t)
        embed.set_footer(text=str(self.bot.me), icon=self.bot.me.avatar_url)
        embed.timestamp = datetime.datetime.now().astimezone()
        await ctx.reply(embed=embed)
Beispiel #9
0
async def on_message(event: hikari.MessageCreateEvent) -> None:
    if not event.message.content or not event.message.content.startswith(prefix) or not event.is_human:
        return

    arguments = event.message.content[len(prefix)].split()

    if arguments[0] == "member":
        if not event.message.guild_id:
            await event.message.respond("Cannot use this command in a DM")
            return

        try:
            member = await cache.get_member(event.message.guild_id, int(arguments[1]))

        except sake.errors.EntryNotFound:
            await event.message.respond(content="Member not found.")

        except ValueError:
            await event.message.respond(content="Invalid ID passed.")

        except IndexError:
            await event.message.respond(content="Missing ID.")

        else:
            embed = (
                hikari.Embed(title=f"Member: {member}")
                .set_thumbnail(member.avatar_url)
                .add_field(name="Joined server", value=member.joined_at.strftime("%d/%m/%y %H:%M %|"))
                .add_field(name="Roles", value=",".join(map(str, member.role_ids)))
                .add_field(name="Is bot", value=str(member.is_bot).lower())
            )
            await event.message.respond(embed=embed)
Beispiel #10
0
async def cache_command(
    ctx: tanjun.abc.Context,
    cache: alluka.Injected[hikari.api.Cache],
    me: typing.Annotated[hikari.OwnUser,
                         tanjun.inject_lc(hikari.OwnUser)],
    process: typing.Annotated[psutil.Process,
                              tanjun.cached_inject(psutil.Process)],
) -> None:
    """Get general information about this bot."""
    start_date = datetime.datetime.fromtimestamp(process.create_time())
    uptime = datetime.datetime.now() - start_date
    memory_usage: float = process.memory_full_info().uss / 1024**2
    cpu_usage: float = process.cpu_percent() / psutil.cpu_count()
    memory_percent: float = process.memory_percent()

    cache_stats_lines: list[tuple[str, float]] = []

    storage_start_time = time.perf_counter()
    for line_template, callback in _about_lines:
        line_start_time = time.perf_counter()
        line = line_template.format(callback(cache))
        cache_stats_lines.append(
            (line, (time.perf_counter() - line_start_time) * 1_000))

    storage_time_taken = time.perf_counter() - storage_start_time
    # This also accounts for the decimal place and 4 decimal places
    left_pad = math.floor(
        math.log(max(num for _, num in cache_stats_lines), 10)) + 6
    largest_line = max(len(line) for line, _ in cache_stats_lines)
    cache_stats = "\n".join(
        line + " " * (largest_line + 2 - len(line)) +
        "{0:0{left_pad}.4f} ms".format(time_taken, left_pad=left_pad)
        for line, time_taken in cache_stats_lines)

    embed = (hikari.Embed(
        description="An experimental pythonic Hikari bot.", color=0x55CDFC
    ).set_author(
        name="Hikari: testing client",
        icon=me.avatar_url or me.default_avatar_url,
        url=hikari.__url__
    ).add_field(
        name="Uptime",
        value=str(uptime),
        inline=True
    ).add_field(
        name="Process",
        value=
        f"{memory_usage:.2f} MB ({memory_percent:.0f}%)\n{cpu_usage:.2f}% CPU",
        inline=True,
    ).add_field(
        name="Standard cache stats", value=f"```{cache_stats}```"
    ).set_footer(
        icon="http://i.imgur.com/5BFecvA.png",
        text=
        f"Made with Hikari v{hikari.__version__} (python {platform.python_version()})",
    ))

    await ctx.respond(content=f"{storage_time_taken * 1_000:.4g} ms",
                      embed=embed,
                      component=utility.delete_row(ctx))
Beispiel #11
0
async def on_message_create(event: hikari.MessageCreateEvent) -> None:
    if not event.is_human or not event.message.content or not event.message.content.startswith(
            prefix):
        return

    arguments = event.message.content[len(prefix):]

    if arguments[0] == "user":
        try:
            user = await cache.get_user(int(arguments[1]))

        except sake.EntryNotFound:
            await event.message.respond(content="User not found.")

        except ValueError:
            await event.message.respond(content="Invalid user ID passed.")

        except IndexError:
            await event.message.respond(content="Missing user ID.")

        else:
            embed = (hikari.Embed(title=str(user)).add_field(
                name="Is bot", value=str(user.is_bot).lower()).add_field(
                    name="Joined Discord",
                    value=user.created_at.strftime(
                        "%d/%m/%y %H:%M %|")).set_thumbnail(user.avatar_url))
            await event.message.respond(embed=embed)
Beispiel #12
0
async def role_command(ctx: tanjun.abc.Context, role: hikari.Role) -> None:
    """Get information about a role in the current guild.

    Arguments:
        * role: Mention or ID of the role to get information about.
    """
    if role.guild_id != ctx.guild_id:
        raise tanjun.CommandError("Role not found")

    permissions = utility.basic_name_grid(role.permissions) or "None"
    role_information = [
        f"Created: {tanjun.conversion.from_datetime(role.created_at)}",
        f"Position: {role.position}"
    ]

    if role.colour:
        role_information.append(f"Color: `{role.colour}`")

    if role.is_hoisted:
        role_information.append("Member list hoisted")

    if role.is_managed:
        role_information.append("Managed by an integration")

    if role.is_mentionable:
        role_information.append("Can be mentioned")

    embed = hikari.Embed(
        colour=role.colour,
        title=role.name,
        description="\n".join(role_information) +
        f"\n\nPermissions:\n{permissions}",
    )
    await ctx.respond(embed=embed, component=utility.delete_row(ctx))
Beispiel #13
0
    async def spotify_cache(self, ctx: Context) -> None:
        """Displays the Spotify cache."""
        client = self.spotify_client
        embed = (hikari.Embed(title="Spotify Cache").add_field(
            name="Color",
            value=f"{plural(len(client.color_cache)):color,}",
            inline=True,
        ).add_field(
            name="Text",
            value=f"{plural(len(client.text_cache)):text,}",
            inline=True,
        ).add_field(
            name="Images",
            value=f"- {plural(len(client.album_cache)):album,}\n"
            f"- {plural(len(client.code_cache)):code,}",
            inline=True,
        ).add_field(
            name="Album",
            value=f"{plural(len(client.cache.albums)):object}\n"
            f"{plural(len(client.cache.get_queries('album'))):query|queries,}",
            inline=True,
        ).add_field(
            name="Artist",
            value=f"{plural(len(client.cache.artists)):object}\n"
            f"{plural(len(client.cache.get_queries('artist'))):query|queries,}",
            inline=True,
        ).add_field(
            name="Track",
            value=f"{plural(len(client.cache.tracks)):object}\n"
            f"w/{len(client.cache.audio_features)} audio features\n"
            f"{plural(len(client.cache.get_queries('track'))):query|queries,}",
            inline=True,
        ))

        await ctx.respond(embed=embed)
Beispiel #14
0
    async def do_rtfm(self, ctx, site, key, obj):
        if not site in self.docs_links:
            await ctx.reply("RTFM not available for " + str(site) + ".")
            return
        print(self.docs_links[site])
        page_types = {
            'latest': self.docs_links[site],
        }

        if obj is None:
            await ctx.send(page_types[key])
            return

        if not hasattr(self, '_rtfm_cache'):
            #await ctx.trigger_typing()
            await self.build_rtfm_lookup_table(page_types)

        cache = list(self._rtfm_cache[key].items())

        def transform(tup):
            return tup[0]

        matches = fuzzy.finder(obj, cache, key=lambda t: t[0], lazy=False)[:8]

        e = hikari.Embed(title=f"Reading the docs are a drag...")
        if len(matches) == 0:
            return await ctx.reply('Could not find anything. Sorry.')
        e.timestamp = datetime.utcnow()
        e.description = '\n'.join(f'[`{key}`]({url})' for key, url in matches)
        await ctx.reply(embed=e)
Beispiel #15
0
 async def on_command_error(self, event):
     # Logging error to file and printing it to the standard output
     if (
         type(event.exception) == lightbulb.errors.CommandIsOnCooldown
     ):  # Checking if error is a cooldown error
         # If error is a cooldown error then the bot is sending a cooldown message to the channel.
         channel = await self.bot.rest.fetch_channel(event.message.channel_id)
         em = hikari.Embed(title="Command on cooldown", color="#ff0000")
         em.add_field(
             name="Hold up man!",
             value=f"This command is on cooldown. You can run it in **{int(event.exception.retry_in)}** seconds.",
         )
         em.timestamp = datetime.now().astimezone()
         await channel.send(em)
         return
     now = datetime.now()
     tinfo = traceback.format_exception(
         type(event.exception), event.exception, tb=event.traceback
     )
     print("".join(tinfo))
     error = (
         f"{now.strftime('%Y-%m-%d %H:%M:%S')} [Command Error] User: \"{event.message.author}\", Message: \"{event.message.content[:30]}\", Error: \"{event.exception}\", Traceback: \""
         + "".join(tinfo).replace("\n", "")
         + '"'
     )
     async with aiofiles.open("bot.log", "a+") as f:
         await f.write(f"{error}\n")
Beispiel #16
0
def get_default_embed(author: hikari.Member = None, **kwargs) -> hikari.Embed:
    '''
    Return a default embed to work with for consistency.

    Parameter:
    - `author`: The author to set in the footer.
    - `**kwargs`: `hikari.Embed` constructor.
    '''

    title = kwargs.get("title")
    url = kwargs.get("url")
    description = kwargs.get("description")
    color = kwargs.get("color") if kwargs.get("color") is not None else DefaultColor.green()
    timestamp = kwargs.get("timestamp")

    embed = hikari.Embed(
        title = title,
        url = url,
        description = description,
        color = color,
        timestamp = timestamp
    )
    if author is not None:
        embed.set_footer(
            text = f"Requested by {author.username}",
            icon = author.avatar_url
        )
    
    return embed
Beispiel #17
0
async def count(ctx: tanjun.abc.SlashContext, game: str) -> None:
    results = await SteamSearch(game)

    appID = results[0]
    name = results[1]

    gsdata = (requests.get(
        "https://store.steampowered.com/api/appdetails/?appids={}&l=english".
        format(appID))).json()

    codata = (requests.get(
        "https://api.steampowered.com/ISteamUserStats/GetNumberOfCurrentPlayers/v1/?appid={}"
        .format(appID))).json()

    check = codata["response"]

    if check.get("player_count") not in check.values():
        await ctx.respond("This game currently does not have players online.")

    else:
        player_count = codata["response"]["player_count"]
        appdetails = gsdata.get("{}".format(appID)).get("data")

        embed = hikari.Embed(title=name,
                             description="There are currently " +
                             "`{}`".format(player_count) + " playing.",
                             color=hikari.Color(0x808080))

        embed.set_thumbnail(appdetails["header_image"])

        await ctx.respond(embed)
Beispiel #18
0
async def about(ctx: lightbulb.Context) -> None:
    bot = ctx.bot
    embed = hikari.Embed()

    description = """
    Requiem is a specially crafted discord bot built to provide the largest
    number of tools and resources for the politics and war community in a
    convenient and easy to use package. Requiem is, always has been, and
    always will be free to use for everyone. Have a feature request or an
    issue to report? Consider dropping by the Requiem [support server](https://discord.gg/uTXdx7J)!
    Want to take a look at my inner workings or fork Requiem? Take a look
    at my [repo](https://github.com/GodEmpressVerin/requiem)!
    """

    embed.add_field(name="Requiem Version",
                    value=__init__.__version__,
                    inline=True)
    embed.add_field(name="Hikari Version",
                    value=hikari.__version__,
                    inline=True)
    embed.add_field(name="Lightbulb Version",
                    value=lightbulb.__version__,
                    inline=True)
    embed.add_field(name="Commands Executed",
                    value=bot.executed_commands,
                    inline=True)
    embed.add_field(name="Time Alive", value="N/A", inline=True)
    embed.add_field(name="About Requiem", value=description)

    await ctx.respond(embed=embed)
Beispiel #19
0
async def userinfo(ctx: lightbulb.Context):
    member = ctx.options.user

    if not member:
        member = ctx.member

    embed = hikari.Embed()

    embed.add_field(name="Username", value=member.username)

    if member.nickname and member.nickname != member.username:
        embed.add_field(name="Nickname", value=member.nickname)

    embed.add_field(name="Snowflake", value=str(member.id))

    created_at = member.created_at.strftime("%A %B %d, %Y")
    embed.add_field(name="Account Created On", value=created_at)

    joined_at = member.joined_at.strftime("%A %B %d, %Y")
    embed.add_field(name="Member Joined On:", value=joined_at)

    embed.add_field(name="Roles", value=str(len(member.role_ids)))

    top_role = member.get_top_role()
    embed.add_field(name="Top Role", value=str(top_role))

    embed.set_thumbnail(member.avatar_url)

    await ctx.respond(embed=embed)
Beispiel #20
0
async def mtg_rulings(ctx:tanjun.abc.SlashContext, card:str):


    try:
        mtgdata = (requests.get("https://api.magicthegathering.io/v1/cards?name={}&pageSize=1&contains=imageUrl".format(card.lower()))).json()

        card = mtgdata.get("cards")[0]

        rulings = card["rulings"]        

        embed = hikari.Embed(
            title = "Rulings.",
            color = hikari.Color(0xFF0000)
        )

        embed.set_thumbnail(card["imageUrl"])

        for x in rulings:
            embed.add_field(name="Date: {}".format(x["date"]), value= x["text"], inline=False)

        await ctx.respond(embed)
    
    except IndexError:
        await ctx.respond("Please double check the spelling of the card.")

    except KeyError:
        await ctx.respond("This card does not have any rulings.")
    async def currentmap(self, ctx, *, ip: str):
        conn = mysql.connector.connect(host=HOST,
                                       user=USER,
                                       passwd=PASSWD,
                                       database=DATABASE)
        c = conn.cursor()

        c.execute(
            f"SELECT ip FROM costumers WHERE guild_id = '{ctx.get_guild().id}' AND ipname = '{ip}'"
        )
        result = c.fetchone()
        c.execute(
            f"SELECT lan FROM language WHERE guild_id = '{ctx.get_guild().id}'"
        )
        lang = c.fetchone()
        conn.commit()
        if result is not None:
            core = scraper.GTcore(result[0])
            title = core.name()
            map = core.map()
            map_image = core.mapimage()
            scanned = core.scan()

            embed = hikari.Embed(title=title,
                                 description=f"`{map}`",
                                 color=COLOR)
            embed.set_image("https:" + map_image)
            embed.set_footer(text=scanned)
            message = await ctx.respond(embed=embed)
        else:
            core = scraper.GTcore(ip)
            if core.checkip() == False:
                await ctx.respond(
                    get_lang("en", "ip_error") if lang is None else get_lang(
                        lang[0], "ip_error"))
            else:
                title = core.name()
                map = core.map()
                map_image = core.mapimage()
                scanned = core.scan()

                embed = hikari.Embed(title=title,
                                     description=f"`{map}`",
                                     color=COLOR)
                embed.set_image("https:" + map_image)
                embed.set_footer(text=scanned)
                await ctx.respond(embed=embed)
Beispiel #22
0
 async def run(self, ctx, user: lightbulb.member_converter=None):
     """Go for a jog or run away from someone"""
     async with aiofiles.open("shikamaru/txt/run_gifs.txt", mode="r") as f:
         gif_ls = await f.readlines()
     if user != None:
         embed = hikari.Embed(
             title=f"{ctx.message.author} is running away from {user}!",
             color="#dba951",
         )
     else:
         embed = hikari.Embed(
             title=f"{ctx.message.author} is running!", color="#dba951"
         )
     embed.set_footer(text=f"Requested by: {ctx.message.author}")
     embed.set_image(random.choice(gif_ls))
     embed.timestamp = datetime.datetime.now().astimezone()
     await ctx.reply(embed)
Beispiel #23
0
async def rating(ctx):
    """Plot rating progression"""
    peak = ctx.options.peak
    usernames = ctx.options.usernames

    query = Query()
    if usernames == []:
        usernames = [query.get_handle(ctx.author.id, ctx.get_guild().id)]

    try:
        users = await asyncio.gather(*[query.get_user(username) for username in usernames])
    except ObjectNotFound:
        return await ctx.respond("User not found")

    usernames = [user.username for user in users]
    for i in range(len(users)):
        if users[i] is None:
            return await ctx.respond(f"{usernames[i]} does not exist on DMOJ")
    if len(users) > 10:
        return await ctx.respond("Too many users given, max 10")

    cond = [Contest_DB.rankings.contains(user.username) for user in users]
    q = session.query(Contest_DB).filter(or_(*cond)).filter(Contest_DB.is_rated == 1)
    contests = q.all()

    def get_rating_change(rankings, users):
        ret = {}
        for ranking in rankings:
            for user in users:
                if user.username == ranking["user"] and ranking["new_rating"]:
                    ret[user.username] = ranking["new_rating"]
        return ret

    data = {}
    data["users"] = [user.username for user in users]
    userPrevRating = {}
    for contest in contests:
        changes = get_rating_change(contest.rankings, users)
        data[contest.end_time] = []
        for user in users:
            if user.username in changes and (
                not peak or changes[user.username] >= userPrevRating.get(user.username, -9999)
            ):
                change = changes[user.username]
                userPrevRating[user.username] = change
                data[contest.end_time].append(change)
            else:
                data[contest.end_time].append(None)
    plot_rating(data)

    embed = hikari.Embed(
        title="Rating Progression",
        color=0xFCDB05,
    )
    with open("./graphs/plot.png", "rb") as file:
        embed.set_image(hikari.Bytes(file.read(), "plot.png"))

    return await ctx.respond(embed=embed)
    async def info(self, ctx, *, ip: str):
        conn = mysql.connector.connect(host=HOST,
                                       user=USER,
                                       passwd=PASSWD,
                                       database=DATABASE)
        c = conn.cursor()

        c.execute(
            f"SELECT ip FROM costumers WHERE guild_id = '{ctx.get_guild().id}' AND ipname = '{ip}'"
        )
        result = c.fetchone()
        c.execute(
            f"SELECT lan FROM language WHERE guild_id = '{ctx.get_guild().id}'"
        )
        lang = c.fetchone()
        conn.commit()
        if result is not None:
            core = scraper.GTcore(result[0])
            title = core.name()
            banner = core.banner()
            scanned = core.scan()
            servermanager = core.servermanager()

            embed = hikari.Embed(title=title, color=COLOR)
            embed.add_field(name="Server Manager:", value=servermanager)
            embed.set_image("https:" + banner)
            embed.set_footer(text=scanned)
            await ctx.respond(embed=embed)
        else:
            core = scraper.GTcore(ip)
            if core.checkip() == False:
                await ctx.respond(
                    get_lang("en", "ip_error") if lang is None else get_lang(
                        lang[0], "ip_error"))
            else:
                title = core.name()
                banner = core.banner()
                scanned = core.scan()
                servermanager = core.servermanager()

                embed = hikari.Embed(title=title, color=COLOR)
                embed.add_field(name="Server Manager:", value=servermanager)
                embed.set_image("https:" + banner)
                embed.set_footer(text=scanned)
                await ctx.respond(embed=embed)
Beispiel #25
0
async def specials(ctx: tanjun.abc.SlashContext) -> None:

    locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

    sdata = (requests.get(
        "http://store.steampowered.com/api/featuredcategories/&l=english")
             ).json()

    specials = sdata["specials"]["items"]

    special1 = specials[0]
    special2 = specials[1]
    special3 = specials[2]
    special4 = specials[3]
    special5 = specials[4]

    embed = hikari.Embed(
        title="Specials",
        url="https://store.steampowered.com/search/?specials=1",
        color=hikari.Color(0xE6E6FA))

    embed.add_field(name=special1["name"],
                    value="Price: " +
                    locale.currency(float(special1["final_price"]) / 100.0) +
                    "\nDiscount Ends: " + datetime.datetime.fromtimestamp(
                        special1["discount_expiration"]).strftime('%m/%d/%Y'),
                    inline=False)

    embed.add_field(name=special2["name"],
                    value="Price: " +
                    locale.currency(float(special2["final_price"]) / 100.0) +
                    "\nDiscount Ends: " + datetime.datetime.fromtimestamp(
                        special2["discount_expiration"]).strftime('%m/%d/%Y'),
                    inline=False)

    embed.add_field(name=special3["name"],
                    value="Price: " +
                    locale.currency(float(special3["final_price"]) / 100.0) +
                    "\nDiscount Ends: " + datetime.datetime.fromtimestamp(
                        special3["discount_expiration"]).strftime('%m/%d/%Y'),
                    inline=False)

    embed.add_field(name=special4["name"],
                    value="Price: " +
                    locale.currency(float(special4["final_price"]) / 100.0) +
                    "\nDiscount Ends: " + datetime.datetime.fromtimestamp(
                        special4["discount_expiration"]).strftime('%m/%d/%Y'),
                    inline=False)

    embed.add_field(name=special5["name"],
                    value="Price: " +
                    locale.currency(float(special5["final_price"]) / 100.0) +
                    "\nDiscount Ends: " + datetime.datetime.fromtimestamp(
                        special5["discount_expiration"]).strftime('%m/%d/%Y'),
                    inline=False)

    await ctx.respond(embed)
Beispiel #26
0
    async def guild(self, context: Context, guild_id: guild_converter = None):
        guild: typing.Union[hikari.GatewayGuild, hikari.RESTGuild] = (
            guild_id or (self.bot.cache.get_available_guild(context.guild_id)
                         or await self.bot.rest.fetch_guild(context.guild_id))
            if context.guild_id else None)

        if guild is None:
            return context.reply("Please provide a guild.")

        now = datetime.now(tz=timezone.utc)

        created_at = guild.created_at.astimezone(timezone.utc)

        created_at = f"{created_at.strftime(self.date_format)}. {display_time_from_delta((now - created_at), granularity=2)} ago."
        roles = self.bot.cache.get_roles_view_for_guild(
            guild.id).values() or await self.bot.rest.fetch_roles(guild.id)
        roles = sorted(
            [r for r in roles if r.position != 0],
            key=lambda r: r.position,
            reverse=True,
        )
        roles_names_or_mentions = ([
            f"<@&{role.id}>" for role in roles
        ] if guild.id == context.guild_id else [role.name for role in roles])
        await context.reply(
            hikari.Embed(
                title="Inspect Guild",
                colour=randint(0, 0xFFFFFF),
                timestamp=now,
                description=f"**Name:** `{guild.name}`\n"
                f"**ID:** `{guild.id}`\n"
                f"**Owner:** `{self.bot.cache.get_user(guild.owner_id) or await self.bot.rest.fetch_user(guild.owner_id)}`\n"
                f"**Members:** `{len(guild.members)}`\n"
                f"**• Humans:** `{len([member for member in guild.members.values() if not member.is_bot])}`\n"
                f"**• Bots:** `{len([member for member in guild.members.values() if member.is_bot])}`\n"
                f"**Roles:** `{len(guild.roles)}`\n"
                f"**Emojis:** `{len(guild.emojis)}`\n"
                f"**Created at:** `{created_at}`\n"
                f"**Channels:** `{len(guild.channels)}`\n"
                f"**• Categories:** `{len(list(filter(lambda channel: isinstance(channel, hikari.GuildCategory), guild.channels.values())))}`\n"
                f"**• Text:** `{len(list(filter(lambda channel: isinstance(channel, hikari.GuildTextChannel), guild.channels.values())))}`\n"
                f"**• Voice:** `{len(list(filter(lambda channel: isinstance(channel, hikari.GuildVoiceChannel), guild.channels.values())))}`\n"
                f"**Region:** `{guild.region}`\n"
                f"**AFK Channel:** {f'<#{guild.afk_channel_id}>' if guild.afk_channel_id else '`None`'}\n"
                f"**AFK Timeout:** `{guild.afk_timeout}`\n"
                f"**System Channel:** <#{guild.system_channel_id}>\n"
                f"**MFA Enforced:** `{'Yes' if guild.mfa_level else 'No'}`\n"
                f"**Verification Level:** `{guild.verification_level}`",
            ).set_footer(
                text=f"Requested by {ctx_name(context)}",
                icon=context.member.avatar_url,
            ).set_thumbnail(guild.icon_url).add_field(
                inline=False,
                name=f"Roles [{len(roles)}]",
                value=", ".join(roles_names_or_mentions) or "@everyone",
            ))
Beispiel #27
0
        def _(index: int, content: str) -> hikari.Embed:
            content = f"```{file_ext}\n{content}```"
            embed = hikari.Embed(
                title="Github",
                description=content,
                url=github_path
            )
            embed.set_footer(text=f"Page {index}/{len(paginator)}")

            return embed
Beispiel #28
0
 def make_embed(index, page):
     return hikari.Embed(
         title=f"Code for {child.name}",
         description=page,
         colour=randint(0, 0xFFF),
         timestamp=datetime.now(tz=timezone.utc),
     ).set_footer(
         text=f"{index}/{len(paginator)}",
         icon=context.author.avatar_url,
     )
Beispiel #29
0
 def make_page(index, page):
     return hikari.Embed(
         title=f"Executed in {(datetime.now(tz=timezone.utc) - start).total_seconds() * 1000:.2f}ms",
         colour=0x58EF92 if self.success else 0xE74C3C,
         description=f"Result: {page}",
         timestamp=datetime.now(tz=timezone.utc),
     ).set_footer(
         text=f"Page {index}/{len(paginator)}",
         icon=self.context.author.avatar_url,
     )
Beispiel #30
0
 async def github(self, ctx):
     """
     Gives link to Shikamaru's GitHub repository
     """
     em = hikari.Embed(title="Shikamaru's GitHub", color="#4dffa6")
     em.description = "[Click here](https://github.com/ahnaf-zamil/shikamaru-bot) to go to Shikamaru's GitHub page"
     em.set_footer(text=str(self.bot.me), icon=self.bot.me.avatar_url)
     em.timestamp = datetime.datetime.now().astimezone()
     em.set_footer(text=str(self.bot.me), icon=self.bot.me.avatar_url)
     await ctx.reply(embed=em)