Exemplo n.º 1
0
        triggers=(
            yuyo.pagination.LEFT_DOUBLE_TRIANGLE,
            yuyo.pagination.LEFT_TRIANGLE,
            yuyo.pagination.STOP_SQUARE,
            yuyo.pagination.RIGHT_TRIANGLE,
            yuyo.pagination.RIGHT_DOUBLE_TRIANGLE,
        ),
        timeout=datetime.timedelta(
            days=99999),  # TODO: switch to passing None here
    )
    first_response = await paginator.get_next_entry()
    executor = utility.paginator_with_to_file(
        ctx,
        paginator,
        make_files=lambda: [
            _bytes_from_io(stdout, "stdout.py"),
            _bytes_from_io(stderr, "stderr.py")
        ])

    assert first_response is not None
    content, embed = first_response
    message = await ctx.respond(content=content,
                                embed=embed,
                                components=executor.builders,
                                ensure_result=True)
    component_client.set_executor(message, executor)


load_sudo = (tanjun.Component(name="sudo", strict=True).add_check(
    tanjun.checks.OwnerCheck()).load_from_scope().make_loader())
Exemplo n.º 2
0
import re
import os
import requests
import nltk
import asyncio
from hashashin.search import SteamSearch
import locale
import random

nltk.download('punkt')

STEAM_KEY = os.environ.get("STEAM_KEY")

api = WebAPI(key=STEAM_KEY)

component = tanjun.Component()


@component.with_slash_command
@tanjun.with_str_slash_option("game", "The name of the game.")
@tanjun.as_slash_command("search", "Search for a game.")
async def command_search(ctx: tanjun.abc.SlashContext, game: str) -> None:

    results = await SteamSearch(game)

    appID = results[0]

    await _game_embed(ctx, appID)


@component.with_slash_command
Exemplo n.º 3
0
        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))


@tanjun.as_message_command("invite")
@tanjun.as_slash_command("invite", "Invite the bot to your server(s)")
async def invite_command(
    ctx: tanjun.abc.Context,
    me: typing.Annotated[hikari.OwnUser,
                         tanjun.inject_lc(hikari.OwnUser)]
) -> None:
    await ctx.respond(
        f"https://discord.com/oauth2/authorize?client_id={me.id}&scope=bot%20applications.commands&permissions=8",
        component=utility.delete_row(ctx),
    )


load_basic = tanjun.Component(name="basic",
                              strict=True).load_from_scope().make_loader()
Exemplo n.º 4
0
def tanjun_docs_command(
    ctx: tanjun.abc.Context,
    component_client: alluka.Injected[yuyo.ComponentClient],
    index: typing.Annotated[DocIndex, alluka.inject(callback=tanjun_index)],
    **kwargs: typing.Any,
) -> _CoroT[None]:
    return _docs_command(ctx, component_client, index, TANJUN_PAGES, TANJUN_PAGES + "/master/", "Tanjun", **kwargs)


yuyo_index = tanjun.dependencies.data.cache_callback(
    utility.FetchedResource(YUYO_PAGES + "/master/search.json", PdocIndex.from_json),
    expire_after=datetime.timedelta(hours=12),
)


@_with_docs_message_options
@tanjun.as_message_command("docs yuyo")
@docs_group.with_command
@_with_docs_slash_options(yuyo_index)
@tanjun.as_slash_command("yuyo", "Search Yuyo's documentation")
def yuyo_docs_command(
    ctx: tanjun.abc.Context,
    component_client: alluka.Injected[yuyo.ComponentClient],
    index: typing.Annotated[DocIndex, alluka.inject(callback=yuyo_index)],
    **kwargs: typing.Any,
) -> _CoroT[None]:
    return _docs_command(ctx, component_client, index, YUYO_PAGES, YUYO_PAGES + "/master/", "Yuyo", **kwargs)


load_docs = tanjun.Component(name="docs").load_from_scope().make_loader()
Exemplo n.º 5
0
            ),
            "tanjun",
            "Find the references for types in Tanjun",
        ),
        tanjun_index,
    ))
tanjun_command = _with_index_message_options(
    tanjun.MessageCommand(tanjun_command.callback, "references tanjun"))

yuyo_index = (ReferenceIndex(
    track_builtins=True,
    track_3rd_party=True).index_module(yuyo, recursive=True).index_module(
        hikari, recursive=True).scan_module(yuyo, recursive=True))
yuyo_command = reference_group.with_command(
    _with_index_slash_options(
        tanjun.SlashCommand(
            _IndexCommand(
                yuyo_index,
                f"Yuyo v{yuyo.__version__}",
            ),
            "yuyo",
            "Find the references for a Yuyo type in Yuyo",
        ),
        yuyo_index,
    ))
yuyo_command = _with_index_message_options(
    tanjun.MessageCommand(yuyo_command.callback, "references yuyo"))

load_reference = tanjun.Component(
    name="reference").load_from_scope().make_loader()
Exemplo n.º 6
0
                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!")

component = tanjun.Component().add_slash_command(poke_group)

@tanjun.as_loader
def load_component(client: tanjun.abc.Client) -> None:
    client.add_component(component.copy())
Exemplo n.º 7
0
@tanjun.with_argument("url", converters=urllib.parse.urlparse)
@tanjun.as_message_command("check_domain", "check domain")
@tanjun.with_str_slash_option("url",
                              "The domain to check",
                              converters=urllib.parse.urlparse)
@tanjun.as_slash_command(
    "check_domain",
    'Check whether a domain is on Discord\'s "bad" domain list')
async def check_domain(
    ctx: tanjun.abc.Context,
    url: urllib.parse.ParseResult,
    bad_domains: typing.Annotated[list[str], domain_hashes],
) -> None:
    domain = url.netloc or url.path
    domain_hash = hashlib.sha256(domain.encode("utf-8")).hexdigest()
    if domain_hash in bad_domains:
        await ctx.respond(
            content="\N{LARGE RED SQUARE} Domain is on the bad domains list.",
            component=utility.delete_row(ctx),
        )
    else:
        await ctx.respond(
            content=
            "\N{LARGE YELLOW SQUARE} Domain is not on the bad domains list.",
            component=utility.delete_row(ctx),
        )


load_external = tanjun.Component(
    name="external").load_from_scope().make_loader()
Exemplo n.º 8
0
    members_only: bool,
    **kwargs: typing.Any,
) -> None:
    found_authors = set[hikari.Snowflake]()
    banner = await _MultiBanner.build(
        ctx,
        reason=f"Bulk ban triggered by {ctx.author.username}#{ctx.author.discriminator} ({ctx.author.id})",
        delete_message_days=clear_message_days,
        members_only=members_only,
    )
    authors = (
        iter_messages(ctx, **kwargs, users=None)
        .map(lambda message: message.author.id)
        .filter(lambda author: author not in found_authors)
    )

    await ctx.respond("Starting bans \N{THUMBS UP SIGN}", component=utility.delete_row(ctx), delete_after=2)
    async for author in authors:
        found_authors.add(author)
        await banner.try_ban(author)

    content, attachment = banner.make_response()
    # Remove once abc.Context has attachments support
    if isinstance(ctx, tanjun.abc.SlashContext):
        await ctx.create_followup(content, attachment=attachment, component=utility.delete_row(ctx))
    else:
        await ctx.respond(content, attachment=attachment, component=utility.delete_row(ctx))


load_moderation = tanjun.Component(name="moderation").load_from_scope().make_loader()
Exemplo n.º 9
0
import hikari
import tanjun
import lavasnek_rs
import typing
import asyncio

music = tanjun.Component()

async def _join_voice(ctx: tanjun.abc.Context, lavalink: lavasnek_rs.Lavalink) -> typing.Optional[hikari.Snowflake]:
    assert ctx.guild_id is not None

    if ctx.client.cache and ctx.client.shards:
        if (voice_state := ctx.client.cache.get_voice_state(ctx.guild_id, ctx.author)) is None:
            await ctx.respond("You have to be connected to a voice channel!", delete_after=10)
            return None

        await ctx.client.shards.update_voice_state(ctx.guild_id, voice_state.channel_id, self_deaf=True)
        conn = await lavalink.wait_for_full_connection_info_insert(ctx.guild_id)
        await lavalink.create_session(conn)
        return voice_state.channel_id

    return None





@music.with_slash_command
@tanjun.with_str_slash_option("song", "Song title or youtube link.")
@tanjun.as_slash_command("play", "Play a song, or add to queue.")
async def play_as_slash(ctx: tanjun.abc.SlashContext, song: str, lavalink: lavasnek_rs.Lavalink = tanjun.injected(type=lavasnek_rs.Lavalink)) -> None:
Exemplo n.º 10
0
@tanjun.with_str_slash_option("card", "Card with similar names to pull up.")
@tanjun.as_slash_command("list", "Look up a list of cards.")
async def mtg_list(ctx:tanjun.abc.SlashContext, card:str):

    try:

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

        cards = mtgdata.get("cards")
            

        embed = hikari.Embed(
            title = "Cards",
            color = hikari.Color(0x228b22)
        )


        for x in cards:
            embed.add_field(name=x["name"], value="Set: " + x["setName"], inline=False)

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


component = tanjun.Component().add_slash_command(mtg_group)


@tanjun.as_loader
def load_component(client: tanjun.abc.Client) -> None:
    client.add_component(component.copy())
Exemplo n.º 11
0
    """Get information about the UTF-8 characters in the executing message.

    Running `char file...` will ensure that the output is always sent as a markdown file.
    """
    if len(characters) > 20:
        file = True

    content: hikari.UndefinedOr[str]
    content = "\n".join(_format_char_line(char, file) for char in characters)
    response_file: hikari.UndefinedOr[hikari.Bytes] = hikari.UNDEFINED

    # highly doubt this'll ever be over 1990 when file is False but better safe than sorry.
    if file or len(content) >= 1990:
        response_file = hikari.Bytes(content.encode(),
                                     "character-info.md",
                                     mimetype="text/markdown; charset=UTF-8")
        content = hikari.UNDEFINED

    else:
        content = content

    await ctx.respond(content=content or "hi there",
                      component=utility.delete_row(ctx))

    if response_file is not hikari.UNDEFINED:
        await ctx.edit_last_response(content=None, attachment=response_file)


load_utility = tanjun.Component(name="utility",
                                strict=True).load_from_scope().make_loader()