diff --git a/changelog.d/143.feature b/changelog.d/143.feature new file mode 100644 index 00000000..39d79710 --- /dev/null +++ b/changelog.d/143.feature @@ -0,0 +1 @@ +Bot command help text now features category headers, and disabled commands are no longer visible. \ No newline at end of file diff --git a/src/AdminRoom.ts b/src/AdminRoom.ts index 6cf08057..4b46663b 100644 --- a/src/AdminRoom.ts +++ b/src/AdminRoom.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ import "reflect-metadata"; import { AdminAccountData, AdminRoomCommandHandler } from "./AdminRoomCommandHandler"; -import { botCommand, compileBotCommands, handleCommand, BotCommands } from "./BotCommands"; +import { botCommand, compileBotCommands, handleCommand, BotCommands, HelpFunction } from "./BotCommands"; import { BridgeConfig } from "./Config/Config"; import { BridgeRoomState, BridgeRoomStateGitHub } from "./Widgets/BridgeWidgetInterface"; import { Endpoints } from "@octokit/types"; @@ -12,7 +12,6 @@ import { GithubGraphQLClient } from "./Github/GithubInstance"; import { GitLabClient } from "./Gitlab/Client"; import { Intent } from "matrix-bot-sdk"; import { JiraBotCommands } from "./Jira/AdminCommands"; -import { MatrixMessageContent } from "./MatrixEvent"; import { NotifFilter, NotificationFilterStateContent } from "./NotificationFilters"; import { ProjectsListResponseData } from "./Github/Types"; import { UserTokenStore } from "./UserTokenStore"; @@ -34,7 +33,7 @@ export const BRIDGE_ROOM_TYPE = "uk.half-shot.matrix-hookshot.github.room"; export const BRIDGE_NOTIF_TYPE = "uk.half-shot.matrix-hookshot.github.notif_state"; export const BRIDGE_GITLAB_NOTIF_TYPE = "uk.half-shot.matrix-hookshot.gitlab.notif_state"; export class AdminRoom extends AdminRoomCommandHandler { - public static helpMessage: () => MatrixMessageContent; + public static helpMessage: HelpFunction; protected widgetAccessToken = `abcdef`; static botCommands: BotCommands; @@ -132,10 +131,15 @@ export class AdminRoom extends AdminRoomCommandHandler { @botCommand("help", "This help text") public async helpCommand() { - return this.botIntent.sendEvent(this.roomId, AdminRoom.helpMessage()); + const enabledCategories = [ + this.config.github ? "github" : "", + this.config.gitlab ? "gitlab" : "", + this.config.jira ? "jira" : "", + ]; + return this.botIntent.sendEvent(this.roomId, AdminRoom.helpMessage(undefined, enabledCategories)); } - @botCommand("github notifications toggle", "Toggle enabling/disabling GitHub notifications in this room") + @botCommand("github notifications toggle", { help: "Toggle enabling/disabling GitHub notifications in this room", category: "github"}) public async setGitHubNotificationsStateToggle() { const newData = await this.saveAccountData((data) => { return { @@ -151,7 +155,7 @@ export class AdminRoom extends AdminRoomCommandHandler { await this.sendNotice(`${newData.github?.notifications?.enabled ? "En" : "Dis"}abled GitHub notifcations`); } - @botCommand("github notifications filter participating", "Toggle enabling/disabling GitHub notifications in this room") + @botCommand("github notifications filter participating", {help: "Toggle enabling/disabling GitHub notifications in this room", category: "github"}) // @ts-ignore - property is used private async setGitHubNotificationsStateParticipating() { const newData = await this.saveAccountData((data) => { @@ -175,9 +179,8 @@ export class AdminRoom extends AdminRoomCommandHandler { return this.sendNotice(`Showing all events`); } - @botCommand("github notifications", "Show the current notification settings") - // @ts-ignore - property is used - private async getGitHubNotificationsState() { + @botCommand("github notifications", {help: "Show the current notification settings", category: "github"}) + public async getGitHubNotificationsState() { if (!this.notificationsEnabled("github")) { return this.sendNotice(`Notifications are disabled`); } @@ -185,7 +188,7 @@ export class AdminRoom extends AdminRoomCommandHandler { } - @botCommand("github project list-for-user", "List GitHub projects for a user", [], ['user', 'repo']) + @botCommand("github project list-for-user", {help: "List GitHub projects for a user", optionalArgs:['user', 'repo'], category: "github"}) // @ts-ignore - property is used private async listProjects(username?: string, repo?: string) { if (!this.config.github) { @@ -227,7 +230,7 @@ export class AdminRoom extends AdminRoomCommandHandler { }); } - @botCommand("github project list-for-org", "List GitHub projects for an org", ['org'], ['repo']) + @botCommand("github project list-for-org", {help: "List GitHub projects for an org", requiredArgs: ['org'], optionalArgs: ['repo'], category: "github"}) // @ts-ignore - property is used private async listProjects(org: string, repo?: string) { if (!this.config.github) { @@ -266,7 +269,7 @@ export class AdminRoom extends AdminRoomCommandHandler { }); } - @botCommand("github project open", "Open a GitHub project as a room", ['projectId']) + @botCommand("github project open", {help: "Open a GitHub project as a room", requiredArgs: ['projectId'], category: "github"}) // @ts-ignore - property is used private async openProject(projectId: string) { if (!this.config.github) { @@ -291,7 +294,7 @@ export class AdminRoom extends AdminRoomCommandHandler { } } - @botCommand("github discussion open", "Open a discussion room", ['owner', 'repo', 'number']) + @botCommand("github discussion open", {help: "Open a discussion room", requiredArgs: ['owner', 'repo', 'number'], category: "github"}) // @ts-ignore - property is used private async listDiscussions(owner: string, repo: string, numberStr: string) { const number = parseInt(numberStr); @@ -318,7 +321,7 @@ export class AdminRoom extends AdminRoomCommandHandler { /* GitLab commands */ - @botCommand("gitlab open issue", "Open or join a issue room for GitLab", ['url']) + @botCommand("gitlab open issue", {help: "Open or join a issue room for GitLab", requiredArgs: ['url'], category: "gitlab"}) // @ts-ignore - property is used private async gitLabOpenIssue(url: string) { if (!this.config.gitlab) { @@ -344,7 +347,7 @@ export class AdminRoom extends AdminRoomCommandHandler { this.emit('open.gitlab-issue', getIssueOpts, issue, instanceName, instance); } - @botCommand("gitlab personaltoken", "Set your personal access token for GitLab", ['instanceName', 'accessToken']) + @botCommand("gitlab personaltoken", {help: "Set your personal access token for GitLab", requiredArgs: ['instanceName', 'accessToken'], category: "gitlab"}) public async setGitLabPersonalAccessToken(instanceName: string, accessToken: string) { let me: GetUserResponse; if (!this.config.gitlab) { @@ -366,7 +369,7 @@ export class AdminRoom extends AdminRoomCommandHandler { return this.tokenStore.storeUserToken("gitlab", this.userId, accessToken, instance.url); } - @botCommand("gitlab hastoken", "Check if you have a token stored for GitLab", ["instanceName"]) + @botCommand("gitlab hastoken", {help: "Check if you have a token stored for GitLab", requiredArgs: ["instanceName"], category: "gitlab"}) public async gitlabHasPersonalToken(instanceName: string) { if (!this.config.gitlab) { return this.sendNotice("The bridge is not configured with GitLab support"); @@ -382,7 +385,7 @@ export class AdminRoom extends AdminRoomCommandHandler { return this.sendNotice("A token is stored for your GitLab account."); } - @botCommand("gitlab notifications toggle", "Toggle enabling/disabling GitHub notifications in this room", ["instanceName"]) + @botCommand("gitlab notifications toggle", {help: "Toggle enabling/disabling GitHub notifications in this room", optionalArgs: ["instanceName"], category: "gitlab"}) public async setGitLabNotificationsStateToggle(instanceName: string) { if (!this.config.gitlab) { return this.sendNotice("The bridge is not configured with GitLab support"); diff --git a/src/BotCommands.ts b/src/BotCommands.ts index ef27490a..e5388ecc 100644 --- a/src/BotCommands.ts +++ b/src/BotCommands.ts @@ -7,52 +7,79 @@ import { MatrixMessageContent } from "./MatrixEvent"; const md = new markdown(); export const botCommandSymbol = Symbol("botCommandMetadata"); -export function botCommand(prefix: string, help: string, requiredArgs: string[] = [], optionalArgs: string[] = [], includeUserId = false) { +export function botCommand(prefix: string, helpOrOpts: string|BotCommandOptions, requiredArgs: string[] = [], optionalArgs: string[] = [], includeUserId = false) { + if (typeof helpOrOpts === "string") { + return Reflect.metadata(botCommandSymbol, { + prefix, + help: helpOrOpts, + requiredArgs, + optionalArgs, + includeUserId, + }); + } return Reflect.metadata(botCommandSymbol, { prefix, - help, - requiredArgs, - optionalArgs, - includeUserId, + ...helpOrOpts }); } +export interface BotCommandOptions { + help: string, + requiredArgs?: string[], + optionalArgs?: string[], + includeUserId?: boolean, + category?: string, +} + + type BotCommandResult = {status?: boolean, reaction?: string}|undefined; type BotCommandFunction = (...args: string[]) => Promise; -export type BotCommands = {[prefix: string]: { - fn: BotCommandFunction, - requiredArgs: string[], - optionalArgs: string[], - includeUserId: boolean, -}}; +export type BotCommands = {[prefix: string]: {fn: BotCommandFunction} & BotCommandOptions}; +export type HelpFunction = (cmdPrefix?: string, categories?: string[]) => MatrixMessageContent -export function compileBotCommands(...prototypes: Record[]): {helpMessage: (cmdPrefix?: string) => MatrixMessageContent, botCommands: BotCommands} { - let content = "Commands:\n"; +export function compileBotCommands(...prototypes: Record[]): {helpMessage: HelpFunction, botCommands: BotCommands} { const botCommands: BotCommands = {}; + const cmdStrs: {[category: string]: string[]} = {}; prototypes.forEach(prototype => { Object.getOwnPropertyNames(prototype).forEach(propetyKey => { const b = Reflect.getMetadata(botCommandSymbol, prototype, propetyKey); if (b) { - const requiredArgs = b.requiredArgs.join(" "); - const optionalArgs = b.optionalArgs.map((arg: string) => `[${arg}]`).join(" "); - content += ` - \`££PREFIX££${b.prefix}\` ${requiredArgs} ${optionalArgs} - ${b.help}\n`; - // We know that this is safe. + const category = b.category || "default"; + const requiredArgs = b.requiredArgs?.join(" ") || ""; + const optionalArgs = b.optionalArgs?.map((arg: string) => `[${arg}]`).join(" ") || ""; + cmdStrs[category] = cmdStrs[category] || [] + cmdStrs[category].push(` - \`££PREFIX££${b.prefix}\` ${requiredArgs} ${optionalArgs} - ${b.help}`); + // We know that these types are safe. botCommands[b.prefix as string] = { fn: prototype[propetyKey], + help: b.help, requiredArgs: b.requiredArgs, optionalArgs: b.optionalArgs, includeUserId: b.includeUserId, + category: b.category, }; } }); }) return { - helpMessage: (cmdPrefix?: string) => ({ - msgtype: "m.notice", - body: content, - formatted_body: md.render(content).replace(/££PREFIX££/g, cmdPrefix || ""), - format: "org.matrix.custom.html" - }), + helpMessage: (cmdPrefix?: string, onlyCategories?: string[]) => { + let content = ""; + for (const [categoryName, commands] of Object.entries(cmdStrs)) { + if (categoryName !== "default" && onlyCategories && !onlyCategories.includes(categoryName)) { + continue; + } + if (categoryName !== "default") { + content += `### ${categoryName[0].toUpperCase()}${categoryName.substring(1).toLowerCase()}\n`; + } + content += commands.join('\n') + "\n"; + } + return { + msgtype: "m.notice", + body: content.replace(/££PREFIX££/g, cmdPrefix || ""), + formatted_body: md.render(content).replace(/££PREFIX££/g, cmdPrefix || ""), + format: "org.matrix.custom.html" + } + }, botCommands, } } @@ -71,7 +98,7 @@ export async function handleCommand(userId: string, command: string, botCommands // We have a match! const command = botCommands[prefix]; if (command) { - if (command.requiredArgs.length > parts.length - i) { + if (command.requiredArgs && command.requiredArgs.length > parts.length - i) { return {handled: true, error: "Missing args"}; } const args = parts.slice(i); diff --git a/src/Github/AdminCommands.ts b/src/Github/AdminCommands.ts index c8c92eb3..3a581a4f 100644 --- a/src/Github/AdminCommands.ts +++ b/src/Github/AdminCommands.ts @@ -20,7 +20,7 @@ export function generateGitHubOAuthUrl(clientId: string, redirectUri: string, st } export class GitHubBotCommands extends AdminRoomCommandHandler { - @botCommand("github login", "Login to GitHub") + @botCommand("github login", {help: "Login to GitHub", category: "github"}) public async loginCommand() { if (!this.config.github) { throw new CommandError("no-github-support", "The bridge is not configured with GitHub support"); @@ -32,13 +32,13 @@ export class GitHubBotCommands extends AdminRoomCommandHandler { return this.sendNotice(`To login, open ${generateGitHubOAuthUrl(this.config.github.oauth.client_id, this.config.github.oauth.redirect_uri, state)} to link your account to the bridge`); } - @botCommand("github startoauth", "Start the OAuth process with GitHub") + @botCommand("github startoauth", {help: "Start the OAuth process with GitHub", category: "github"}) public async beginOAuth() { // Legacy command return this.loginCommand(); } - @botCommand("github setpersonaltoken", "Set your personal access token for GitHub", ['accessToken']) + @botCommand("github setpersonaltoken", {help: "Set your personal access token for GitHub", requiredArgs: ['accessToken'], category: "github"}) public async setGHPersonalAccessToken(accessToken: string) { if (!this.config.github) { throw new CommandError("no-github-support", "The bridge is not configured with GitHub support"); @@ -56,7 +56,7 @@ export class GitHubBotCommands extends AdminRoomCommandHandler { await this.tokenStore.storeUserToken("github", this.userId, JSON.stringify({access_token: accessToken, token_type: 'pat'} as GitHubOAuthToken)); } - @botCommand("github hastoken", "Check if you have a token stored for GitHub") + @botCommand("github hastoken", {help: "Check if you have a token stored for GitHub", category: "github"}) public async hasPersonalToken() { if (!this.config.github) { throw new CommandError("no-github-support", "The bridge is not configured with GitHub support"); diff --git a/src/Jira/AdminCommands.ts b/src/Jira/AdminCommands.ts index e9c07f84..7b63e317 100644 --- a/src/Jira/AdminCommands.ts +++ b/src/Jira/AdminCommands.ts @@ -33,7 +33,7 @@ export function generateJiraURL(clientId: string, redirectUri: string, state: st } export class JiraBotCommands extends AdminRoomCommandHandler { - @botCommand("jira login", "Login to JIRA") + @botCommand("jira login", {help: "Login to JIRA", category: "jira"}) public async loginCommand() { if (!this.config.jira?.oauth) { this.sendNotice(`Bot is not configured with JIRA OAuth support`); @@ -44,7 +44,7 @@ export class JiraBotCommands extends AdminRoomCommandHandler { await this.sendNotice(`To login, open ${generateJiraURL(cfg.client_id, cfg.redirect_uri, state)} to link your account to the bridge`); } - @botCommand("jira whoami", "Determine JIRA identity") + @botCommand("jira whoami", {help: "Determine JIRA identity", category: "jira"}) public async whoami() { if (!this.config.jira) { await this.sendNotice(`Bot is not configured with JIRA OAuth support`); diff --git a/tests/AdminRoomTest.ts b/tests/AdminRoomTest.ts index d6dcd7f3..87c9ad57 100644 --- a/tests/AdminRoomTest.ts +++ b/tests/AdminRoomTest.ts @@ -14,7 +14,7 @@ function createAdminRoom(data: any = {admin_user: "@admin:bar"}): [AdminRoom, In data.admin_user = "@admin:bar"; } const tokenStore = new UserTokenStore("notapath", intent, DefaultConfig); - return [new AdminRoom(ROOM_ID, data, NotifFilter.getDefaultContent(), intent, tokenStore, {} as any, ), intent]; + return [new AdminRoom(ROOM_ID, data, NotifFilter.getDefaultContent(), intent, tokenStore, DefaultConfig), intent]; } describe("AdminRoom", () => { @@ -22,10 +22,9 @@ describe("AdminRoom", () => { const [adminRoom, intent] = createAdminRoom(); await adminRoom.handleCommand("$foo:bar", "help"); expect(intent.sentEvents).to.have.lengthOf(1); - expect(intent.sentEvents[0]).to.deep.equal({ roomId: ROOM_ID, - content: AdminRoom.helpMessage(), + content: AdminRoom.helpMessage(undefined, ["github", "gitlab", "jira"]), }); }); }) \ No newline at end of file