Skip to content

Commit

Permalink
Add event decorator to limit duplicated code (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
ludeeus authored Oct 19, 2022
1 parent da724e0 commit 8cb5176
Show file tree
Hide file tree
Showing 7 changed files with 169 additions and 179 deletions.
2 changes: 1 addition & 1 deletion libs/sentry/src/reporting.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { ServiceError } from '@lib/common';
import { ServiceError } from '../../common/src/error';
import { ExecutionContext } from '@nestjs/common';
import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql';
import * as Sentry from '@sentry/node';
Expand Down
71 changes: 26 additions & 45 deletions services/bots/src/discord/commands/common/message.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { TransformPipe } from '@discord-nestjs/common';
import {
DiscordTransformedCommand,
On,
Param,
Payload,
TransformedCommandExecutionContext,
UsePipes,
} from '@discord-nestjs/core';
import { reportException } from '@lib/sentry/reporting';
import { AutocompleteInteraction, EmbedBuilder } from 'discord.js';
import { AutocompleteInteraction, EmbedBuilder, Events, InteractionType } from 'discord.js';
import { OptionalUserMentionDto } from '../../discord.const';
import { CommandHandler, DiscordCommandClass } from '../../discord.decorator';
import { CommandHandler, DiscordCommandClass, OnDiscordEvent } from '../../discord.decorator';
import { ServiceCommonMessageData } from '../../services/common/message-data';

class MessageDto extends OptionalUserMentionDto {
Expand Down Expand Up @@ -72,48 +70,31 @@ export class CommandCommonMessage implements DiscordTransformedCommand<MessageDt
}

// This is the autocomplete handler for the /message command
@On('interactionCreate')
@OnDiscordEvent({
event: Events.InteractionCreate,
commandName: 'message',
interactionType: InteractionType.ApplicationCommandAutocomplete,
})
async onInteractionCreate(interaction: AutocompleteInteraction): Promise<void> {
if (!interaction.isAutocomplete() || interaction.commandName !== 'message') {
return;
}
try {
await this.serviceCommonMessageData.ensureData(interaction.guildId);
const focusedValue = interaction.options.getFocused()?.toLowerCase();

if (interaction.responded) {
// this happens up upgrades when 2 bots run at the same time
return;
}
await this.serviceCommonMessageData.ensureData(interaction.guildId);
const focusedValue = interaction.options.getFocused()?.toLowerCase();

await interaction.respond(
focusedValue.length !== 0
? Object.entries(this.serviceCommonMessageData.data)
.filter(([_, data]) => data.description || data.title)
.map(([key, data]) => ({
name: data.description || data.title,
value: key,
}))
.filter(
(choice) =>
choice.value.toLowerCase().includes(focusedValue) ||
choice.name.toLowerCase().includes(focusedValue),
)
// The API only allow max 25 sugestions
.slice(0, 25)
: [],
);
} catch (err) {
reportException(err, {
cause: err,
data: {
interaction: interaction.toJSON(),
user: interaction.user.toJSON(),
channel: interaction.channel.toJSON(),
command: interaction.command.toJSON(),
},
});
await interaction.respond([]);
}
await interaction.respond(
focusedValue.length !== 0
? Object.entries(this.serviceCommonMessageData.data)
.filter(([_, data]) => data.description || data.title)
.map(([key, data]) => ({
name: data.description || data.title,
value: key,
}))
.filter(
(choice) =>
choice.value.toLowerCase().includes(focusedValue) ||
choice.name.toLowerCase().includes(focusedValue),
)
// The API only allow max 25 sugestions
.slice(0, 25)
: [],
);
}
}
69 changes: 25 additions & 44 deletions services/bots/src/discord/commands/esphome/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ import {
TransformedCommandExecutionContext,
Param,
UsePipes,
On,
} from '@discord-nestjs/core';
import { CommandHandler, DiscordCommandClass } from '../../discord.decorator';
import { AutocompleteInteraction, EmbedBuilder } from 'discord.js';
import { reportException } from '@lib/sentry/reporting';
import { CommandHandler, DiscordCommandClass, OnDiscordEvent } from '../../discord.decorator';
import { AutocompleteInteraction, EmbedBuilder, Events, InteractionType } from 'discord.js';
import {
ServiceEsphomeComponentData,
sourceWithFallback,
Expand Down Expand Up @@ -84,49 +82,32 @@ export class CommandEsphomeComponent implements DiscordTransformedCommand<Compon
}

// This is the autocomplete handler for the /component command
@On('interactionCreate')
@OnDiscordEvent({
event: Events.InteractionCreate,
commandName: 'component',
interactionType: InteractionType.ApplicationCommandAutocomplete,
})
async onInteractionCreate(interaction: AutocompleteInteraction): Promise<void> {
if (!interaction.isAutocomplete() || interaction.commandName !== 'component') {
return;
}
const channel = interaction.channel.id;

try {
await this.serviceEsphomeComponentData.ensureData(channel);
const focusedValue = interaction.options.getFocused()?.toLowerCase();
await this.serviceEsphomeComponentData.ensureData(channel);
const focusedValue = interaction.options.getFocused()?.toLowerCase();

if (interaction.responded) {
// this happens up upgrades when 2 bots run at the same time
return;
}

await interaction.respond(
focusedValue.length !== 0
? Object.entries(this.serviceEsphomeComponentData.data[sourceWithFallback(channel)])
.map(([component, data]) => ({
name: data.title,
value: component,
}))
.filter(
(choice) =>
choice.value.toLowerCase().includes(focusedValue) ||
choice.name.toLowerCase().includes(focusedValue),
)
// The API only allow max 25 sugestions
.slice(0, 25)
: [],
);
} catch (err) {
reportException(err, {
cause: err,
data: {
interaction: interaction.toJSON(),
user: interaction.user.toJSON(),
channel: interaction.channel.toJSON(),
command: interaction.command.toJSON(),
},
});
await interaction.respond([]);
}
await interaction.respond(
focusedValue.length !== 0
? Object.entries(this.serviceEsphomeComponentData.data[sourceWithFallback(channel)])
.map(([component, data]) => ({
name: data.title,
value: component,
}))
.filter(
(choice) =>
choice.value.toLowerCase().includes(focusedValue) ||
choice.name.toLowerCase().includes(focusedValue),
)
// The API only allow max 25 sugestions
.slice(0, 25)
: [],
);
}
}
69 changes: 25 additions & 44 deletions services/bots/src/discord/commands/home-assistant/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ import {
TransformedCommandExecutionContext,
Param,
UsePipes,
On,
} from '@discord-nestjs/core';
import { CommandHandler, DiscordCommandClass } from '../../discord.decorator';
import { AutocompleteInteraction, EmbedBuilder } from 'discord.js';
import { reportException } from '@lib/sentry/reporting';
import { CommandHandler, DiscordCommandClass, OnDiscordEvent } from '../../discord.decorator';
import { AutocompleteInteraction, EmbedBuilder, Events, InteractionType } from 'discord.js';
import { Emoji } from '../../discord.const';
import { ServiceHomeassistantIntegrationData } from '../../services/home-assistant/integration-data';

Expand Down Expand Up @@ -103,47 +101,30 @@ export class CommandHomeassistantIntegration implements DiscordTransformedComman
}

// This is the autocomplete handler for the /integration command
@On('interactionCreate')
@OnDiscordEvent({
event: Events.InteractionCreate,
commandName: 'integration',
interactionType: InteractionType.ApplicationCommandAutocomplete,
})
async onInteractionCreate(interaction: AutocompleteInteraction): Promise<void> {
if (!interaction.isAutocomplete() || interaction.commandName !== 'integration') {
return;
}
try {
await this.serviceHomeassistantIntegrationData.ensureData();
const focusedValue = interaction.options.getFocused()?.toLowerCase();
await this.serviceHomeassistantIntegrationData.ensureData();
const focusedValue = interaction.options.getFocused()?.toLowerCase();

if (interaction.responded) {
// this happens up upgrades when 2 bots run at the same time
return;
}

await interaction.respond(
focusedValue.length !== 0
? Object.entries(this.serviceHomeassistantIntegrationData.data)
.map(([domain, data]) => ({
name: data.title,
value: domain,
}))
.filter(
(choice) =>
choice.value.toLowerCase().includes(focusedValue) ||
choice.name.toLowerCase().includes(focusedValue),
)
// The API only allow max 25 sugestions
.slice(0, 25)
: [],
);
} catch (err) {
reportException(err, {
cause: err,
data: {
interaction: interaction.toJSON(),
user: interaction.user.toJSON(),
channel: interaction.channel.toJSON(),
command: interaction.command.toJSON(),
},
});
await interaction.respond([]);
}
await interaction.respond(
focusedValue.length !== 0
? Object.entries(this.serviceHomeassistantIntegrationData.data)
.map(([domain, data]) => ({
name: data.title,
value: domain,
}))
.filter(
(choice) =>
choice.value.toLowerCase().includes(focusedValue) ||
choice.name.toLowerCase().includes(focusedValue),
)
// The API only allow max 25 sugestions
.slice(0, 25)
: [],
);
}
}
62 changes: 22 additions & 40 deletions services/bots/src/discord/commands/home-assistant/my.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import {
TransformedCommandExecutionContext,
UsePipes,
} from '@discord-nestjs/core';
import { reportException } from '@lib/sentry/reporting';
import {
ActionRowBuilder,
AutocompleteInteraction,
EmbedBuilder,
Events,
ModalActionRowComponentBuilder,
ModalBuilder,
ModalSubmitInteraction,
Expand All @@ -23,7 +23,7 @@ import {
ServiceHomeassistantIntegrationData,
} from '../../services/home-assistant/integration-data';
import { ServiceHomeassistantMyRedirectData } from '../../services/home-assistant/my-redirect-data';
import { CommandHandler, DiscordCommandClass } from '../../discord.decorator';
import { CommandHandler, DiscordCommandClass, OnDiscordEvent } from '../../discord.decorator';

class MyDto {
@Param({
Expand Down Expand Up @@ -104,50 +104,32 @@ export class CommandHomeAssistantMy implements DiscordTransformedCommand<MyDto>
});
}

@On('interactionCreate')
@OnDiscordEvent({ event: Events.InteractionCreate })
async onInteractionCreate(
interaction: AutocompleteInteraction | ModalSubmitInteraction,
): Promise<void> {
// This is the autocomplete handler for the /my command
if (interaction.isAutocomplete() && interaction.commandName === 'my') {
try {
await this.serviceHomeassistantMyRedirectData.ensureData();
const focusedValue = interaction.options.getFocused()?.toLowerCase();
await this.serviceHomeassistantMyRedirectData.ensureData();
const focusedValue = interaction.options.getFocused()?.toLowerCase();

if (interaction.responded) {
// this happens up upgrades when 2 bots run at the same time
return;
}

await interaction.respond(
focusedValue.length !== 0
? this.serviceHomeassistantMyRedirectData.data
.filter((redirect) => !redirect.deprecated)
.map((redirect) => ({
name: redirect.name,
value: redirect.redirect,
}))
.filter(
(choice) =>
choice.value.toLowerCase().includes(focusedValue) ||
choice.name.toLowerCase().includes(focusedValue),
)
// The API only allow max 25 sugestions
.slice(0, 25)
: [],
);
} catch (err) {
reportException(err, {
cause: err,
data: {
interaction: interaction.toJSON(),
user: interaction.user.toJSON(),
channel: interaction.channel.toJSON(),
command: interaction.command.toJSON(),
},
});
await interaction.respond([]);
}
await interaction.respond(
focusedValue.length !== 0
? this.serviceHomeassistantMyRedirectData.data
.filter((redirect) => !redirect.deprecated)
.map((redirect) => ({
name: redirect.name,
value: redirect.redirect,
}))
.filter(
(choice) =>
choice.value.toLowerCase().includes(focusedValue) ||
choice.name.toLowerCase().includes(focusedValue),
)
// The API only allow max 25 sugestions
.slice(0, 25)
: [],
);
} // This is modal submition handler if the redirect supports params
else if (interaction.isModalSubmit()) {
const redirectData = await this.serviceHomeassistantMyRedirectData.getRedirect(
Expand Down
Loading

0 comments on commit 8cb5176

Please sign in to comment.