Skip to content

Commit

Permalink
Add echo bot example
Browse files Browse the repository at this point in the history
  • Loading branch information
chrispanag committed Mar 31, 2020
1 parent 2ee32a4 commit a29af32
Show file tree
Hide file tree
Showing 15 changed files with 323 additions and 2 deletions.
4 changes: 4 additions & 0 deletions examples/echo-bot/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
dist
tsconfig.tsbuildinfo
.vscode
19 changes: 19 additions & 0 deletions examples/echo-bot/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@ebenos/example-bot",
"version": "1.0.0",
"main": "./dist/server.js",
"license": "MIT",
"private": true,
"scripts": {
"start": "node ./dist/server.js",
"build": "npx tsc",
"dev": "npm run build && node ./dist/server.js",
"fb:config": "node ./dist/scripts/install.js"
},
"dependencies": {
"@types/node-fetch": "^2.5.5",
"@ebenos/framework": "*",
"@ebenos/messenger-adapter": "*",
"node-fetch": "^2.6.0"
}
}
14 changes: 14 additions & 0 deletions examples/echo-bot/src/bot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Bot } from "@ebenos/framework";
import { MessengerAdapter, MessengerUser } from "@ebenos/messenger-adapter";

import { fbConfig, mongodbUri } from "./secret";
import getStarted from "./modules/getStarted";

export const adapter = new MessengerAdapter(fbConfig);

export const bot = new Bot<MessengerUser>([adapter], {
mongodbUri
});

// This should get imported at the end
bot.addModule(getStarted);
13 changes: 13 additions & 0 deletions examples/echo-bot/src/modules/getStarted/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { bot } from '../../bot';
import { sendAPI, MessengerUser } from '@ebenos/messenger-adapter';

const { Message } = sendAPI;

export async function getStarted(user: MessengerUser) {
const now = new Date();
await bot.scenario(user)
.send(new Message({
text: `${now.toISOString()}`
}))
.end();
}
16 changes: 16 additions & 0 deletions examples/echo-bot/src/modules/getStarted/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Module } from '@ebenos/framework';
import { MessengerUser } from '@ebenos/messenger-adapter';

import * as actions from './actions';
import text from './text';
import routes from './routes';
import { preMiddlewares } from './middlewares';

const getStartedModule: Module<MessengerUser> = {
actions,
text,
routes,
preMiddlewares
};

export default getStartedModule;
9 changes: 9 additions & 0 deletions examples/echo-bot/src/modules/getStarted/middlewares.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ActionMiddleware } from '@ebenos/framework';
import { MessengerUser } from '@ebenos/messenger-adapter';

export const preMiddlewares: Array<ActionMiddleware<MessengerUser>> = [
(actionName: string, user: MessengerUser, params: any[], next) => {
console.log(`User ${user.firstName} triggered action: ${actionName} with params ${JSON.stringify(params)}`);
next();
}
];
12 changes: 12 additions & 0 deletions examples/echo-bot/src/modules/getStarted/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { bot } from "../../bot";
import { MessengerUser } from '@ebenos/messenger-adapter';

const routes = {
stringPayloads: {
getStarted: (user: MessengerUser) => bot.actions.exec('getStarted', user)
},
objectPayloads: {
}
};

export default routes;
8 changes: 8 additions & 0 deletions examples/echo-bot/src/modules/getStarted/text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { bot } from '../../bot';
import { MessengerUser } from '@ebenos/messenger-adapter';

const textRules: Array<{ regex: RegExp, action: (user: MessengerUser) => any }> = [
{ regex: /.*/, action: (user: MessengerUser) => bot.actions.exec('getStarted', user) }
];

export default textRules;
122 changes: 122 additions & 0 deletions examples/echo-bot/src/scripts/install.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
Script for installing a FB Chatbot to a page.
Assumes that all the files are in the ./config directory
Also, FB_PAGE_TOKEN, WIT_TOKEN & FB_PAGE_ID are environment variables
Sets up:
* App-to-Page Subscription -> Needs FB_PAGE_TOKEN & FB_PAGE_ID
* Messenger Profile -> Needs FB_PAGE_TOKEN & ./config/profile.json
* Wit AI Integration -> Needs FB_PAGE_TOKEN & WIT_TOKEN + NLP_ENABLED = true
If the file ./config/profile.json it skips the Messenger Profile Setup
Also if NLP_ENABLED = false then it skips the Wit.AI Integration
Written By: Christos Panagiotakopoulos
*/

const NLP_ENABLED = false;

import fetch from 'node-fetch';
import fs from 'fs';

const FB_PAGE_TOKEN = process.env.FB_PAGE_TOKEN;
if (!FB_PAGE_TOKEN) {
throw new Error('missing FB_PAGE_TOKEN');
}

const FB_PAGE_ID = process.env.FB_PAGE_ID;
if (!FB_PAGE_ID) {
throw new Error('missing FB_PAGE_ID');
}

const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN);

const promises = [];

try {
// Read Messenger Profile File
const body = fs.readFileSync('./config/profile.json');
console.log("Setting up Messenger Profile...");
// Send Request to Facebook
const profilePromise = fetch(`https://graph.facebook.com/v2.11/me/messenger_profile?${qs}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body
})
.then((rsp) => rsp.json())
.then((json) => {
// Handle Errors sent from Facebook
if (json.error) {
console.error(`Error on Messenger Profile Setup:`);
console.error(json.error);
} else {
console.log("\t\tMessenger Profile Setup: Success! :)");
}
})
.catch((err) => {
// Handle Errors on the request itself
console.error(`Error on Messenger Profile Setup: ${err}`);
});
promises.push(profilePromise);
} catch (err) {
// Handle Errors on the reading of the file
if (err.code === 'ENOENT') {
console.log("profile.json not found | Skipping Messenger Profile Setup...");
} else {
throw new Error("Error reading profile.json");
}
}

const subscribePromise = fetch(`https://graph.facebook.com/v2.6/${FB_PAGE_ID}/subscribed_apps?${qs}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
.then((rsp) => rsp.json())
.then((json) => {
if (json.success) {
console.log(`Subscribed App to the page with page_id: ${FB_PAGE_ID}`);
} else {
console.error(`Error subscribing the bot to the page with id: ${FB_PAGE_ID}`);
console.error(json.error);
}
})
.catch((err) => {
throw new Error(err);
});
promises.push(subscribePromise);

if (NLP_ENABLED) {
const WIT_TOKEN = process.env.WIT_TOKEN;
if (!WIT_TOKEN) {
throw new Error('missing WIT_TOKEN');
}

const nlpPromise = fetch(`https://graph.facebook.com/v2.11/me/nlp_configs?nlp_enabled=${NLP_ENABLED}&custom_token=${WIT_TOKEN}&${qs}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
})
.then((rsp) => rsp.json())
.then((json) => {
if (json.success) {
console.log(`Connected app with Wit.AI successfully`);
} else {
console.error(`Error connecting the app to Wit.AI`);
console.error(json.error);
}
})
.catch((err) => {
throw new Error(err);
});

promises.push(nlpPromise);
}

// Wait for all the promises to resolve (for all the jobs to end) and then exit gracefully
Promise.all(promises).then(() => {
console.log("The bot has been installed successfully");
process.exit(0);
})
.catch(() => {
console.error("There were errors in the installation of the bot");
process.exit(1);
});
28 changes: 28 additions & 0 deletions examples/echo-bot/src/secret.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const FB_PAGE_ID = process.env.FB_PAGE_ID;
if (!FB_PAGE_ID) {
throw new Error("Missing env: No FB_PAGE_ID");
}

const FB_PAGE_TOKEN = process.env.FB_PAGE_TOKEN;
if (!FB_PAGE_TOKEN) {
throw new Error("Missing env: No FB_PAGE_TOKEN");
}

const FB_APP_SECRET = process.env.FB_APP_SECRET;
if (!FB_APP_SECRET) {
throw new Error("Missing env: No FB_APP_SECRET");
}

export const fbConfig = {
pageId: FB_PAGE_ID,
pageToken: FB_PAGE_TOKEN,
appSecret: FB_APP_SECRET,
webhookKey: "123"
};

const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
throw new Error("Missing env: No MONGODB_URI");
}

export const mongodbUri = MONGODB_URI;
5 changes: 5 additions & 0 deletions examples/echo-bot/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { bot } from './bot';

bot.start({
port: (process.env.PORT as any) || 3000
});
69 changes: 69 additions & 0 deletions examples/echo-bot/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
"declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
"strictNullChecks": true /* Enable strict null checks. */,
"strictFunctionTypes": true /* Enable strict checking of function types. */,
"strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,
"strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */,
"noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
"alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,

/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"baseUrl": "./dist" /* Base directory to resolve non-absolute module names. */,
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
"rootDirs": [
"./src/"
] /* List of root folders whose combined content represents the structure of the project at runtime. */,
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": ["./src/**/*"]
}
1 change: 1 addition & 0 deletions lerna.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"npmClient": "yarn",
"packages": [
"examples/*",
"packages/*"
],
"version": "3.2.1",
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"license": "MIT",
"private": true,
"workspaces": [
"packages/*"
"packages/*",
"examples/*"
],
"scripts": {
},
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1076,7 +1076,7 @@
"@types/mongodb" "*"
"@types/node" "*"

"@types/node-fetch@^2.1.6", "@types/node-fetch@^2.3.2":
"@types/node-fetch@^2.1.6", "@types/node-fetch@^2.3.2", "@types/node-fetch@^2.5.5":
version "2.5.5"
resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.5.5.tgz#cd264e20a81f4600a6c52864d38e7fef72485e92"
integrity sha512-IWwjsyYjGw+em3xTvWVQi5MgYKbRs0du57klfTaZkv/B24AEQ/p/IopNeqIYNy3EsfHOpg8ieQSDomPcsYMHpA==
Expand Down

0 comments on commit a29af32

Please sign in to comment.