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

add-voicevox-speakerコマンドをインタラクティブに #175

Merged
merged 2 commits into from
Apr 2, 2022
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
7 changes: 7 additions & 0 deletions src/commandContextSlash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,13 @@ export class CommandContextSlash extends CommandContext {
content,
components,
channel,
ephemeral = false,
}: {
type?: ReplyType;
content: string | MessageEmbed | MessageEmbed[];
components?: MessageActionRow[];
channel?: Readonly<TextChannel>;
ephemeral?: boolean;
}): Promise<Message> {
if (Array.isArray(content) && content.length > 10) {
logger.error("10個以上のembedsを含む返信にはreplyMultiを使用する必要があります");
Expand All @@ -99,12 +101,14 @@ export class CommandContextSlash extends CommandContext {
embeds: embeds,
components: components,
fetchReply: true,
ephemeral: ephemeral,
});
} else {
const message = await this.interaction.reply({
embeds: embeds,
components: components,
fetchReply: true,
ephemeral: ephemeral,
});
clearTimeout(this.differTimer);
return message;
Expand All @@ -115,10 +119,12 @@ export class CommandContextSlash extends CommandContext {
type = "plain",
content,
channel,
ephemeral,
}: {
type?: ReplyType;
content: MessageEmbed[];
channel?: Readonly<TextChannel>;
ephemeral?: boolean;
}): Promise<Message[]> {
const embeds = constructEmbeds(type, content);

Expand All @@ -131,6 +137,7 @@ export class CommandContextSlash extends CommandContext {
type: type,
content: embedsChunk,
channel: channel,
ephemeral: ephemeral,
});
});

Expand Down
260 changes: 224 additions & 36 deletions src/handler/command/configSub/addSpeakerVoicevoxSub.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,247 @@
import { CommandInteraction } from "discord.js";
import {
Collection,
MessageActionRow,
MessageButton,
MessageSelectMenu,
MessageSelectOptionData,
} from "discord.js";

import { ConfigEachLevel, MasterLevel } from "../../../config/typesConfig";
import { CommandContextSlash } from "../../../commandContextSlash";
import { MasterLevel } from "../../../config/typesConfig";
import { SpeakerBuildOption } from "../../../speaker/voiceProvider";
import { createVoicevoxClient } from "../../../speaker/voicevoxApi";
import { AddSpeakerSubHandler } from "../../base/addSpeakerSubHandler";
import { VoicevoxSpeakerBuildOption } from "../../../speaker/voicevoxSpeaker";
import { ConfigSubCommandHandler } from "../../base/configSubCommandHandler";
import { SubCommandProps } from "../../base/subCommandHandler";

export class AddSpeakerVoicevoxSub extends AddSpeakerSubHandler {
protected initCommandProps(): SubCommandProps {
export class AddSpeakerVoicevoxSub extends ConfigSubCommandHandler<MasterLevel> {
protected override initCommandProps(): SubCommandProps {
return {
name: "add-voicevox",
description: "VOICEVOXによるボイスの追加",
options: [
{
name: "name",
description: "ボイスの登録名",
type: "STRING",
required: true,
},
{
name: "url",
description: "VOICEVOXエンジンのURLBase",
type: "STRING",
required: true,
},
{
name: "styleid",
description: "追加したいspeakerのstyleのId",
type: "NUMBER",
required: true,
},
],
permission: this.getPermissionLevel(),
};
}

protected async getValueFromOptions(
options: CommandInteraction["options"],
oldValue: Readonly<ConfigEachLevel<MasterLevel>["speakerBuildOptions"]> | undefined
): Promise<ConfigEachLevel<MasterLevel>["speakerBuildOptions"] | undefined> {
const voiceName = options.getString("name", true);
const urlBase = options.getString("url", true);
const styleId = options.getNumber("styleid", true);

const option: SpeakerBuildOption = {
type: "voicevox",
voiceName: voiceName,
urlBase: urlBase,
...(await fetchVoicevoxSpeakerIds(urlBase, styleId)),
};
override async execute(context: CommandContextSlash): Promise<void> {
const accessor = this.getConfigAccessor(context);

return {
...oldValue,
[voiceName]: option,
};
const baseUrl = await this.inquireUrl(context);
if (baseUrl === null) {
await context.reply({
type: "error",
content: "URLが指定されませんでした.",
ephemeral: true,
});
return;
}

const selectedSpeakers = await this.inquireVoice(context, baseUrl);
if (selectedSpeakers === null) {
await context.reply({
type: "error",
content: "Speakerが指定されませんでした.",
ephemeral: true,
});
return;
}

const oldValue = (await accessor.get("speakerBuildOptions")) ?? {};

const setValue = selectedSpeakers.reduce((acc, cur) => {
return {
...acc,
[cur.voiceName]: cur,
};
}, oldValue);

await accessor.set("speakerBuildOptions", setValue);
await context.reply({
content: `Speakerを追加しました!
${selectedSpeakers.map((speaker) => ` ${speaker.voiceName}`).join("\n")}`,
});
}

protected async getVoicesCollection(
context: CommandContextSlash
): Promise<Collection<string, SpeakerBuildOption>> {
const accessor = this.getConfigAccessor(context);

const existingVoices = (await accessor.get("speakerBuildOptions")) ?? {};
return new Collection(Object.entries(existingVoices));
}

protected async inquireUrl(context: CommandContextSlash): Promise<string | null> {
try {
const urlOption = context.getOptions().getString("url");
if (urlOption) {
return urlOption;
}

const existingVoicesCollection = await this.getVoicesCollection(context);
const existingUrls = Array.from(
new Set(
existingVoicesCollection
.filter((value) => value.type === "voicevox")
.map((value) => value.urlBase)
)
);

if (existingUrls.length === 0) {
return null;
}

const options: MessageSelectOptionData[] = existingUrls.map((item) => ({
label: item,
value: item,
}));
const baseUrlMenu = new MessageSelectMenu()
.setCustomId("url")
.addOptions(options)
.setPlaceholder("BaseUrl");

const message = await context.reply({
content: "VOICEVOXのエンドポイントを選択",
components: [new MessageActionRow().addComponents(baseUrlMenu)],
ephemeral: true,
});

const resInteraction = await message.awaitMessageComponent({
time: 5 * 60 * 1000,
filter: (interaction) => {
return interaction.user.id === context.interaction.user.id;
},
componentType: "SELECT_MENU",
});

await resInteraction.deferUpdate();
return resInteraction.values[0];
} catch (e) {
this.logger.warn(e);
return null;
}
}

protected async inquireVoice(
context: CommandContextSlash,
url: string
): Promise<
| (VoicevoxSpeakerBuildOption & {
voiceName: string;
})[]
| null
> {
try {
const client = createVoicevoxClient(url);

const speakers = await client.speakers.$get();

const speakersOptions: MessageSelectOptionData[] = speakers.map((value) => ({
label: value.name,
value: value.speaker_uuid,
}));
const speakerMenu = new MessageSelectMenu()
.setCustomId("speaker")
.addOptions(speakersOptions)
.setPlaceholder("Speaker");

const speakerMessage = await context.reply({
content: "Speakerを選択",
components: [new MessageActionRow().addComponents(speakerMenu)],
ephemeral: true,
});

const speakerResInteraction = await speakerMessage.awaitMessageComponent({
time: 5 * 60 * 1000,
filter: (interaction) => {
return interaction.user.id === context.interaction.user.id;
},
componentType: "SELECT_MENU",
});
this.logger.trace(speakerResInteraction.toJSON());
await speakerResInteraction.deferUpdate();

const uuid = speakerResInteraction.values[0];

this.logger.trace(`selected: ${uuid}`);

const selectedSpeaker = speakers.find((speaker) => speaker.speaker_uuid === uuid);
this.logger.trace(`selectedSpeaker: ${selectedSpeaker?.name}`);
const styles = selectedSpeaker?.styles;
this.logger.trace(`styles: ${styles}`);
if (!selectedSpeaker || !styles) return null;

const stylesOptions: MessageSelectOptionData[] = styles.map((value) => ({
label: value.name,
value: value.name,
}));
const stylesMenu = new MessageSelectMenu()
.setCustomId("styles")
.addOptions(stylesOptions)
.setPlaceholder("Style")
.setMinValues(1)
.setMaxValues(stylesOptions.length);

const confirmButton = new MessageButton()
.setCustomId("confirm")
.setStyle("PRIMARY")
.setLabel("追加");

const styleMessage = await context.reply({
content: "スタイルを選択",
components: [
new MessageActionRow().addComponents(stylesMenu),
new MessageActionRow().addComponents(confirmButton),
],
ephemeral: true,
});

let selectedStyles: string[] = [];
const collector = styleMessage.createMessageComponentCollector({
time: 5 * 60 * 1000,
filter: (interaction) => {
return (
interaction.user.id === context.interaction.user.id &&
interaction.customId === stylesMenu.customId
);
},
componentType: "SELECT_MENU",
});
collector.on("collect", async (interaction) => {
await interaction.deferUpdate();
selectedStyles = interaction.values;
});

const styleResInteraction = await styleMessage.awaitMessageComponent({
time: 5 * 60 * 1000,
filter: (interaction) => {
return (
interaction.user.id === context.interaction.user.id &&
interaction.customId === confirmButton.customId
);
},
componentType: "BUTTON",
});
await styleResInteraction.deferUpdate();

return selectedStyles.map((style) => ({
voiceName: `${selectedSpeaker.name}(${style})`,
speakerUUID: uuid,
type: "voicevox",
urlBase: url,
styleName: style,
}));
} catch (e) {
this.logger.warn(e);
return null;
}
}
}

Expand Down