Skip to content

Commit

Permalink
Merge pull request #8 from JDsProjects/testing
Browse files Browse the repository at this point in the history
Changes several things of Rtfm Bot
  • Loading branch information
JDJGInc authored May 5, 2024
2 parents 659165d + 80f0a9b commit 0e0cde4
Show file tree
Hide file tree
Showing 12 changed files with 820 additions and 84 deletions.
Binary file modified bot.db
Binary file not shown.
4 changes: 2 additions & 2 deletions cogs/rtfm.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from random import randint
from typing import TYPE_CHECKING, Any, Optional, Union

import discord
from discord import AllowedMentions, Embed
from discord.ext import commands
import discord

from utils.extra import RTFMEmbedPaginator, reference
import utils
from utils import fuzzy
from utils.extra import RTFMEmbedPaginator, reference

if TYPE_CHECKING:
from discord.ext.commands import Context
Expand Down
191 changes: 121 additions & 70 deletions cogs/rtfm_slash.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
from __future__ import annotations

import typing
from typing import TYPE_CHECKING
import os
from typing import TYPE_CHECKING, Optional

from discord.app_commands import AppCommandError, Choice
from discord.app_commands import command as app_command
from discord.ext import commands
import discord
from discord import app_commands
from utils import fuzzy
from discord.app_commands import Choice, Transform, Transformer
from discord.ext import commands

import utils
from utils import fuzzy
from utils.extra import RtfmObject

if TYPE_CHECKING:
from discord import Interaction
Expand All @@ -19,102 +20,152 @@
RTFMBot = commands.Bot


class RTFMSlash(commands.Cog):
def __init__(self, bot: RTFMBot) -> None:
self.bot = bot

@app_commands.command(description="looks up docs", name="rtfm")
async def rtfm_slash(
self, interaction: discord.Interaction, library: str, query: typing.Optional[str] = None
) -> None:
"""Looks up docs for a library with optionally a query."""
if query is None or query == "No Results Found":
return await interaction.response.send_message(f"Alright Let's see \n{library}")
class LibraryTransformer(Transformer):
async def transform(self, interaction: Interaction[RTFMBot], value: str) -> str:
return interaction.client.rtfm_libraries.get(value, value)

await interaction.response.send_message(f"Alright Let's see \n{library+query}")
async def autocomplete(self, interaction: Interaction[RTFMBot], current: str) -> list[Choice]:
choices = [Choice(name=name, value=name) for name in interaction.client.rtfm_libraries]
start_with = list(filter(lambda x: x.name.startswith(current), choices)) or choices
return start_with[:25]

@rtfm_slash.autocomplete("library")
async def rtfm_library_autocomplete(self, interaction: discord.Interaction, current: str) -> list[Choice]:
libraries = self.bot.rtfm_libraries

all_choices: list[Choice] = [Choice(name=name, value=link) for name, link in libraries.items()]
startswith: list[Choice] = [choices for choices in all_choices if choices.name.startswith(current)]
if not (current and startswith):
return all_choices[0:25]
class QueryTransformer(Transformer):
async def transform(self, interaction: Interaction[RTFMBot], value: str) -> RtfmObject:
library = interaction.client.rtfm_libraries.get(interaction.namespace.library, interaction.namespace.library)
library = library or interaction.client.rtfm_libraries["master"]
unfiltered_results = await utils.rtfm(interaction.client, library)
if item := fuzzy.find(value, unfiltered_results, key=lambda t: t.name):
return item

return startswith[0:25]
raise commands.BadArgument("No Results Found")

@rtfm_slash.autocomplete("query")
async def rtfm_query_autocomplete(self, interaction: discord.Interaction, current: str) -> list[Choice]:
url = interaction.namespace.library or list(dict(self.rtfm_dictionary).values())[0]
unfiltered_results = await utils.rtfm(self.bot, url)
async def autocomplete(self, interaction: Interaction[RTFMBot], current: str) -> list[Choice]:
library = interaction.client.rtfm_libraries.get(interaction.namespace.library, interaction.namespace.library)
library = library or interaction.client.rtfm_libraries["master"]
unfiltered_results = await utils.rtfm(interaction.client, library)
choices = [
Choice(name=result.name, value=result.name)
for result in fuzzy.finder(current, unfiltered_results, key=lambda t: t.name)
]
return choices[:25]

all_choices = [Choice(name=result.name, value=result.url.replace(url, "")) for result in unfiltered_results]

if not current:
return all_choices[:25]
class DocsQueryTransformer(Transformer):
async def transform(self, interaction: Interaction[RTFMBot], value: str) -> RtfmObject:
unfiltered_results = await utils.algolia_lookup(
interaction.client,
os.environ["ALGOLIA_APP_ID"],
os.environ["ALGOLIA_API_KEY"],
"discord",
value,
)

filtered_results = fuzzy.finder(current, unfiltered_results, key=lambda t: t[0])
if result := fuzzy.find(value, unfiltered_results, key=lambda t: t.name):
return result

results = [Choice(name=result.name, value=result.url.replace(url, "")) for result in filtered_results]
raise commands.BadArgument("No Results Found")

return results[:25]
async def autocomplete(self, interaction: Interaction[RTFMBot], current: str) -> list[Choice]:
unfiltered_results = await utils.algolia_lookup(
interaction.client,
os.environ["ALGOLIA_APP_ID"],
os.environ["ALGOLIA_API_KEY"],
"discord",
current,
)
# use new method to handle results from discord ologia, but fuzzy can be used now
# I will remove the starting discord api docs if necessary.

@rtfm_slash.error
async def rtfm_error(self, interaction: discord.Interaction, error) -> None:
await interaction.response.send_message(f"{error}! Please Send to this to my developer", ephemeral=True)
print(error)
print(interaction.command)
all_choices = [Choice(name=result.name, value=result.name) for result in unfiltered_results]

@app_commands.command(description="looks up docs from discord developer docs", name="docs")
async def docs(self, interaction: discord.Interaction, query: typing.Optional[str] = None) -> None:
"""Looks up docs from discord developer docs with optionally a query."""
if not current:
return all_choices[:25]

url = "https://discord.com/developers/docs/"
if query is None or query == "No Results Found":
# place holder for now.
return await interaction.response.send_message(f"Alright Let's see \n{url}")
filtered_results = fuzzy.finder(current, unfiltered_results, key=lambda t: t.name)

await interaction.response.send_message(f"Alright Let's see \n{url+query}")
results = [Choice(name=result.name, value=result.name) for result in filtered_results]

@docs.autocomplete("query")
async def docs_autocomplete(self, interaction: discord.Interaction, current: str) -> list[Choice]:
if not results:
results = [Choice(name="Getting Started", value="Getting Started")]

url = "https://discord.com/developers/docs/"
return results[:25]

unfiltered_results = await utils.algolia_lookup(
self.bot, os.environ["ALGOLIA_APP_ID"], os.environ["ALGOLIA_API_KEY"], "discord", current
)
# use new method to handle results from discord ologia, but fuzzy can be used now
# I will remove the starting discord api docs if necessary.

all_choices = [Choice(name=result.name, value=result.url.replace(url, "")) for result in unfiltered_results]
Library = Transform[str, LibraryTransformer]
Query = Transform[RtfmObject, QueryTransformer]
DocsQuery = Transform[RtfmObject, DocsQueryTransformer]

if not current:
return all_choices[:25]

filtered_results = fuzzy.finder(current, unfiltered_results, key=lambda t: t[0])
class RTFMSlash(commands.Cog):
def __init__(self, bot: RTFMBot) -> None:
self.bot = bot

results = [Choice(name=result.name, value=result.url.replace(url, "")) for result in filtered_results]
@app_commands.command(name="rtfm")
@app_commands.user_install()
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def rtfm_slash(
self,
interaction: Interaction[RTFMBot],
library: Optional[Library],
query: Optional[Query],
) -> None:
"""Looks up docs for a library with optionally a query.
Parameters
----------
library : str
The library to search for.
query : RtfmObject
The query to search for.
"""
url = query.url if query else library
await interaction.response.send_message(f"Alright Let's see \n{url}")

for result in results:
if len(result.value) > 100:
print(result.value)
@rtfm_slash.error
async def rtfm_error(self, interaction: discord.Interaction, error) -> None:
await interaction.response.send_message(f"{error}! Please Send to this to my developer", ephemeral=True)
print(error)
print(interaction.command)

# seems to have issues with some sizes.
@app_commands.command()
@app_commands.user_install()
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def docs(self, interaction: Interaction[RTFMBot], query: Optional[DocsQuery] = None):
"""Looks up docs from discord developer docs with optionally a query.
if not results:
result = utils.RtfmObject("Getting Started", "https://discord.com/developers/docs/")
results = [Choice(name=result.name, value=result.url.replace(url, ""))]
Parameters
----------
query : RtfmObject
The query to search for.
"""

return results[:25]
if not query:
return await interaction.response.send_message("https://discord.com/developers/docs/")

await interaction.response.send_message(f"Alright Let's see \n{query.url}")

@docs.error
async def docs_error(self, interaction: discord.Interaction, error) -> None:
await interaction.response.send_message(f"{error}! Please Send to this to my developer", ephemeral=True)
print(error)
print(interaction.command)

@app_commands.command()
@app_commands.user_install()
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def source(self, interaction: Interaction[RTFMBot]):
"""Sends link to the bot's source code"""
view = discord.ui.View()
view.add_item(
discord.ui.Button(
label=f"Source",
url="https://github.com/JDsProjects/Rtfm-Bot",
style=discord.ButtonStyle.link,
)
)
await interaction.response.send_message("Source: https://github.com/JDsProjects/Rtfm-Bot", view=view)


async def setup(bot: RTFMBot) -> None:
await bot.add_cog(RTFMSlash(bot))
3 changes: 2 additions & 1 deletion data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,6 @@ INSERT INTO "RTFM_DICTIONARY" ("name","link") VALUES ('aiogifs','https://aiogifs
('pytube','https://pytube.io/en/latest/'),
('quart','https://quart.palletsprojects.com/en/latest/'),
('vt-py','https://virustotal.github.io/vt-py/'),
('wavelink','https://wavelink.readthedocs.io/en/latest/');
('wavelink','https://wavelink.readthedocs.io/en/latest/'),
('litestar','https://docs.litestar.dev/2/');
COMMIT;
5 changes: 4 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@ async def close(self) -> None:
await super().close()


bot = RTFMBot(command_prefix=get_prefix, intents=Intents(messages=True, message_content=True, guilds=True))
bot = RTFMBot(
command_prefix=get_prefix,
intents=Intents(messages=True, message_content=True, guilds=True),
)


@bot.event
Expand Down
Loading

0 comments on commit 0e0cde4

Please sign in to comment.