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

Plugins v2 #49

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ node_modules
# config file
config.yml

#plugins data directory
data/

# IDE config
.idea/

Expand Down
11 changes: 9 additions & 2 deletions src/plugins/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ import { omit } from "ramda";
import commandParser from "../commandParser";
import eventTypes from "../eventTypes";

const getFormattedConfig = (config) => {
const sanitizedConfig = omit(
["apiToken", "signingSecret", "appToken", "botToken"],
config
);
return JSON.stringify(sanitizedConfig, null, 4);
};

export default (config, emitter, log) => {
const processMessage = async (message) => {
const command = commandParser(message.text);
Expand All @@ -19,10 +27,9 @@ export default (config, emitter, log) => {
process.exit();
break;
case "config":
const txt = JSON.stringify(omit(["apiToken"], config), null, 4);
emitter.emit(
eventTypes.OUT.sendMessage,
"```" + txt + "```",
"```" + getFormattedConfig(config) + "```",
message.channel
);
}
Expand Down
43 changes: 43 additions & 0 deletions src/plugins/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import createDebug from "debug";
import adminPlugin from "./admin";

export const initPlugins = async (config, emitter, app) => {
const log = createDebug("taperbot:core:plugins");
const pluginsFolder = "./";

const plugins = Object.keys(config.plugins).map((pluginName) => {
log(`Iniciando plugin ${pluginName}`);
const pluginConfig = config.plugins[pluginName];
try {
// eslint-disable-next-line no-constant-condition
if (!pluginConfig.v2) {
//V1
return require(`${pluginsFolder}${pluginName}`).default(
pluginConfig,
emitter,
createDebug(`taperbot:${pluginName}`)
);
} else {
// V2
log(`${pluginName} esta en la nueva version 🚀`);
const plugin = require(`${pluginsFolder}v2/${pluginName}`).default({
app,
config: pluginConfig,
log: createDebug(`taperbot:${pluginName}`),
});

plugin.commands.forEach((cm) => {
app.command(cm.command, cm.action);
});
}
} catch (error) {
log(`Error inicializando plugin ${pluginName}`);
}
});

await Promise.all(plugins);

return plugins.concat([
adminPlugin(config, emitter, createDebug("taperbot:admin")),
]);
};
16 changes: 16 additions & 0 deletions src/plugins/v2/echo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { directMention } from "@slack/bolt";
export const help = "";

export const commands = [
{
command: "/echo",
description: "devuelve lo que le mandes",
},
];

export default ({ app, config, log }) => {
app.message(directMention(), "/echo", async ({ message, say }) => {
log(message);
await say(`${message.text}`);
});
};
53 changes: 53 additions & 0 deletions src/plugins/v2/soto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import fs from "fs/promises";
import { directMention } from "@slack/bolt";
import dayjs from "dayjs";
import "dayjs/locale/es";
import "dayjs/plugin/relativeTime";
import commandParser from "../../commandParser";

const sotoFile = "data/soto.json";
let lastSotos = [];
export default async ({ app, log }) => {
try {
lastSotos = JSON.parse(await fs.readFile(sotoFile));
} catch (error) {
log("Error cargando el archivo de last sotos");
}

app.message(directMention(), "soto?", async ({ message, say }) => {
log(message);
const { text } = commandParser(message.text);
const lastSoto = lastSotos[lastSotos.length];
lastSotos.push({ date: dayjs().format(), text });
fs.writeFile(sotoFile, JSON.stringify(lastSotos));
if (lastSoto) {
await say(`Days since last Soto: ~${lastSoto.date}~ 0`);
}
});

return {
commands: [
{
command: "/soto",
description: "Days since last soto",
action: async ({ ack, respond }) => {
log("SOTO");
// Acknowledge command request
await ack();

await respond(`Soto!`);
},
},
],
help: "le decis que viste a un soto y registra la cantidad de dias desde el ultimo avistaje de un soto",
homePage: () => ({
type: "section",
text: {
type: "mrkdwn",
text: lastSotos
.map((soto) => `- ${dayjs(soto.date).fromNow()}: ${soto.text}`)
.join("\n"),
},
}),
};
};
25 changes: 7 additions & 18 deletions src/run.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,27 @@
const { App } = require("@slack/bolt");
import { EventEmitter } from "events";
import createDebug from "debug";

import { getConfig } from "./config";
import {
getNextId,
isFromChannels,
shouldProcess,
isFromUser,
} from "./messageUtil";
import adminPlugin from "./plugins/admin";

import { initPlugins } from "./plugins";
import eventTypes from "./eventTypes";
import { getFromAPI, postToAPI } from "./slackWeb";

const initPlugins = (config, emitter) => {
const pluginsFolder = "./plugins/";

return Object.keys(config.plugins)
.map((pluginName) => {
log(`Iniciando plugin ${pluginName}`);
const pluginConfig = config.plugins[pluginName];
return require(`${pluginsFolder}${pluginName}`).default(
pluginConfig,
emitter,
createDebug(`taperbot:${pluginName}`)
);
})
.concat([adminPlugin(config, emitter, createDebug("taperbot:admin"))]);
};

const log = createDebug("taperbot:core");
const devLog = createDebug("taperbot:core:dev");

const config = getConfig();

log("initing with config:");
log(config);

const app = new App({
token: config.botToken,
signingSecret: config.signingSecret,
Expand Down Expand Up @@ -66,7 +55,7 @@ app.event("reaction_removed", async ({ event, logger }) => {
}
});

initPlugins(config, emitter);
initPlugins(config, emitter, app);

const startServer = async () => {
await app.start(process.env.PORT || 3000);
Expand Down
File renamed without changes.