Ejemplo n.º 1
0
async def close(ctx, user: Option(
    str, "@Tag the user, then press TAB"), mode: Option(
        str,
        "Write, click or select an option with the arrow keys, then press TAB",
        choices=["Regular", "Stale"])):
    """Ask if the ticket can be closed"""
    if "Staff" not in str(ctx.author.roles):
        await ctx.respond(":warning: Insufficient permission.", ephemeral=True)
        return

    if mode == "Regular":
        embed = discord.Embed(
            title=
            "If there's nothing else we can help you with, we would like to go ahead close this ticket now.",
            description=
            "You can either do this yourself by scrolling up to the start of the ticket and then clicking the \"Close\" button, or just let us know that you've read this and we'll do it."
        )
        embed.set_footer(
            text=
            "And feel free to open a new ticket at any time if there's something we can do for you!"
        )
    else:
        embed = discord.Embed(
            title="If you still require help, please answer now.",
            description=
            "It's been a while now since you last sent a message and we will go ahead close this ticket soon."
        )
    await ctx.respond(content=f"{user}", embed=embed)
Ejemplo n.º 2
0
 async def drake(
         self,
         ctx: discord.ApplicationContext,
         upper_text: Option(str, "Tekst g贸rny"),
         bottom_text: Option(str, "Tekst dolny"),
 ):
     lines = [upper_text, bottom_text]
     await ctx.defer()
     template = Image.open("assets/drake/template.jpg")
     font = ImageFont.truetype("assets/drake/impact.ttf", 40)
     d1 = ImageDraw.Draw(template)
     offset = 20
     for line in textwrap.wrap(lines[0].strip(), width=15):
         d1.text((360, offset), line, font=font, fill="#000000")
         offset += font.getsize(line)[1]
     offset = 383
     for line in textwrap.wrap(lines[1].strip(), width=15):
         d1.text((360, offset), line, font=font, fill="#000000")
         offset += font.getsize(line)[1]
     img = BytesIO()
     template.save(img, "PNG")
     img.seek(0)
     embed = discord.Embed()
     embed.title = "Tw贸j mem z Drake"
     embed.set_image(url="attachment://drake.png")
     await ctx.send_followup(embed=embed,
                             file=discord.File(img, filename="drake.png"))
Ejemplo n.º 3
0
    async def spoiler(
        self,
        ctx: ApplicationContext,
        preset: Option(str,
                       description="The preset you want generate.",
                       required=True,
                       autocomplete=autocomplete_alttpr),
        festive: Option(str,
                        description="Use the festive randomizer? (default no)",
                        choices=["yes", "no"],
                        required=False,
                        default="no"),
    ):
        """
        Generates an ALTTP Randomizer Spoiler Race on https://alttpr.com
        """
        await ctx.defer()
        spoiler = await generate_spoiler_game(preset, festive=festive == "yes")

        embed = await spoiler.seed.embed(emojis=self.bot.emojis)
        embed.insert_field_at(0, name="Preset", value=preset, inline=False)
        embed.insert_field_at(0,
                              name="Spoiler Log URL",
                              value=spoiler.spoiler_log_url,
                              inline=False)

        await ctx.respond(embed=embed)
Ejemplo n.º 4
0
    async def msg(self, ctx, token: Option(str,
                                           "Game token to send the message."),
                  msg: Option(str, "Message to send to the game.")):
        """
        Send a command to the multiworld server.
        """
        result = await http.request_generic(
            url=f'http://localhost:5000/game/{token}',
            method='get',
            returntype='json')

        if not result.get('success', True):
            raise SahasrahBotException("That game does not exist.")

        if not result['admin']:
            raise SahasrahBotException(
                'You must be the creator of the game to send messages to it.')

        data = {'msg': msg}
        response = await http.request_json_put(
            url=f'http://localhost:5000/game/{token}/msg',
            data=data,
            returntype='json')

        if response.get('success', True) is False:
            raise SahasrahBotException(
                response.get(
                    'error',
                    'Unknown error occured while processing message.'))

        if 'resp' in response and response['resp'] is not None:
            await ctx.respond(response['resp'])
Ejemplo n.º 5
0
 async def boost(self, ctx,
                 action: Option(str,
                                "Выберите раздел",
                                required=True,
                                choices=["Список", "Добавить", "Удалить"],
                                default="Список"),
                 channel: Option(discord.TextChannel,
                                 "Канал который добавить/удалить из списка",
                                 required=False,
                                 default=None)):
     if action == "Список":
         embed = await boostChannels.list(ctx)
         await ctx.send(embed=embed)
     elif action == "Добавить":
         if channel:
             embed = await boostChannels.add(ctx, channel)
             await ctx.send(embed=embed)
         else:
             await ctx.send("Не указан канал!")
     elif action == "Удалить":
         if channel:
             embed = await boostChannels.remove(ctx, channel)
             await ctx.send(embed=embed)
         else:
             await ctx.send("Не указан канал!")
     else:
         await ctx.send("Неизвестное действие.")
Ejemplo n.º 6
0
    async def resume(self,
                     ctx,
                     token: Option(str, "Game token"),
                     port: Option(int, "Port #"),
                     use_server_options: Option(
                         bool, "Use server options?") = False):
        """
        Resume an existing multiworld that was previously closed.
        """
        data = {
            'token': token,
            'port': port,
            'admin': ctx.author.id,
            'use_server_options': use_server_options,
            'meta': {
                'channel':
                None if isinstance(ctx.channel, discord.DMChannel) else
                ctx.channel.name,
                'guild':
                ctx.guild.name if ctx.guild else None,
                'name':
                f'{ctx.author.name}#{ctx.author.discriminator}'
            }
        }
        multiworld = await http.request_json_post(
            url='http://localhost:5000/game', data=data, returntype='json')

        await ctx.respond(embed=make_embed(multiworld))
Ejemplo n.º 7
0
 async def rtfm(
         self,
         ctx: discord.ApplicationContext,
         package: Option(str, "Nazwa biblioteki"),
         term: Option(str, "Szukana fraza"),
 ):
     package = package.lower()
     await ctx.defer()
     embed = discord.Embed()
     embed.title = "Znalezione w dokumentacji"
     pypi = requests.get(
         f"https://pypi.org/pypi/{package}/json",
         headers={"User-agent": "Atorin"},
     )
     if pypi.status_code == 200:
         data = pypi.json()
         embed.add_field(name="🔤 Biblioteka", value=data["info"]["name"])
         embed.add_field(name="⚙️ Wersja", value=data["info"]["version"])
     else:
         embed.add_field(name="🔤 Biblioteka", value=package)
     if not self.rtfm_cache.get(package):
         url = docs.get(package)
         if not url:
             if ("project_urls" in data["info"]
                     and "Documentation" in data["info"]["project_urls"]):
                 url = data["info"]["project_urls"]["Documentation"]
                 if "readthedocs.io" in url and not "/en/latest" in url:
                     url = os.path.join(url, "en", "latest")
             else:
                 url = f"https://{package}.readthedocs.io/en/latest/"
         r = requests.get(
             os.path.join(url, "objects.inv"),
             headers={"User-agent": "Atorin"},
         )
         if r.status_code == 200:
             self.rtfm_cache[package] = SphinxObjectFileReader(
                 r.content).parse_object_inv(url)
         elif r.status_code == 404:
             raise commands.BadArgument("Nie znaleziono dokumentacji!")
         else:
             raise commands.CommandError(
                 f"Wystąpił błąd przy pobieraniu dokumentacji! ({r.status_code})"
             )
     cache = self.rtfm_cache.get(package)
     results = finder(term,
                      list(cache.items()),
                      key=lambda x: x[0],
                      lazy=False)[:5]
     if results:
         embed.description = "\n".join(
             [f"[`{key}`]({url})" for key, url in results])
     else:
         embed.description = "Brak wyników wyszukiwania"
     await ctx.send_followup(embed=embed)
Ejemplo n.º 8
0
 async def lol(
         self,
         ctx: discord.ApplicationContext,
         region: Option(
             str,
             "Wybierz region na którym grasz",
             choices=[
                 OptionChoice("EUNE", "eun1"),
                 OptionChoice("BR", "br1"),
                 OptionChoice("EUW", "euw1"),
                 OptionChoice("JP", "jp1"),
                 OptionChoice("KR", "kr"),
                 OptionChoice("LAN", "la1"),
                 OptionChoice("LAS", "la2"),
                 OptionChoice("NA", "na1"),
                 OptionChoice("OCE", "oc1"),
                 OptionChoice("RU", "ru"),
                 OptionChoice("TR", "tr1"),
             ],
         ),
         nick: Option(str, "Nick gracza"),
 ):
     await ctx.defer()
     r = requests.get(
         f"https://{region}.api.riotgames.com/lol/summoner/v4/summoners/by-name/{nick}",
         params={"api_key": config["lol"]},
     )
     if r.status_code == 404:
         raise commands.BadArgument("Nie znaleziono podanego gracza!")
     summoner = r.json()
     r2 = requests.get(
         f"https://{region}.api.riotgames.com/lol/league/v4/entries/by-summoner/{summoner['id']}",
         params={"api_key": config["lol"]},
     )
     stats = r2.json()
     embed = discord.Embed()
     embed.title = "Statystyki w grze League of Legends"
     embed.description = f"🧑 Gracz: **{summoner['name']}**\n🏆 Poziom: **{summoner['summonerLevel']}**\n🌍 Region: **{region}**"
     embed.set_thumbnail(
         url=
         f"https://ddragon.leagueoflegends.com/cdn/10.15.1/img/profileicon/{summoner['profileIconId']}.png"
     )
     for gamemode in stats:
         value = ""
         if "tier" in gamemode:
             value += f"🎌 **Ranga:** `{gamemode['tier']} {gamemode['rank']}`\n"
         value += f"✅ **Wygrane:** `{gamemode['wins']}`\n"
         value += f"❌ **Przegrane:** `{gamemode['losses']}`\n"
         embed.add_field(
             name=f"🏟 Tryb gry: `{gamemode['queueType'].replace('_', ' ')}`",
             value=value,
         )
     await ctx.send_followup(embed=embed)
Ejemplo n.º 9
0
    async def custommystery(
        self,
        ctx: ApplicationContext,
        yamlfile: Option(discord.Attachment,
                         description="A valid mystery yaml file.",
                         required=True),
        race: Option(
            str,
            description=
            "Is this a race? (choosing no never masks settings) (default yes)",
            choices=["yes", "no"],
            required=False,
            default="yes"),
        mask_settings: Option(str,
                              description="Mask settings? (default yes)",
                              choices=["yes", "no"],
                              required=False,
                              default="yes"),
    ):
        """
        Generates an ALTTP Randomizer Mystery game on https://alttpr.com using a custom yaml
        """
        await ctx.defer()

        namespace = await generator.create_or_retrieve_namespace(
            ctx.author.id, ctx.author.name)
        content = await yamlfile.read()
        data = await generator.ALTTPRMystery.custom(
            content, f"{namespace.name}/latest")
        await data.save()

        mystery = await data.generate(
            spoilers="mystery" if mask_settings else "off",
            tournament=race == "yes")

        embed = await mystery.seed.embed(emojis=ctx.bot.emojis,
                                         name="Mystery Game")

        if mystery.custom_instructions:
            embed.insert_field_at(0,
                                  name="Custom Instructions",
                                  value=mystery.custom_instructions,
                                  inline=False)

        embed.add_field(
            name="Saved as custom weightset!",
            value=
            f"You can generate this weightset again by using the weightset name of `{namespace.name}/latest`.",
            inline=False)

        await ctx.respond(embed=embed)
Ejemplo n.º 10
0
 async def fortnite(
         self,
         ctx: discord.ApplicationContext,
         platform: Option(
             str,
             "Wybierz platformę na której grasz",
             choices=[
                 OptionChoice("Epic Games", "epic"),
                 OptionChoice("Playstation Network", "psn"),
                 OptionChoice("Xbox Live", "xbl"),
             ],
         ),
         nick: Option(str, "Nick gracza"),
 ):
     await ctx.defer()
     r = requests.get(
         url="https://fortnite-api.com/v2/stats/br/v2",
         params={
             "name": nick,
             "accountType": platform
         },
         headers={"Authorization": config["fortnite"]},
     )
     if r.status_code == 200:
         json = r.json()
         data = json["data"]["stats"]["all"]["overall"]
         embed = discord.Embed()
         embed.title = "Statystyki w grze Fortnite"
         embed.description = "🧑 Gracz: **{}**".format(nick)
         embed.add_field(name="⭐️ Punkty",
                         value=humanize.intcomma(data["score"]))
         embed.add_field(name="🏆 Wygrane",
                         value=humanize.intcomma(data["wins"]))
         embed.add_field(name="⚔ Zabójstwa",
                         value=humanize.intcomma(data["kills"]))
         embed.add_field(name="☠ Śmierci",
                         value=humanize.intcomma(data["deaths"]))
         embed.add_field(name="🕹 Rozegranych meczy",
                         value=humanize.intcomma(data["matches"]))
         await ctx.send_followup(embed=embed)
     elif r.status_code == 403:
         raise commands.BadArgument(
             f"Statystyki gracza __{nick}__ są **prywatne**!")
     elif r.status_code == 404:
         raise commands.BadArgument(
             "Podany gracz nie istnieje lub nigdy nie grał w Fortnite!")
     else:
         raise commands.CommandError(await r.text())
Ejemplo n.º 11
0
    async def memory(self, ctx, channel: Option(discord.TextChannel,
                                                "Выбреите канал",
                                                required=True),
                     member: Option(discord.Member,
                                    "Выберите пользователя",
                                    required=False,
                                    default=None)):
        messages = session.query(Message, Member)\
            .filter(Message.ChannelId == channel.id)\
            .filter(Message.MemberId == Member.Id)

        if member:
            messages = messages.filter(Member.MemberId == member.id)

        pages = []

        iter = 0
        for message, dbmember in messages.order_by(desc(Message.Created)):
            member = ctx.guild.get_member(dbmember.MemberId)
            iter += 1
            embed = discord.Embed(title=member.name)
            embed.add_field(name="Сообщение:", value=message.Text, inline=True)
            embed.add_field(name="Отправлено:",
                            value=str(message.Created),
                            inline=True)

            if iter == 1:
                page = Page(embeds=[embed])
            else:
                page.embeds.append(embed)
            if iter == 10:
                pages.append(page)
                iter = 0

        try:
            if pages.count(page) == 0:
                pages.append(page)
        except UnboundLocalError:
            return

        if len(pages) == 0:
            return

        paginator = Paginator(pages=pages,
                              loop_pages=True,
                              disable_on_timeout=True,
                              timeout=360)
        await paginator.respond(ctx.interaction)
Ejemplo n.º 12
0
 async def tvp(self, ctx: discord.ApplicationContext,
               text: Option(str, "Tre艣膰 paska")):
     if len(text) > 48:
         raise commands.BadArgument(
             f"Tre艣膰 paska jest zbyt d艂uga! Max. 48 znak贸w, podano {len(text)}."
         )
     await ctx.defer()
     async with aiohttp.ClientSession() as session:
         async with session.post(
                 "https://pasek-tvpis.pl/index.php",
                 data={
                     "fimg": randint(0, 1),
                     "msg": text
                 },
         ) as r:
             if r.status == 200:
                 image = await r.content.read()
                 embed = discord.Embed()
                 embed.title = "Tw贸j pasek z Wiadomo艣ci"
                 embed.set_image(url="attachment://tvp.png")
                 await ctx.send_followup(
                     embed=embed,
                     file=discord.File(BytesIO(image), filename="tvp.png"),
                 )
             else:
                 raise commands.CommandError(await r.text())
Ejemplo n.º 13
0
 async def csgo(self, ctx: discord.ApplicationContext,
                url: Option(str, "Link do profilu Steam")):
     await ctx.defer()
     if "steamcommunity.com/id/" in url or "steamcommunity.com/profiles/" in url:
         try:
             steam_id, nick = await steam_resolve_url(url, config["steam"])
         except TypeError:
             raise commands.BadArgument("Nie odnaleziono podanego gracza!")
     else:
         raise commands.BadArgument("Podany link jest nieprawidłowy!")
     stats = await steam_get_stats(730, config["steam"], steam_id)
     if not stats:
         raise commands.BadArgument("Podany profil musi być publiczny!")
     embed = discord.Embed()
     embed.title = "Statystyki w grze CS:GO"
     embed.description = "🧑 Gracz: **{}**".format(nick)
     for i in stats:
         if i["name"] == "total_kills":
             embed.add_field(name="🔫 Liczba zabójstw", value=i["value"])
         elif i["name"] == "total_deaths":
             embed.add_field(name="☠ Liczba śmierci", value=i["value"])
         elif i["name"] == "total_matches_played":
             embed.add_field(name="⚔ Rozegranych meczy", value=i["value"])
         elif i["name"] == "total_matches_won":
             embed.add_field(name="🏆 Wygranych meczy",
                             value=i["value"],
                             inline=False)
     await ctx.send_followup(embed=embed)
Ejemplo n.º 14
0
 async def mcskin(self, ctx: discord.ApplicationContext,
                  nick: Option(str, "Nick w Minecraft")):
     await ctx.defer()
     mojang = requests.get(
         f"https://api.mojang.com/users/profiles/minecraft/{nick}")
     if mojang.status_code == 200:
         data = mojang.json()
         skin = requests.get(
             f"https://crafatar.com/renders/body/{data['id']}")
         if skin.status_code == 200:
             embed = discord.Embed()
             embed.title = f"Skin {nick} w Minecraft"
             embed.set_image(url="attachment://skin.png")
             await ctx.send_followup(
                 embed=embed,
                 files=[
                     discord.File(BytesIO(skin.content),
                                  filename="skin.png")
                 ],
             )
         else:
             raise commands.CommandError(skin.text)
     elif mojang.status_code == 204:
         raise commands.BadArgument("Nie znaleziono podanego gracza!")
     else:
         raise commands.CommandError(mojang.text)
Ejemplo n.º 15
0
    async def recent(self, ctx, filter: Option(
        str,
        "The first event matching this will be sent in the channel.",
        required=False,
        default=None)):
        """Returns the most recent event gathered, optionally matching `filter`."""

        if filter and not await validate_filter(ctx, filter, filter_context):
            return  # `validate_filter` will respond for us.

        await ctx.defer(ephemeral=False)

        matching_filter_str = f" matching `{filter}`" if filter else ""

        filter_query, filter_values = filter_to_sql(filter)
        database = Database(SCRAPER_DB_NAME)
        try:
            event = await database.retrieve_event(
                where=filter_query,
                where_values=filter_values,
                order_by="time DESC",
                extensive=True if filter else False)
        except TimeoutError:
            await ctx.followup.send(
                f"✗ Took too long to find an event{matching_filter_str}.")
            return

        if not event:
            await ctx.followup.send(
                f"✗ No event{matching_filter_str} could be found.")
            return

        await ctx.followup.send(
            f"✓ Most recent event{matching_filter_str}:\r\n{format_link(event)}",
            embed=await format_embed(event))
Ejemplo n.º 16
0
 async def smdash(self, ctx: ApplicationContext,
                  mode: Option(str,
                               description="The mode you want to generate.",
                               choices=['mm', 'full', 'sgl20', 'vanilla'],
                               required=True),
                  race: Option(str,
                               description="Is this a race? (default no)",
                               choices=["yes", "no"],
                               required=False,
                               default="no")):
     """
     Generates an Super Metroid Varia Randomizer game on https://varia.run
     """
     await ctx.defer()
     url = await smdash.create_smdash(mode=mode, encrypt=race == "yes")
     await ctx.respond(url)
Ejemplo n.º 17
0
    async def blast(self, ctx: ApplicationContext,
                    role_name: Option(str,
                                      "Choose a role to blast",
                                      required=True,
                                      autocomplete=role_name_autocomplete)):
        """
        Used by Synack to blast requests to link your RaceTime.gg account to this bot.
        """
        role: discord.Role = discord.utils.get(ctx.guild._roles.values(),
                                               name=role_name)
        await ctx.defer()
        msg = []
        for member in role.members:
            result = await models.SRLNick.get_or_none(discord_user_id=member.id
                                                      )
            if result is None or result.rtgg_id is None:
                try:
                    await member.send((
                        f"Greetings {member.name}!  We have detected that you do not have a RaceTime.gg ID linked to SahasrahBot.\n"
                        f"Please visit <{APP_URL}/racetime/verification/initiate> to verify your RaceTime.gg ID!  We will need this info.\n\n"
                        "If you have any questions, please contact Synack.  Thank you!"
                    ))
                    msg.append(
                        f"Send DM to {member.name}#{member.discriminator}")
                except (discord.Forbidden, discord.HTTPException) as e:
                    msg.append(
                        f"Failed to send DM to {member.name}#{member.discriminator}.\n\n{str(e)}"
                    )

        if msg:
            await ctx.respond("\n".join(msg))
        else:
            await ctx.respond("No messages sent.")
Ejemplo n.º 18
0
 async def chart(self, ctx, *, chart: Option(
     str,
     "Choose chart.",
     choices=["Melon", "Billboard", "Billboard Japan"])):
     """ I will tell you from the 1st to the 10th place on the chart site """
     if not chart == None:
         chart = chart.upper()
     if chart == "MELON":
         title, artist = await get_melon()
         embed = discord.Embed(title=get_lan(ctx.author.id,
                                             "chart_melon_chart"),
                               color=color_code)
     elif chart == "BILLBOARD":
         title, artist = await get_billboard()
         embed = discord.Embed(title=get_lan(ctx.author.id,
                                             "chart_billboard_chart"),
                               color=color_code)
     elif chart == "BILLBOARD JAPAN":
         title, artist = await get_billboardjp()
         embed = discord.Embed(title=get_lan(ctx.author.id,
                                             "chart_billboardjp_chart"),
                               color=color_code)
     for i in range(0, 10):
         embed.add_field(name=str(i + 1) + ".",
                         value=f"{artist[i]} - {title[i]}",
                         inline=False)
     embed.set_footer(text=BOT_NAME_TAG_VER)
     await ctx.respond(embed=embed)
Ejemplo n.º 19
0
 async def changemymind(self, ctx: discord.ApplicationContext,
                        text: Option(str, "Tre艣膰 mema")):
     if len(text) > 140:
         raise commands.BadArgument(
             f"Tre艣膰 mema jest zbyt d艂uga! Max. 140 znak贸w, podano {len(text)}"
         )
     await ctx.defer()
     template = Image.open("assets/changemymind/changemymind.jpg")
     txt = Image.new("RGBA", (700, 350), (0, 0, 0, 0))
     d1 = ImageDraw.Draw(txt)
     font = ImageFont.truetype("assets/changemymind/impact.ttf", 24)
     offset = 0
     for line in textwrap.wrap(text.strip(), width=30):
         d1.text((50, offset), line, font=font, fill="#000000")
         offset += font.getsize(line)[1]
     w = txt.rotate(22.5)
     template.paste(w, (310, 200), w)
     img = BytesIO()
     template.save(img, "PNG")
     img.seek(0)
     embed = discord.Embed()
     embed.title = "Change my mind"
     embed.set_image(url="attachment://changemymind.png")
     await ctx.send_followup(embed=embed,
                             file=discord.File(img,
                                               filename="changemymind.png"))
Ejemplo n.º 20
0
    async def subscribe(self, ctx, filter: Option(
        str,
        "Any event matching this will be sent in the channel.",
        required=True)):
        """Subscribes this channel to events matching `filter`."""
        if ctx.author.bot:
            return

        if not ctx.channel.guild:
            await ctx.respond("✗ This command can only be used in a server.",
                              ephemeral=True)
            return

        if not ctx.channel.permissions_for(ctx.author).manage_channels:
            await ctx.respond(
                "✗ You need the `Manage Channels` permission here to use this command.",
                ephemeral=True)
            return

        if not await validate_filter(ctx, filter, filter_context):
            return  # `validate_filter` will respond for us.

        subscribe(ctx.channel, filter)

        embed = Embed()
        embed.colour = Colour.from_rgb(255, 170, 50)
        embed.add_field(name="🔔\u2000Subscribed to",
                        value=f"""
                {escape_markdown(filter)}
                `{expand(filter)}`
                """)

        await ctx.respond("✓", embed=embed)
Ejemplo n.º 21
0
 async def request_role(self, ctx: ApplicationContext, role_name: Option(
     str,
     "Name of a role to toggle (optional)",
     autocomplete=roles_for_autocomplete,
     required=False)):
     roles = get_roles(ctx)
     if role_name and role_name in roles.keys():
         roleset_name = roles[role_name]
         role = find(lambda r: r.name.lower() == role_name.lower(),
                     ctx.guild.roles)
         changes = get_role_changes(ctx.user, role, roleset_name)
         confirm_view = Confirm(do_role_changes(changes))
         await ctx.respond(f"Changes:\n{role_changes_to_string(changes)}",
                           view=confirm_view,
                           ephemeral=True)
     elif 1 < len(roles) < 25:
         role_options = [
             SelectOption(label=role_name, value=role_name)
             for role_name in get_roles(ctx).keys()
         ]
         view = RolesView(role_options)
         view.interaction = await ctx.respond('Have a choice!',
                                              view=view,
                                              ephemeral=True)
     else:
         await ctx.respond(
             'The following roles are self-assignable on this server, use this command with a '
             'role_name:\n ' + ', '.join(role
                                         for role in sorted(roles.keys())),
             ephemeral=True)
Ejemplo n.º 22
0
    async def play(
            self,
            ctx: discord.ApplicationContext,
            query: Option(str, "Tytuł lub link do Youtube/Twitch/MP3"),
    ):
        """Searches and plays a song from a given query."""
        await ctx.defer()
        player: lavalink.DefaultPlayer = self.bot.lavalink.player_manager.get(
            ctx.guild.id)
        query = query.strip("<>")

        if not url_rx.match(query):
            query = f"ytsearch:{query}"
        else:
            if "open.spotify.com/track/" in query:
                song = get_song_from_spotify(
                    query.split("open.spotify.com/track/")[1].split("?")[0])
                query = f"ytsearch:{song}"
            elif "spotify:track:" in query:
                song = get_song_from_spotify(query.split("spotify:track:")[1])
                query = f"ytsearch:{song}"

        results = await player.node.get_tracks(query)

        if not results or not results["tracks"]:
            return await ctx.send_followup(
                "❌ Nie znaleziono utworu o podanej nazwie!")

        embed = discord.Embed()

        # Valid loadTypes are:
        #   TRACK_LOADED    - single video/direct URL)
        #   PLAYLIST_LOADED - direct URL to playlist)
        #   SEARCH_RESULT   - query prefixed with either ytsearch: or scsearch:.
        #   NO_MATCHES      - query yielded no results
        #   LOAD_FAILED     - most likely, the video encountered an exception during loading.
        if results["loadType"] == "PLAYLIST_LOADED":
            tracks = results["tracks"]

            for track in tracks:
                player.add(requester=ctx.author.id, track=track)

            embed.title = "Dodano playlistę do kolejki!"
            embed.description = (
                f'{results["playlistInfo"]["name"]} - {len(tracks)} utworów')
        else:
            track = results["tracks"][0]
            embed.title = "Dodano do kolejki"
            embed.description = f'[{track["info"]["title"]}]({track["info"]["uri"]})'
            embed.set_thumbnail(
                url=
                f"https://img.youtube.com/vi/{track['info']['identifier']}/maxresdefault.jpg"
            )
            track = lavalink.models.AudioTrack(track, ctx.author.id)
            player.add(requester=ctx.author.id, track=track)

        await ctx.send_followup(embed=embed)

        if not player.is_playing:
            await player.play()
Ejemplo n.º 23
0
    async def report(self, ctx: ApplicationContext,
                     role_name: Option(str,
                                       "Choose a role to report",
                                       required=True,
                                       autocomplete=role_name_autocomplete)):
        """
        Used by Synack to report users who have not linked their racetime account to SahasrahBot.
        """
        if not await self.bot.is_owner(ctx.author):
            await ctx.reply("Only the bot owner can use this command.")
            return

        await ctx.defer()
        role: discord.Role = discord.utils.get(ctx.guild._roles.values(),
                                               name=role_name)
        msg = []
        for member in role.members:
            result = await models.SRLNick.get_or_none(discord_user_id=member.id
                                                      )
            if result is None or result.rtgg_id is None:
                msg.append(f"{member.name}#{member.discriminator}")

        if msg:
            await ctx.respond("\n".join(msg))

        else:
            await ctx.respond(
                "Everyone in this role is registered with the bot.")
Ejemplo n.º 24
0
async def reject(ctx, reason: Option(str, "Reason for rejection")):
    """Reject a suggestion"""
    if "Staff" not in str(ctx.author.roles):
        await ctx.respond(":warning: Insufficient permission.", ephemeral=True)
        return

    print(ctx.channel.type)

    # Make sure it's a thread
    if ctx.channel.type != discord.ChannelType.public_thread:
        await ctx.respond(
            ":warning: This command can only be used in threads.",
            ephemeral=True)
        return

    try:
        await ctx.channel.owner.send(
            f"{ctx.author.mention} has closed your suggestion thread with the title *{ctx.channel.name}*.\n{reason}"
        )
        await ctx.respond(":white_check_mark:", ephemeral=True)
    except:
        await ctx.respond("Couldn't message the thread owner.", ephemeral=True)
    time.sleep(3)

    await ctx.channel.delete()
Ejemplo n.º 25
0
 async def user(
     self,
     ctx: discord.ApplicationContext,
     member: Option(
         discord.Member,
         "Osoba której informacje chcesz wyświetlić",
         required=False,
     ),
 ):
     if member is None:
         member = ctx.author
     embed = discord.Embed()
     embed.title = f"Informacje o {member}"
     embed.add_field(name="🆔 ID", value=f"`{member.id}`", inline=False)
     if member.nick:
         embed.add_field(name="🎭 Pseudonim", value=member.nick)
     embed.add_field(
         name="🏅 Role",
         value=", ".join(role.mention for role in member.roles),
         inline=False,
     )
     embed.add_field(
         name="👶 Data utworzenia konta",
         value=f"<t:{int(datetime.timestamp(member.created_at))}>",
     )
     embed.add_field(
         name="🤝 Data dołączenia",
         value=f"<t:{int(datetime.timestamp(member.joined_at))}>",
     )
     embed.set_thumbnail(url=str(member.display_avatar))
     await ctx.respond(embed=embed)
Ejemplo n.º 26
0
async def forms(ctx, type: Option(
    str,
    "Write, click or select an option with the arrow keys, then press TAB",
    choices=["Staff Application", "Ban Appeal"]
), action: Option(
    str,
    "Write, click or select an option with the arrow keys, then press TAB",
    choices=["Accept", "Reject"]
), user: Option(
    str,
    "@Tag the user, write their ID or full name (with #discriminator), then press TAB"
)):
    """Send automated answers"""
    if "Staff" not in str(ctx.author.roles):
        await ctx.respond(":warning: Insufficient permission.", ephemeral=True)
        return

    try:
        member = ctx.guild.get_member(int(user))
    except:
        member = ctx.guild.get_member_named(user)

    if member is not None:
        try:
            if type == "Staff Application" and action == "Accept":
                await member.send(
                    f"Hey! Your application has been accepted. You will hear from us shortly.\n\nIn the meantime, you can take a look at this: <https://1literzinalco.github.io/vampirism/staff.html>\n\nWe're using \"Trello\" to organize everything important, such as bugs and punishments. Check out this brief overview: <https://youtu.be/AphRCn5__38> and then join our board: ||<{config.TRELLO}>|| (keep this link secret!)"
                )
            elif type == "Staff Application" and action == "Reject":
                await member.send(
                    f"Hey! Your application has been rejected. You can reapply in two weeks at the earliest!"
                )
            elif type == "Ban Appeal" and action == "Accept":
                await member.send(
                    "Your ban appeal has been accepted. You will be unbanned within 24 hours."
                )
            elif type == "Ban Appeal" and action == "Reject":
                await member.send(
                    "Your ban appeal has been rejected. You can appeal again in two weeks at the earliest."
                )
            await ctx.respond(
                f"{member.name}'s {type.lower()} has been {action.lower()}ed!")
        except Exception as e:
            await ctx.respond(f":warning: {e}")
    else:
        await ctx.respond(
            f":warning: I couldn't find a user by searching for `{user}`.")
Ejemplo n.º 27
0
    async def custompreset(
        self,
        ctx: ApplicationContext,
        yamlfile: Option(discord.Attachment,
                         description="The preset you want generate.",
                         required=True),
        race: Option(str,
                     description="Is this a race? (default no)",
                     choices=["yes", "no"],
                     required=False,
                     default="no"),
        hints: Option(str,
                      description="Enable hints? (default no)",
                      choices=["yes", "no"],
                      required=False,
                      default="no"),
        allow_quickswap: Option(str,
                                description="Allow quickswap? (default yes)",
                                choices=["yes", "no"],
                                required=False,
                                default="yes"),
    ):
        """
        Generates an ALTTP Randomizer game on https://alttpr.com using a custom yaml provided by the user
        """
        await ctx.defer()

        namespace = await generator.create_or_retrieve_namespace(
            ctx.author.id, ctx.author.name)

        content = await yamlfile.read()
        data = await generator.ALTTPRPreset.custom(content,
                                                   f"{namespace.name}/latest")
        await data.save()
        seed = await data.generate(spoilers="off" if race == "yes" else "on",
                                   tournament=race == "yes",
                                   allow_quickswap=allow_quickswap == "yes",
                                   hints=hints == "yes")

        embed: discord.Embed = await seed.embed(emojis=self.bot.emojis)
        embed.add_field(
            name="Saved as preset!",
            value=
            f"You can generate this preset again by using the preset name of `{namespace.name}/latest`",
            inline=False)

        await ctx.respond(embed=embed)
Ejemplo n.º 28
0
    async def sgdaily_cmd(self, ctx: discord.ApplicationContext,
                          number_of_days: Option(
                              int,
                              description="Number of days to lookup.",
                              default=1)):
        """
        Retrieves the next SG daily race.
        """
        sg_schedule = await speedgaming.get_upcoming_episodes_by_event(
            "alttprdaily", hours_past=0, hours_future=192)
        if len(sg_schedule) == 0:
            await ctx.respond(
                "There are no currently SpeedGaming ALTTPR Daily Races scheduled within the next 8 days."
            )
            return

        if number_of_days == 1:
            embed = discord.Embed(
                title=sg_schedule[0]['event']['name'],
                description=
                f"**Mode:** {'*TBD*' if sg_schedule[0]['match1']['title'] == '' else sg_schedule[0]['match1']['title']}\n[Full Schedule](http://speedgaming.org/alttprdaily)"
            )
        else:
            embed = discord.Embed(
                title="ALTTP Randomizer SG Daily Schedule",
                description=
                "[Full Schedule](http://speedgaming.org/alttprdaily)")

        for episode in sg_schedule[0:number_of_days]:
            when = dateutil.parser.parse(episode['when'])
            if number_of_days == 1:
                embed.add_field(
                    name='Time',
                    value=
                    f"{discord.utils.format_dt(when, 'f')} ({discord.utils.format_dt(when, 'R')})",
                    inline=False)
                broadcast_channels = [
                    a['slug'] for a in episode['channels']
                    if not " " in a['name']
                ]
                if broadcast_channels:
                    embed.add_field(name="Twitch Channels",
                                    value=', '.join([
                                        f"[{a}](https://twitch.tv/{a})"
                                        for a in broadcast_channels
                                    ]),
                                    inline=False)
            else:
                embed.add_field(name='TBD' if episode['match1']['title'] == ''
                                else episode['match1']['title'],
                                value=discord.utils.format_dt(when, 'f'),
                                inline=False)
        embed.set_footer()

        embed.set_thumbnail(
            url=
            'https://pbs.twimg.com/profile_images/1185422684190105600/3jiXIf5Y_400x400.jpg'
        )
        await ctx.respond(embed=embed)
Ejemplo n.º 29
0
 async def weather(
         self,
         ctx: discord.ApplicationContext,
         city: Option(str, "Miejscowość lub kod pocztowy"),
 ):
     token = config["weather"]
     await ctx.defer()
     async with aiohttp.ClientSession() as session:
         async with session.get(
                 "http://api.openweathermap.org/data/2.5/weather?appid={0}&units=metric&lang=pl&q={1}"
                 .format(token, quote(city))) as r:
             embed = discord.Embed()
             if r.status == 200:
                 data = await r.json()
                 embed.title = "Pogoda w " + data["name"]
                 emoji = get_weather_emoji(data["weather"][0]["id"])
                 embed.description = f"{emoji} __**{data['weather'][0]['description'].capitalize()}**__"
                 embed.add_field(
                     name="🌡️ Temperatura",
                     value=f"{data['main']['temp']}°C",
                 )
                 embed.add_field(
                     name="👐 Odczuwalna",
                     value=f"{data['main']['feels_like']}°C",
                 )
                 embed.add_field(
                     name="🥶 Najniższa",
                     value=f"{data['main']['temp_min']}°C",
                 )
                 embed.add_field(
                     name="🥵 Najwyższa",
                     value=f"{data['main']['temp_max']}°C",
                 )
                 embed.add_field(
                     name="🎈 Ciśnienie",
                     value=f"{data['main']['pressure']}hPa",
                 )
                 embed.add_field(
                     name="💧 Wilgotność",
                     value=f"{data['main']['humidity']}%",
                 )
                 embed.add_field(
                     name="💨 Wiatr",
                     value=f"{int(data['wind']['speed'] * 3.6)}km/h",
                 )
                 embed.add_field(
                     name="🌅 Wschód słońca",
                     value=f"<t:{data['sys']['sunrise']}:t>",
                 )
                 embed.add_field(
                     name="🌇 Zachód słońca",
                     value=f"<t:{data['sys']['sunset']}:t>",
                 )
                 await ctx.send_followup(embed=embed)
             elif r.status == 404:
                 raise commands.BadArgument(
                     "Nie odnaleziono podanej miejscowości.")
             else:
                 raise commands.CommandError(await r.text())
Ejemplo n.º 30
0
 async def together(self, ctx: discord.ApplicationContext,
                    option: Option(str,
                                   "Pick a sound!",
                                   autocomplete=get_options)):
     """Together: youtube, poker, chess, betrayal, fishing"""
     link = await self.togetherControl.create_link(
         ctx.author.voice.channel.id, str(option))
     await ctx.send(f"Click the blue link!\n{link}")