Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2.22.13 #155

Merged
merged 9 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 5 additions & 13 deletions docker/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,28 +1,20 @@
FROM alpine AS runtime
#FROM python:3.12-slim AS runtime

VOLUME /config
WORKDIR /app

RUN apk update; apk add --no-cache python3 tesseract-ocr-data-eng re2-dev
#ENV DEBIAN_FRONTEND=noninteractive APT="apt-get -qq"
#RUN $APT update; \
# $APT install tesseract-ocr; \
# $APT clean; \
# rm -rf /var/lib/apt/lists/*

FROM alpine AS build
#FROM python:3.12-slim AS build

WORKDIR /deps

#RUN pip --no-cache-dir install --progress-bar=off "poetry==1.8"
RUN apk update
RUN apk add --no-cache g++ git re2-dev poetry python3-dev
RUN apk update; apk add --no-cache g++ git re2-dev poetry python3-dev

COPY pyproject.toml poetry.lock poetry.toml ./
RUN python -VV
RUN poetry env use $(which python)
RUN poetry install -nvvv --no-root --compile --only main

COPY fred ./fred/
RUN poetry install -nvvv --only-root --compile

Expand All @@ -31,5 +23,5 @@ FROM runtime
COPY --from=build /deps/.venv ./venv
COPY fred ./fred/
COPY *.env .
RUN pwd
CMD ./venv/bin/python -m fred

CMD ["./venv/bin/python", "-m", "fred"]
1 change: 0 additions & 1 deletion fred/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import json
import os
import pathlib
from numbers import Number
Expand Down
2 changes: 1 addition & 1 deletion fred/fred.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ async def on_error(self, event_method: str, *args, **kwargs):
async def githook_send(self, data: dict):
self.logger.info("Handling GitHub payload", extra={"data": data})

embed: nextcord.Embed | None = await createembed.run(data)
embed: nextcord.Embed | None = await createembed.github_embed(data)
if embed is None:
self.logger.info("Non-supported Payload received")
else:
Expand Down
130 changes: 74 additions & 56 deletions fred/fred_commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
import inspect
import io
import logging
import re
from os.path import split
from urllib.parse import urlparse

import nextcord
from algoliasearch.search_client import SearchClient
import re2
from algoliasearch.search.client import SearchClient
from nextcord.ext.commands.view import StringView

from ._baseclass import BaseCmds, common, config, commands
Expand Down Expand Up @@ -76,44 +76,51 @@ async def on_message(self, message: nextcord.Message):

prefix = self.bot.command_prefix
self.logger.info("Processing a message", extra=common.message_info(message))
if message.content.startswith(prefix):
name = message.content.lower().lstrip(prefix).split(" ")[0]
self.logger.info(f"Processing the command {name}", extra=common.message_info(message))
if (command := config.Commands.fetch(name)) is not None:
if (
(content := command["content"])
and content.startswith(prefix) # for linked aliases of commands like ff->rp
and (linked_command := config.Commands.fetch(content.lstrip(prefix)))
):
command = linked_command
content = linked_command["content"]

if (attachment := command["attachment"]) is not None:
async with self.bot.web_session.get(attachment) as resp:
buff = io.BytesIO(await resp.read())
_, filename = split(urlparse(attachment).path)
attachment = nextcord.File(filename=filename, fp=buff)
args = []
view = StringView(message.content.lstrip(prefix))
view.get_word() # command name
while not view.eof:
view.skip_ws()
args.append(view.get_quoted_word())
if content:
# ok who wrote this unreadable garbage? oh wait, it was me - Borketh
# this should probably be simplified...
text = re.sub(
r"{(\d+)}",
lambda match: (
args[int(match.group(1))] if int(match.group(1)) < len(args) else "(missing argument)"
),
content,
).replace("{...}", " ".join(args))
else:
text = None

await self.bot.reply_to_msg(message, text, file=attachment)
return
command_pattern = re2.compile(rf"{re2.escape(prefix)}(\S+)\s*(.*)")
if (match := re2.match(command_pattern, message.content)) is None:
return

(name, arguments) = match.groups()

self.logger.info(f"Processing the command {name}", extra=common.message_info(message))

if (command := config.Commands.fetch(name)) is None:
return

if (
(content := command["content"])
and content.startswith(prefix) # for linked aliases of commands like ff->rp
and (linked_command := config.Commands.fetch(content.lstrip(prefix)))
):
command = linked_command
content = linked_command["content"]

if (attachment := command["attachment"]) is not None:
async with self.bot.web_session.get(attachment) as resp:
buff = io.BytesIO(await resp.read())
_, filename = split(urlparse(attachment).path)
attachment = nextcord.File(filename=filename, fp=buff, force_close=True)

args = []
view = StringView(arguments)
while not view.eof:
view.skip_ws()
args.append(view.get_quoted_word())

if content:
text = str(content)
substitutions = map(int, re2.findall(r"{(\d+)}", text))
for substitution in substitutions:
text = re2.sub(
rf"\{{{substitution}\}}",
args[substitution] if substitution < len(args) else "(missing argument)",
text,
)
text = text.replace("{...}", " ".join(args) if args else "(no arguments given)")
else:
text = None

await self.bot.reply_to_msg(message, text, file=attachment)

@commands.command()
async def mod(self, ctx: commands.Context, *, mod_name: str) -> None:
Expand All @@ -137,12 +144,17 @@ async def mod(self, ctx: commands.Context, *, mod_name: str) -> None:
if view:

async def callback(interaction: nextcord.Interaction):
logging.info(interaction.data.values)
new_embed, new_attachment, _ = await createembed.mod_embed(interaction.data["values"][0], self.bot)
# Two edits because the view doesn't go away with one... go figure why
await msg.edit(view=None)
await msg.edit(embed=new_embed, file=new_attachment)
view.stop()
if interaction.user == ctx.author:
logging.info(interaction.data.values)
new_embed, new_attachment, _ = await createembed.mod_embed(
interaction.data["values"][0], self.bot
)
# Two edits because the view doesn't go away with one... go figure why
await msg.edit(view=None)
await msg.edit(embed=new_embed, file=new_attachment)
view.stop()
else:
await interaction.send("Only the user who called this command can do this!", ephemeral=True)

async def timeout():
await msg.edit(view=None)
Expand All @@ -157,16 +169,22 @@ async def docsearch(self, ctx: commands.Context, *, search: str) -> None:
"""Usage: `docsearch (search: str)`
Response: Equivalent to using the search function on the SMR docs page; links the first search result"""
self.logger.info(f"Searching the documentation. {search =}")
client: SearchClient = SearchClient.create("BH4D9OD16A", "53b3a8362ea7b391f63145996cfe8d82")
index = client.init_index("ficsit")
index.set_settings({"searchableAttributes": ["url"]})
query = index.search(search, {"attributesToRetrieve": "*"})
import json

self.logger.debug(json.dumps(query, indent=2))
for hit in query["hits"]:
if hit["hierarchy"]["lvl0"].endswith("latest"):
await self.bot.reply_to_msg(ctx.message, f"This is the best result I got from the SMD :\n{hit['url']}")
client: SearchClient = SearchClient("2FDCZBLZ1A", "28531804beda52a04275ecd964db429d")

query = await client.search_single_index(
index_name="ficsit",
search_params={
"query": search,
"facetFilters": [
"component_name:satisfactory-modding",
"component_version:latest",
],
},
)

for hit in query.hits:
if hit.hierarchy["lvl0"].endswith("latest"):
await self.bot.reply_to_msg(ctx.message, f"This is the best result I got from the SMD :\n{hit.url}")
return


Expand Down
16 changes: 16 additions & 0 deletions fred/fred_commands/_baseclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,22 @@ async def get(self, ctx: commands.Context):
await self.bot.reply_to_msg(ctx.message, "Invalid sub command passed...")
return

@commands.command()
@commands.check(common.l4_only)
async def alias(self, ctx: commands.Context):
"""Usage: don't
Purpose: to remind people that this isn't how you do this command
Notes: see issue #102"""
probably_command = ctx.message.content.partition("alias")[2].split()[0]
if probably_command in ("add", "remove"):
await self.bot.reply_to_msg(
ctx.message, f"This is not the right command! Use `{probably_command} alias` instead!"
)
else:
await self.bot.reply_to_msg(
ctx.message, f"This wouldn't even be a valid command if you did it the right way around!"
)


class SearchFlags(commands.FlagConverter, delimiter="=", prefix="-"):
column: str = "name"
Expand Down
2 changes: 1 addition & 1 deletion fred/libraries/createembed.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def timestamp(iso8601: str) -> str:


# GitHub Update Embed Formats
async def run(data: dict) -> nextcord.Embed | None:
async def github_embed(data: dict) -> nextcord.Embed | None:
embed = None

global repo_name, repo_full_name
Expand Down
Loading