Skip to content

Commit

Permalink
Integrate Fluent API
Browse files Browse the repository at this point in the history
  • Loading branch information
SeoulSKY committed Feb 22, 2024
1 parent a0a8b31 commit 335ffb7
Show file tree
Hide file tree
Showing 17 changed files with 342 additions and 177 deletions.
14 changes: 8 additions & 6 deletions commands/arcaea.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
from discord.ext.commands import Bot

from utils import templates, ui
from utils.constants import DEFAULT_LOCALE
from utils.translator import Localization

LINK_PLAY_LIFESPAN_MINUTES = 30
LINK_PLAY_LIFESPAN = datetime.timedelta(minutes=LINK_PLAY_LIFESPAN_MINUTES)

logger = logging.getLogger(__name__)

loc = Localization(["en"], [os.path.join("commands", "arcaea.ftl")])
loc = Localization(DEFAULT_LOCALE, [os.path.join("commands", "arcaea.ftl")])
EMPTY_TEXT = loc.format_value("empty")


Expand Down Expand Up @@ -140,13 +141,14 @@ class Arcaea(app_commands.Group):
"""

def __init__(self, bot: Bot):
super().__init__()
super().__init__(name=loc.format_value("arcaea-name"), description=loc.format_value("arcaea-description"))
self.bot = bot

@app_commands.command(description=loc.format_value("description", {
"duration": LINK_PLAY_LIFESPAN_MINUTES
}))
@app_commands.describe(roomcode=loc.format_value("roomcode"))
@app_commands.command(name=loc.format_value("linkplay-name"),
description=loc.format_value("linkplay-description", {
"duration": LINK_PLAY_LIFESPAN_MINUTES
}))
@app_commands.describe(roomcode=loc.format_value("linkplay-roomcode-description"))
async def linkplay(self, interaction: Interaction, roomcode: str):
"""
Create an embed to invite people to your Link Play
Expand Down
26 changes: 14 additions & 12 deletions commands/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,20 @@
from discord.ext.commands import Bot

from mongo.user import User, get_user, set_user
from utils.constants import DEFAULT_LOCALE
from utils.templates import info, success, error
from utils.translator import is_english, languages, language_to_code, Localization, locale_to_language, Translator
from utils.translator import is_english, languages, language_to_code, Localization, Translator, code_to_language

loc = Localization(DEFAULT_LOCALE, [os.path.join("commands", "chat.ftl")])


class Chat(app_commands.Group):
"""
Commands related to AI chats
"""

loc = Localization(["en"], [os.path.join("commands", "chat.ftl")])

def __init__(self, bot: Bot):
super().__init__()
super().__init__(name=loc.format_value("chat-name"), description=loc.format_value("chat-description"))
self.bot = bot
self._logger = logging.getLogger(__name__)
self._client = PyAsyncCAI(os.getenv("CAI_TOKEN"))
Expand Down Expand Up @@ -67,11 +68,11 @@ async def on_message(message: Message):
self.bot.add_listener(on_message)

def _timeout_message(self) -> str:
return info(self.loc.format_value("timeout", {"name": self.bot.user.display_name}))
return info(loc.format_value("timeout", {"name": self.bot.user.display_name}))

@staticmethod
def _error_message() -> str:
return error(Chat.loc.format_value("error", {"name": "SeoulSKY"}))
return error(loc.format_value("error", {"name": "SeoulSKY"}))

async def _create_new_chat(self, user: User, user_name: str):
response = await self._client.chat.new_chat(os.getenv("CAI_CHAR_ID"))
Expand All @@ -95,9 +96,10 @@ async def _send_message(self, user: User, text: str) -> str:

return content

@app_commands.command(name=loc.format_value("name"), description=loc.format_value("description"))
@app_commands.command(name=loc.format_value("update-language-name"),
description=loc.format_value("update-language-description"))
@app_commands.choices(language=[Choice(name=lang.title(), value=language_to_code(lang)) for lang in languages])
@app_commands.describe(language=loc.format_value("language"))
@app_commands.describe(language=loc.format_value("update-language-language-description"))
async def update_language(self, interaction: Interaction, language: str = None):
"""
Update the chat language to the current discord language
Expand All @@ -107,19 +109,19 @@ async def update_language(self, interaction: Interaction, language: str = None):
await set_user(user)

await interaction.response.send_message(
self.loc.format_value("updated", {"language": locale_to_language(user.locale).title()}),
loc.format_value("updated", {"language": code_to_language(user.locale).title()}),
ephemeral=True
)

@app_commands.command(name=loc.format_value("name2"), description=loc.format_value("description2"))
@app_commands.command(name=loc.format_value("clear-name"), description=loc.format_value("clear-description"))
async def clear(self, interaction: Interaction):
"""
Clear the chat history between you and this bot
"""
user = await get_user(interaction.user.id)
if user.chat_history_id is None:
await interaction.response.send_message(
error(self.loc.format_value("no-history", {"name": interaction.client.user.display_name})),
error(loc.format_value("no-history", {"name": interaction.client.user.display_name})),
ephemeral=True)
return

Expand All @@ -136,4 +138,4 @@ async def clear(self, interaction: Interaction):
user.chat_history_tgt = None
await set_user(user)

await interaction.followup.send(success(self.loc.format_value("deleted")), ephemeral=True)
await interaction.followup.send(success(loc.format_value("deleted")), ephemeral=True)
21 changes: 11 additions & 10 deletions commands/movie.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from tqdm import tqdm

from utils import templates, constants
from utils.constants import ErrorCode, DEFAULT_LOCALE
from utils.translator import Localization

DESKTOP_CACHE_PATH = os.path.join(constants.CACHE_DIR, "movie", "desktop")
Expand Down Expand Up @@ -69,6 +70,8 @@
Maximum value of RGB for each pixel
"""

loc = Localization(DEFAULT_LOCALE, [os.path.join("commands", "movie.ftl")])


class Movie(app_commands.Group):
"""
Expand All @@ -84,10 +87,8 @@ class Movie(app_commands.Group):
_num_playing = 0
_lock = threading.Lock()

loc = Localization(["en"], [os.path.join("commands", "movie.ftl")])

def __init__(self, bot: Bot):
super().__init__()
super().__init__(name=loc.format_value("movie-name"), description=loc.format_value("movie-description"))
self.bot = bot

if not os.path.exists(DESKTOP_CACHE_PATH) or not os.path.exists(MOBILE_CACHE_PATH):
Expand Down Expand Up @@ -132,17 +133,17 @@ async def get_frames(name: str, is_on_mobile: bool) -> list[str]:

return Movie._cache[path]

@app_commands.command(description=loc.format_value("description"))
@app_commands.describe(title=loc.format_value("title"))
@app_commands.describe(fps=loc.format_value("fps", {
@app_commands.command(name=loc.format_value("play-name"), description=loc.format_value("play-description"))
@app_commands.describe(title=loc.format_value("play-title-description"))
@app_commands.describe(fps=loc.format_value("play-fps-description", {
"min": FPS_MIN, "max": FPS_MAX, "default": FPS_DEFAULT
}))
@app_commands.describe(original_speed=loc.format_value("original-speed", {
@app_commands.describe(original_speed=loc.format_value("play-original-speed-description", {
"default": str(ORIGINAL_SPEED_DEFAULT)
}))
@app_commands.choices(title=[
Choice(name="Bad Apple", value="bad_apple"),
Choice(name="Ultra B+K", value="ultra_b+k")
Choice(name="Bad Apple!!", value="bad_apple"),
Choice(name="ULTRA B+K", value="ultra_b+k")
])
@app_commands.choices(fps=[Choice(name=str(i), value=i) for i in range(FPS_MIN, FPS_MAX + 1)])
async def play(self, interaction: Interaction,
Expand Down Expand Up @@ -183,7 +184,7 @@ async def display():
except NotFound: # Message is deleted
display.cancel()
except HTTPException as ex:
if ex.code == 50027:
if ex.code == ErrorCode.MESSAGE_EXPIRED:
message = await message.channel.fetch_message(message.id)
await message.edit(embed=embed)
else:
Expand Down
8 changes: 4 additions & 4 deletions commands/ping.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
import discord
from discord import app_commands

from utils.constants import BOT_NAME
from utils.constants import BOT_NAME, DEFAULT_LOCALE
from utils.templates import info
from utils.translator import Localization

loc = Localization(["en"], [os.path.join("commands", "ping.ftl")])
loc = Localization(DEFAULT_LOCALE, [os.path.join("commands", "ping.ftl")])


@app_commands.command(name=loc.format_value("name"),
description=loc.format_value("description", {"name": BOT_NAME}))
@app_commands.command(name=loc.format_value("ping-name"),
description=loc.format_value("ping-description", {"name": BOT_NAME}))
async def ping(interaction: discord.Interaction):
"""Ping this bot"""
await interaction.response.send_message(
Expand Down
35 changes: 19 additions & 16 deletions commands/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,29 @@
from mongo.channel import get_channel, set_channel
from mongo.user import get_user, set_user
from utils import templates, ui
from utils.constants import ErrorCode, Limit
from utils.constants import ErrorCode, Limit, DEFAULT_LOCALE
from utils.templates import success
from utils.translator import BatchTranslator, locale_to_code, Localization

loc = Localization(DEFAULT_LOCALE, [os.path.join("commands", "translator.ftl")])


class ChannelLanguageSelect(ui.LanguageSelect):
"""
Select UI to select available languages for a channel
"""

def __init__(self, locale: Locale):
self.localization = Localization([locale_to_code(locale)],
[os.path.join("commands", "translator.ftl")])
super().__init__(self.localization.format_value("select-channel-languages"))
self.loc = Localization(locale_to_code(locale),[os.path.join("commands", "translator.ftl")])
super().__init__(self.loc.format_value("select-channel-languages"))

async def callback(self, interaction: Interaction):
config = await get_channel(interaction.channel_id)
config.translate_to = self.values
await set_channel(config)

await interaction.response.send_message(
success(self.localization.format_value("channel-languages-updated")), ephemeral=True
success(self.loc.format_value("channel-languages-updated")), ephemeral=True
)


Expand All @@ -41,8 +42,7 @@ class UserLanguageSelect(ui.LanguageSelect):
"""

def __init__(self, locale: Locale):
self.loc = Localization([locale_to_code(locale)],
[os.path.join("commands", "translator.ftl")])
self.loc = Localization(locale_to_code(locale),[os.path.join("commands", "translator.ftl")])
super().__init__(self.loc.format_value("select-your-languages"))

async def callback(self, interaction: Interaction):
Expand All @@ -60,10 +60,9 @@ class Translator(app_commands.Group):
Commands related to translation
"""

doc = Localization(["en"], [os.path.join("commands", "translator.ftl")])

def __init__(self, bot: Bot):
super().__init__()
super().__init__(name=loc.format_value("translator-name"),
description=loc.format_value("translator-description"))
self.bot = bot

self._setup_user_listeners()
Expand Down Expand Up @@ -137,7 +136,8 @@ def _split(string: str, count: int):
for i in range(0, len(string), count):
yield string[i: i + count]

@app_commands.command(name=doc.format_value("name"), description=doc.format_value("description"))
@app_commands.command(name=loc.format_value("set-your-languages-name"),
description=loc.format_value("set-your-languages-description"))
async def set_your_languages(self, interaction: Interaction):
"""
Set languages to be translated for your messages
Expand All @@ -146,7 +146,8 @@ async def set_your_languages(self, interaction: Interaction):
view.add_item(UserLanguageSelect(interaction.locale))
await interaction.response.send_message(view=view, ephemeral=True)

@app_commands.command(name=doc.format_value("name2"), description=doc.format_value("description2"))
@app_commands.command(name=loc.format_value("set-channel-languages-name"),
description=loc.format_value("set-channel-languages-description"))
@app_commands.checks.has_permissions(administrator=True)
async def set_channel_languages(self, interaction: Interaction):
"""
Expand All @@ -156,7 +157,8 @@ async def set_channel_languages(self, interaction: Interaction):
view.add_item(ChannelLanguageSelect(interaction.locale))
await interaction.response.send_message(view=view, ephemeral=True)

@app_commands.command(name=doc.format_value("name3"), description=doc.format_value("description3"))
@app_commands.command(name=loc.format_value("clear-your-languages-name"),
description=loc.format_value("clear-your-languages-description"))
async def clear_your_languages(self, interaction: Interaction):
"""
Clear languages to be translated for your messages
Expand All @@ -165,10 +167,11 @@ async def clear_your_languages(self, interaction: Interaction):
user.translate_to = []
await set_user(user)

await interaction.response.send_message(success(self.doc.format_value("your-languages-cleared")),
await interaction.response.send_message(success(loc.format_value("your-languages-cleared")),
ephemeral=True)

@app_commands.command(name=doc.format_value("name4"), description=doc.format_value("description4"))
@app_commands.command(name=loc.format_value("clear-channel-languages-name"),
description=loc.format_value("clear-channel-languages-description"))
@app_commands.checks.has_permissions(administrator=True)
async def clear_channel_languages(self, interaction: Interaction):
"""
Expand All @@ -178,5 +181,5 @@ async def clear_channel_languages(self, interaction: Interaction):
channel.translate_to = []
await set_channel(channel)

await interaction.response.send_message(success(self.doc.format_value("channel-languages-cleared")),
await interaction.response.send_message(success(loc.format_value("channel-languages-cleared")),
ephemeral=True)
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
"""
Implements translate context menus
Implements a context menu to translate messages
"""
import os

import discord
from discord import app_commands

from utils import translator
from utils.constants import DEFAULT_LOCALE
from utils.translator import Localization, locale_to_code

loc = Localization(["en"], [os.path.join("context_menus", "translate.ftl")])
loc = Localization(DEFAULT_LOCALE, [os.path.join("context_menus", "translate_message.ftl")])


@app_commands.context_menu(name=loc.format_value("name"))
async def translate(interaction: discord.Interaction, message: discord.Message):
@app_commands.context_menu(name=loc.format_value("translate-message-name"))
async def translate_message(interaction: discord.Interaction, message: discord.Message):
"""Translate this message into your language"""
await interaction.response.send_message(
translator.translate(message.content, locale_to_code(interaction.locale)), ephemeral=True
Expand Down
11 changes: 7 additions & 4 deletions locales/en/commands/arcaea.ftl
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# Link Play Command
name = linkplay
description = Create an embed to invite people to your Link Play. It will last for { $duration } minutes
roomcode = Room code of your Arcaea Link Play
# Commands
arcaea-name = arcaea
arcaea-description = Commands related to Arcaea
linkplay-name = linkplay
linkplay-description = Create an embed to invite people to your Link Play. It will last for { $duration } minutes
linkplay-roomcode-name = roomcode
linkplay-roomcode-description = Room code of your Arcaea Link Play
# Embed
title = Arcaea Link Play
Expand Down
14 changes: 9 additions & 5 deletions locales/en/commands/chat.ftl
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
# Commands
name = update_language
description = Update the chat language to the current discord language
language = The new chat language. Defaults to your current discord language
chat-name = chat
chat-description = Commands related to AI chats
name2 = clear
description2 = Clear the chat history between you and this bot
update-language-name = update_language
update-language-description = Update the chat language to the current discord language
update-language-language-name = language
update-language-language-description = The new chat language. Defaults to your current discord language
clear-name = clear
clear-description = Clear the chat history between you and this bot
# Successes
updated = The chat language has been updated to `{ $language }`
Expand Down
16 changes: 12 additions & 4 deletions locales/en/commands/movie.ftl
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
description = Play a movie
title = Title of the movie to play
fps = Number of frames to display per second. Range from { $min } to { $max } (inclusive). Default value is { $default }
original-speed = Play the movie at the original speed by skipping some frames. Default value is { $default }
# Commands
movie-name = movie
movie-description = Commands related to Movie
play-name = play
play-description= Play a movie
play-title-name = title
play-title-description = Title of the movie to play
play-fps-name = fps
play-fps-description = Number of frames to display per second. Range from { $min } to { $max } (inclusive). Default value is { $default }
play-original-speed-name = original_speed
play-original-speed-description = Play the movie at the original speed by skipping some frames. Default value is { $default }
4 changes: 2 additions & 2 deletions locales/en/commands/ping.ftl
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Command
name = ping
description = Check the response time of { $name }
ping-name = ping
ping-description = Check the response time of { $name }
# Successes
latency = Latency: { $value }ms
Loading

0 comments on commit 335ffb7

Please sign in to comment.