Skip to content
This repository has been archived by the owner on Sep 9, 2024. It is now read-only.

Commit

Permalink
Merge pull request #59 from is-a-dev/developments
Browse files Browse the repository at this point in the history
Slash cmd migration
  • Loading branch information
MaskDuck authored May 29, 2024
2 parents 3d1456b + 2a2bba6 commit 4bd00b2
Show file tree
Hide file tree
Showing 12 changed files with 333 additions and 29 deletions.
12 changes: 11 additions & 1 deletion _orangcbot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@

import nextcord
import psycopg2
from nextcord import Intents
from nextcord import ApplicationError, Intents
from nextcord.ext import application_checks as ac
from nextcord.ext import commands, help_commands

prefix = "oct/" if os.getenv("TEST") else "oc/"
Expand Down Expand Up @@ -42,6 +43,15 @@ async def on_command_error(
await context.send("Fool")
await super().on_command_error(context, error)

async def on_application_command_error(
self, interaction: nextcord.Interaction, exception: ApplicationError
) -> None:
if isinstance(exception, ac.ApplicationMissingRole):
await interaction.send("Imagine not being a staff")
else:
await interaction.send("Fool")
await super().on_application_command_error(interaction, exception)


bot = OrangcBot(
intents=Intents.all(),
Expand Down
24 changes: 22 additions & 2 deletions _orangcbot/extensions/archwiki.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Final, Generic, TypeVar
from typing import TYPE_CHECKING, Any, Final, Generic, Self, TypeVar

import aiohttp
import nextcord
import typing_extensions
from nextcord import SlashOption, slash_command
from nextcord.ext import commands, menus

T = TypeVar("T")
Expand Down Expand Up @@ -56,6 +56,26 @@ async def archwiki(self, ctx: commands.Context, *, query: str) -> None:
l: ArchWikiButtonMenu = ArchWikiButtonMenu(k)
await l.start(ctx=ctx)

@nextcord.slash_command(name="archwiki")
async def archwiki_(
self: Self,
interaction: nextcord.Interaction,
query: str = SlashOption(
description="The documentation query to search for", required=True
),
):
"""Query ArchWiki for a documentation entry."""
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://wiki.archlinux.org/api.php?action=opensearch&search={query}&limit=20&format=json"
) as resp:
k = await resp.json()
if len(k[1]) == 0:
await interaction.send("No results foundd, aborting.")
return
l: ArchWikiButtonMenu = ArchWikiButtonMenu(k)
await l.start(interaction=interaction)


def setup(bot: commands.Bot) -> None:
bot.add_cog(ArchWiki(bot))
13 changes: 12 additions & 1 deletion _orangcbot/extensions/converters.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from __future__ import annotations

from typing import Tuple
from typing import Final, Tuple

from nextcord import Interaction, OptionConverter
from nextcord.ext import commands

__all__: Final[Tuple[str]] = ("SubdomainNameConverter", "SlashSubdomainNameConverter")


class SubdomainNameConverter(commands.Converter):
async def convert(self, ctx: commands.Context, argument: str) -> str:
Expand All @@ -16,3 +19,11 @@ async def convert(self, ctx: commands.Context, argument: str) -> str:
class RGBColorTupleConverter(commands.Converter):
async def convert(self, ctx: commands.Context, argument: str) -> Tuple[str]:
return argument.split("-") # type: ignore[reportReturnType]


class SlashSubdomainNameConverter(OptionConverter):
async def convert(self, interaction: Interaction, value: str) -> str:
value = value.lower()
if value.endswith(".is-a.dev"):
return value[:-9]
return value
30 changes: 28 additions & 2 deletions _orangcbot/extensions/dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def update_msg(self, msg: nextcord.Message):

class DNSView(nextcord.ui.View):
if TYPE_CHECKING:
_message: nextcord.Message
_message: nextcord.Message | nextcord.PartialInteractionMessage

def __init__(self, url: str, author_id: int):
super().__init__(timeout=600)
Expand All @@ -88,7 +88,9 @@ async def interaction_check(self, interaction: nextcord.Interaction) -> bool:
await interaction.send("Fool", ephemeral=True)
return False

def update_msg(self, msg: nextcord.Message) -> None:
def update_msg(
self, msg: nextcord.Message | nextcord.PartialInteractionMessage
) -> None:
self._message = msg
self.dropdown.update_msg(msg)

Expand Down Expand Up @@ -117,6 +119,30 @@ async def dig(self, ctx: commands.Context, url: str):
msg = await ctx.send(embed=construct_embed(url, answer, "CNAME"), view=k)
k.update_msg(msg)

@nextcord.slash_command(name="dig")
async def dig_(
self,
interaction: nextcord.Interaction,
url: str = nextcord.SlashOption(
description="The URL to dig for DNS records. Be sure to remove http or https://",
required=True,
),
) -> None:
"""Dig an URL for its DNS records. Default to CNAME, if you want other things then please choose in the dropdown provided later."""
try:
answers = _dnsresolver.resolve(url, "CNAME")
answer = "\n".join([str(ans) for ans in answers])
except _dnsresolver.NoAnswer:
answer = "NOT FOUND"
except _dnsresolver.NXDOMAIN:
await interaction.send("Domain requested does not exist. Aborting.")
return
k = DNSView(url, interaction.user.id)
msg = await interaction.send(
embed=construct_embed(url, answer, "CNAME"), view=k
)
k.update_msg(msg)


def setup(bot: commands.Bot) -> None:
bot.add_cog(DNS(bot))
18 changes: 15 additions & 3 deletions _orangcbot/extensions/faq.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ def __init__(self):
super().__init__(placeholder="Select your question.", options=options)
self._message: nextcord.Message = None

def update_msg(self, message: nextcord.Message):
self._message: nextcord.Message = message
def update_msg(self, message: nextcord.Message | nextcord.InteractionMessage):
self._message: nextcord.Message | nextcord.InteractionMessage = message

async def callback(self, interaction: nextcord.Interaction):
await interaction.response.defer()
Expand Down Expand Up @@ -130,13 +130,25 @@ async def faq(self, ctx: commands.Context):
"""Show FAQ."""
k = FAQView()
embed = nextcord.Embed(
title="Welcome to FAQ",
title="Welcome to FAQ.",
description="Click the dropdown below to toggle the questions.",
color=nextcord.Color.blurple(),
)
m = await ctx.send(embed=embed, view=k)
k.update_msg(m)

@nextcord.slash_command(name="faq")
async def faq_slash(self, interaction: nextcord.Interaction) -> None:
"""Show FAQ."""
k = FAQView()
embed = nextcord.Embed(
title="Welcome to FAQ.",
description="Click the dropdown below to toggle the questions.",
color=nextcord.Color.blurple(),
)
m = await interaction.send(embed=embed, view=k)
k.update_msg(m) # type: ignore[reportArgumentType]


def setup(bot):
bot.add_cog(FAQ(bot))
98 changes: 82 additions & 16 deletions _orangcbot/extensions/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import aiohttp
import dotenv
import nextcord
from nextcord import Interaction, SlashOption
from nextcord.ext import commands
from psl_dns import PSL

Expand Down Expand Up @@ -239,17 +240,13 @@ async def moral(
if not member:
member = ctx.author # type: ignore[reportAssignmentType]
if member.id == 716134528409665586: # type: ignore[reportOptionalMemberAccess]

state = "Paragon of Virtue"

elif member.id == 853158265466257448: # type: ignore[reportOptionalMemberAccess]

state = "Beneath contempt"
elif member.id == 961063229168164864: # type: ignore[reportOptionalMemberAccess]

state = "Degenerate"
else:

state = choice(_morals)

await ctx.send(f"**{member.display_name}**'s moral status is **{state}**") # type: ignore[reportOptionalMemberAccess]
Expand All @@ -260,17 +257,13 @@ async def see_moral(
) -> None:
# state = ""
if member.id == 716134528409665586:

state = "Paragon of Virtue"
elif member.id == 853158265466257448:

state = "Beneath contempt"
elif member.id == 961063229168164864:

state = "Degenerate"

else:

state = choice(_morals)
await interaction.response.send_message(
f"**{member.display_name}**'s moral status is **{state}**"
Expand All @@ -297,14 +290,6 @@ async def fool(

await ctx.send(f"**{member.display_name}** is {level}% a fool.") # type: ignore[reportOptionalMemberAccess]

@commands.command()
async def imbored(self, ctx: commands.Context):
"""Fetch an activity to do from BoredAPI."""
response = await request("GET", "http://www.boredapi.com/api/activity/")
await ctx.send(
f"You should probably **{response['activity']}** to occupy yourself."
)

@commands.command()
async def httpcat(self, ctx: commands.Context, code: int = 406):
"""Fetch an HTTP Cat image from the http.cat API."""
Expand All @@ -323,5 +308,86 @@ async def shouldi(self, ctx: commands.Context, question: Optional[str] = None):
await ctx.send(f"answer: [{r['answer']}]({r['image']})")


class FunSlash(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self._bot = bot

@nextcord.slash_command()
async def dog(self, interaction: Interaction):
k = await request("GET", "https://dog.ceo/api/breeds/image/random")
await interaction.send(k["message"])

@nextcord.slash_command()
async def httpcat(
self,
interaction: nextcord.Interaction,
code: int = SlashOption(
description="The HTTP code to fetch for", required=True
),
) -> None:
await interaction.send(f"https://http.cat/{code}")

@nextcord.slash_command()
async def shouldi(
self,
interaction: nextcord.Interaction,
question: str = SlashOption(
description="What are you asking me for?", required=False
),
) -> None:
r = await request("GET", "https://yesno.wtf/api")
await interaction.send(f"answer: [{r['answer']}]({r['image']})")

@nextcord.slash_command()
async def ubdict(
self,
interaction: nextcord.Interaction,
word: str = SlashOption(description="The word to search for", required=True),
) -> None:
params = {"term": word}
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.urbandictionary.com/v0/define", params=params
) as response:
data = await response.json()
if not data["list"]:
await interaction.send("No results found.")
return
embed = nextcord.Embed(
title=data["list"][0]["word"],
description=data["list"][0]["definition"],
url=data["list"][0]["permalink"],
color=nextcord.Color.green(),
)
embed.set_footer(
text=f"👍 {data['list'][0]['thumbs_up']} | 👎 {data['list'][0]['thumbs_down']} | Powered by: Urban Dictionary"
)
await interaction.send(embed=embed)

@nextcord.slash_command()
async def moral(
self,
interaction: Interaction,
member: nextcord.User = SlashOption(
description="The user you want to see the moral.", required=False
),
) -> None:
if not member:
member = interaction.user
if member.id == 716134528409665586:
state = "Paragon of Virtue"
elif member.id == 853158265466257448:
state = "Beneath contempt"
elif member.id == 961063229168164864:
state = "Degenerate"

else:
state = choice(_morals)
await interaction.response.send_message(
f"**{member.display_name}**'s moral status is **{state}**"
)


def setup(bot):
bot.add_cog(Fun(bot))
bot.add_cog(FunSlash(bot))
21 changes: 21 additions & 0 deletions _orangcbot/extensions/nixwiki.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,27 @@ async def nixwiki(self, ctx: commands.Context, *, query: str) -> None:
l: NixWikiButtonMenu = NixWikiButtonMenu(k)
await l.start(ctx=ctx)

@nextcord.slash_command(name="nixwiki")
async def nixwiki_(
self,
interaction: nextcord.Interaction,
query: str = nextcord.SlashOption(
description="The query of the documentation page to search for.",
required=True,
),
) -> None:
"""Query the NixWiki Documentation for a specified query."""
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://nixos.wiki/api.php?action=opensearch&search={query}&limit=20&format=json"
) as resp:
k = await resp.json()
if len(k[1]) == 0:
await interaction.send("No results found")
return
l: NixWikiButtonMenu = NixWikiButtonMenu(k)
await l.start(interaction=interaction)


def setup(bot: commands.Bot) -> None:
bot.add_cog(NixWiki(bot))
Loading

0 comments on commit 4bd00b2

Please sign in to comment.