LanguageBot Slack Bot

node v12.13.0
version: 1.0.0
endpointsharetweet
const { createServer } = require('http'); const express = require('express'); const { createEventAdapter } = require('@slack/events-api'); const got = require("got"); const quizWordPairs = [ ["enseñar", /(to\s+)?teach/i], ["trabajar", /(to\s+)?work/i], ["aprender", /(to\s+)?learn/i], ["jugar", /(to\s+)?play/i] ]; function getNextWordPair() { return quizWordPairs[Math.floor(quizWordPairs.length * Math.random())]; } var answerRegex = null; // Initialize const slackEvents = createEventAdapter(process.env.SLACK_SIGNING_SECRET); async function postSlackMessage(text, channel) { console.log(`Sending message: ${text}`); const start = Date.now(); await got(`https://slack.com/api/chat.postMessage?token=${process.env.SLACK_TOKEN}&channel=${channel}&text=${encodeURIComponent(text)}`); const duration = Date.now() - start; console.log(`Sent in ${duration}ms`); return duration; } // Create an express application const app = express(); app.get('/test', async (req, res) => { const duration = await postSlackMessage("test", "DQAA6NQGG&"); res.end(`Sent test message in ${duration}ms.`); }); // Plug the adapter in as a middleware app.use('/languagebot-events', slackEvents.requestListener()); slackEvents.on('message', async (event) => { if (!event.user) { return; } if (answerRegex) { if (answerRegex.test(event.text)) { await postSlackMessage("Correct!", event.channel); answerRegex = null; } else { await postSlackMessage("Try again!", event.channel); } } else { if (/q+u+i+z+(i+n+g+)?\s*me/i.test(event.text)) { const wordPair = getNextWordPair(); answerRegex = wordPair[1]; await postSlackMessage(`What does "${wordPair[0]}" mean in Spanish?`, event.channel); } else { await postSlackMessage("Say \"quiz me\" to get quizzed!", event.channel); } } }); const server = createServer(app); server.listen(0, async () => { console.log(`Listening for events on ${server.address().port}`); });
Loading…

no comments

    sign in to comment