mirror of
https://github.com/darksaid98/cadence-discord-bot.git
synced 2026-12-04 14:38:49 +00:00
fix: refactored autocomplete interactions
This commit is contained in:
1 parent
20bc4aa88f
commit
af78759813
4 files changed
+127
-73
No files matched your search
@@ -0,0 +1,16 @@
|
|||||||
|
import { Track } from 'discord-player';
|
||||||
|
|
||||||
|
export function shouldUseLastQuery(query: string, lastQuery?: string, timestamp?: number): boolean {
|
||||||
|
return Boolean(
|
||||||
|
lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - (timestamp ?? 0) < 500
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isQueryTooShort(query: string): boolean {
|
||||||
|
return query.length < 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTrackName(track: Track): string {
|
||||||
|
const name = `${track.title} [Author: ${track.author}]`;
|
||||||
|
return name.length > 100 ? name.slice(0, 100) : name;
|
||||||
|
}
|
||||||
@@ -1,72 +1,101 @@
|
|||||||
import { LyricsData, lyricsExtractor } from '@discord-player/extractor';
|
import { LyricsData, lyricsExtractor } from '@discord-player/extractor';
|
||||||
import { Player, SearchResult, useMainPlayer } from 'discord-player';
|
import { Player, SearchResult, useMainPlayer } from 'discord-player';
|
||||||
import { ApplicationCommandOptionChoiceData } from 'discord.js';
|
import { ApplicationCommandOptionChoiceData } from 'discord.js';
|
||||||
|
import { Logger } from 'pino';
|
||||||
import { BaseAutocompleteInteraction } from '../../classes/interactions';
|
import { BaseAutocompleteInteraction } from '../../classes/interactions';
|
||||||
import { BaseAutocompleteParams, BaseAutocompleteReturnType } from '../../types/interactionTypes';
|
import { getTrackName, isQueryTooShort, shouldUseLastQuery } from '../../common/autocompleteUtils';
|
||||||
|
import { BaseAutocompleteParams, BaseAutocompleteReturnType, RecentQuery } from '../../types/interactionTypes';
|
||||||
// TODO: create type for recent query object
|
|
||||||
const recentQueries = new Map();
|
|
||||||
|
|
||||||
class LyricsAutocomplete extends BaseAutocompleteInteraction {
|
class LyricsAutocomplete extends BaseAutocompleteInteraction {
|
||||||
|
private recentQueries = new Map<string, RecentQuery>();
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super('lyrics');
|
super('lyrics');
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(params: BaseAutocompleteParams): BaseAutocompleteReturnType {
|
async execute({ executionId, interaction }: BaseAutocompleteParams): BaseAutocompleteReturnType {
|
||||||
const { executionId, interaction } = params;
|
|
||||||
const logger = this.getLogger(this.name, executionId, interaction);
|
const logger = this.getLogger(this.name, executionId, interaction);
|
||||||
|
|
||||||
const query: string = interaction.options.getString('query', true);
|
const query: string = interaction.options.getString('query', true);
|
||||||
const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {};
|
const { lastQuery, result, timestamp } = this.recentQueries.get(interaction.user.id) || {};
|
||||||
|
|
||||||
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
|
if (shouldUseLastQuery(query, lastQuery, timestamp)) {
|
||||||
logger.debug(`Responding with results from lastQuery for query '${query}'`);
|
logger.debug(`Responding with results from lastQuery for query '${query}'`);
|
||||||
return interaction.respond(result);
|
return interaction.respond(result as ApplicationCommandOptionChoiceData<string | number>[]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (query.length < 3) {
|
if (isQueryTooShort(query)) {
|
||||||
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
|
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
|
||||||
return interaction.respond([]);
|
return interaction.respond([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
const genius = lyricsExtractor();
|
const autocompleteChoices = await this.getAutocompleteChoices(query, logger);
|
||||||
const lyricsResult: LyricsData = (await genius.search(query).catch(() => null)) as LyricsData;
|
|
||||||
let response: ApplicationCommandOptionChoiceData<string>[] = [];
|
|
||||||
|
|
||||||
if (!lyricsResult) {
|
if (!autocompleteChoices || autocompleteChoices.length === 0) {
|
||||||
logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`);
|
|
||||||
const player: Player = useMainPlayer()!;
|
|
||||||
const searchResults: SearchResult = await player.search(query);
|
|
||||||
response = searchResults.tracks.slice(0, 1).map((track) => ({
|
|
||||||
name:
|
|
||||||
`${track.title} [Artist: ${track.author}]`.length > 100
|
|
||||||
? `${track.title}`.slice(0, 100)
|
|
||||||
: `${track.title} [Artist: ${track.author}]`,
|
|
||||||
value: track.title.slice(0, 100)
|
|
||||||
}));
|
|
||||||
} else {
|
|
||||||
logger.debug(`Found Genius lyrics for query '${query}'.`);
|
|
||||||
response = [
|
|
||||||
{
|
|
||||||
name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100),
|
|
||||||
value: lyricsResult.title.slice(0, 100)
|
|
||||||
}
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!response || response.length === 0) {
|
|
||||||
logger.debug(`Responding with empty results for query '${query}'`);
|
logger.debug(`Responding with empty results for query '${query}'`);
|
||||||
return interaction.respond([]);
|
return interaction.respond([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
recentQueries.set(interaction.user.id, {
|
this.updateRecentQuery(interaction.user.id, query, autocompleteChoices);
|
||||||
lastQuery: query,
|
|
||||||
result: response,
|
|
||||||
timestamp: Date.now()
|
|
||||||
});
|
|
||||||
|
|
||||||
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
|
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
|
||||||
return interaction.respond(response);
|
return interaction.respond(autocompleteChoices);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getAutocompleteChoices(
|
||||||
|
query: string,
|
||||||
|
logger: Logger
|
||||||
|
): Promise<ApplicationCommandOptionChoiceData<string>[]> {
|
||||||
|
const genius = lyricsExtractor();
|
||||||
|
const lyricsResult: LyricsData = (await genius.search(query).catch(() => null)) as LyricsData;
|
||||||
|
|
||||||
|
if (!lyricsResult) {
|
||||||
|
return this.getAutocompleteChoicesFallback(query, logger);
|
||||||
|
} else {
|
||||||
|
return this.getAutocompleteChoicesFromLyricsResult(lyricsResult);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getAutocompleteChoicesFallback(
|
||||||
|
query: string,
|
||||||
|
logger: Logger
|
||||||
|
): Promise<ApplicationCommandOptionChoiceData<string>[]> {
|
||||||
|
logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`);
|
||||||
|
|
||||||
|
const player: Player = useMainPlayer()!;
|
||||||
|
const searchResults: SearchResult = await player.search(query);
|
||||||
|
|
||||||
|
return searchResults.tracks.slice(0, 1).map((track) => ({
|
||||||
|
name: getTrackName(track),
|
||||||
|
value: track.title.slice(0, 100)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private getAutocompleteChoicesFromLyricsResult(
|
||||||
|
lyricsResult: LyricsData
|
||||||
|
): ApplicationCommandOptionChoiceData<string>[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: this.getLyricsResultName(lyricsResult),
|
||||||
|
value: lyricsResult.title.slice(0, 100)
|
||||||
|
}
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private getLyricsResultName(lyricsResult: LyricsData): string {
|
||||||
|
return `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateRecentQuery(
|
||||||
|
userId: string,
|
||||||
|
query: string,
|
||||||
|
result: ApplicationCommandOptionChoiceData<string>[]
|
||||||
|
): void {
|
||||||
|
this.recentQueries.set(userId, {
|
||||||
|
lastQuery: query,
|
||||||
|
result: result,
|
||||||
|
timestamp: Date.now()
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import { Player, SearchResult, useMainPlayer } from 'discord-player';
|
import { Player, SearchResult, useMainPlayer } from 'discord-player';
|
||||||
import { ApplicationCommandOptionChoiceData } from 'discord.js';
|
import { ApplicationCommandOptionChoiceData } from 'discord.js';
|
||||||
import { BaseAutocompleteInteraction } from '../../classes/interactions';
|
import { BaseAutocompleteInteraction } from '../../classes/interactions';
|
||||||
import { BaseAutocompleteParams, BaseAutocompleteReturnType } from '../../types/interactionTypes';
|
import { getTrackName, isQueryTooShort, shouldUseLastQuery } from '../../common/autocompleteUtils';
|
||||||
|
import { BaseAutocompleteParams, BaseAutocompleteReturnType, RecentQuery } from '../../types/interactionTypes';
|
||||||
// TODO: create type for recent query object
|
|
||||||
const recentQueries = new Map();
|
|
||||||
|
|
||||||
class PlayAutocomplete extends BaseAutocompleteInteraction {
|
class PlayAutocomplete extends BaseAutocompleteInteraction {
|
||||||
|
private recentQueries = new Map<string, RecentQuery>();
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super('play');
|
super('play');
|
||||||
}
|
}
|
||||||
@@ -15,50 +15,53 @@ class PlayAutocomplete extends BaseAutocompleteInteraction {
|
|||||||
const { executionId, interaction } = params;
|
const { executionId, interaction } = params;
|
||||||
const logger = this.getLogger(this.name, executionId, interaction);
|
const logger = this.getLogger(this.name, executionId, interaction);
|
||||||
|
|
||||||
const player: Player = useMainPlayer()!;
|
|
||||||
const query: string = interaction.options.getString('query', true);
|
const query: string = interaction.options.getString('query', true);
|
||||||
|
|
||||||
const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {};
|
const { lastQuery, result, timestamp } = this.recentQueries.get(interaction.user.id) || {};
|
||||||
|
|
||||||
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
|
if (shouldUseLastQuery(query, lastQuery, timestamp)) {
|
||||||
logger.debug(`Responding with results from lastQuery for query '${query}'`);
|
logger.debug(`Responding with results from lastQuery for query '${query}'`);
|
||||||
return interaction.respond(results);
|
return interaction.respond(result as ApplicationCommandOptionChoiceData<string | number>[]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (query.length < 3) {
|
if (isQueryTooShort(query)) {
|
||||||
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
|
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
|
||||||
return interaction.respond([]);
|
return interaction.respond([]);
|
||||||
}
|
}
|
||||||
const searchResults: SearchResult = await player.search(query);
|
|
||||||
|
|
||||||
let response: ApplicationCommandOptionChoiceData<string>[] = [];
|
const autocompleteChoices: ApplicationCommandOptionChoiceData<string>[] =
|
||||||
|
await this.getAutocompleteChoices(query);
|
||||||
|
|
||||||
response = searchResults.tracks.slice(0, 5).map((track) => {
|
if (!autocompleteChoices || autocompleteChoices.length === 0) {
|
||||||
if (track.url.length > 100) {
|
|
||||||
track.url = track.title.slice(0, 100);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
name:
|
|
||||||
`${track.title} [Author: ${track.author}]`.length > 100
|
|
||||||
? `${track.title}`.slice(0, 100)
|
|
||||||
: `${track.title} [Author: ${track.author}]`,
|
|
||||||
value: track.url
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
recentQueries.set(interaction.user.id, {
|
|
||||||
lastQuery: query,
|
|
||||||
results: response,
|
|
||||||
timestamp: Date.now()
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response || response.length === 0) {
|
|
||||||
logger.debug(`Responding with empty results for query '${query}'`);
|
logger.debug(`Responding with empty results for query '${query}'`);
|
||||||
return interaction.respond([]);
|
return interaction.respond([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.updateRecentQuery(interaction.user.id, query, autocompleteChoices);
|
||||||
|
|
||||||
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
|
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
|
||||||
return interaction.respond(response);
|
return interaction.respond(autocompleteChoices);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getAutocompleteChoices(query: string): Promise<ApplicationCommandOptionChoiceData<string>[]> {
|
||||||
|
const player: Player = useMainPlayer()!;
|
||||||
|
const searchResults: SearchResult = await player.search(query);
|
||||||
|
return searchResults.tracks.slice(0, 5).map((track) => ({
|
||||||
|
name: getTrackName(track),
|
||||||
|
value: track.url
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateRecentQuery(
|
||||||
|
userId: string,
|
||||||
|
query: string,
|
||||||
|
result: ApplicationCommandOptionChoiceData<string>[]
|
||||||
|
): void {
|
||||||
|
this.recentQueries.set(userId, {
|
||||||
|
lastQuery: query,
|
||||||
|
result: result,
|
||||||
|
timestamp: Date.now()
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Vendored
+6
@@ -59,3 +59,9 @@ export enum FilterType {
|
|||||||
Equalizer = 'equalizer',
|
Equalizer = 'equalizer',
|
||||||
Disable = 'disable'
|
Disable = 'disable'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type RecentQuery = {
|
||||||
|
lastQuery: string;
|
||||||
|
result: ApplicationCommandOptionChoiceData<string>[];
|
||||||
|
timestamp: number;
|
||||||
|
};
|
||||||
Reference in new issue
Block a user