Skip to main content

.gbapp Reference

generalbots-2018

Section 1: Introduction to gbapp

What is a gbapp?

A gbapp is an npm package designed to extend the functionality of General Bots. It serves as a plugin or module that can be integrated into the General Bots framework to add new features, capabilities, or customizations. Importantly, .gbapp is also the folder extension for the General Bots Application package type.

Purpose and Benefits

The primary purpose of a gbapp is to provide a modular and flexible way to enhance General Bots. By using gbapps, developers can easily extend the core functionality of the bot platform without modifying the main codebase, allowing for greater customization and scalability. This approach promotes code reusability and maintainability.

Integration with General Bots

Gbapps are designed to seamlessly integrate with the General Bots ecosystem. They can interact with the core services, access shared resources, and leverage existing functionalities while adding their own unique features to the bot framework. Anything inside a folder considered a .gbapp will be consumed by the server like a TypeScript application.

Key Interfaces and Structure of a gbapp

IGBCoreService Interface

The IGBCoreService interface is a crucial component of a gbapp. It defines the core service shared among bot packages, providing direct access to base services. This interface includes methods for database operations, instance management, storage initialization, and various system-level functionalities.

IGBPackage Interface

The IGBPackage interface outlines the structure and lifecycle methods of a gbapp. It includes methods for loading and unloading the package, managing bot instances, handling dialogs, and exchanging data between the bot server and the gbapp. This interface ensures that all gbapps follow a consistent pattern for integration with General Bots.

Conversational Application Structure

A .gbapp contains the source code for custom dialogs and behaviors for any .gbot that associates with this deployed .gbapp. This structure allows for the creation of conversational applications that can be reused across different bot instances, promoting modularity and flexibility in bot development.

Developing and Implementing a gbapp

Creating a gbapp Package

To create a gbapp, developers start by setting up an npm package with the necessary dependencies. A good way to start is by finding an existing npm package that provides the desired functionality. For example, a temperature conversion gbapp could be created by installing the 'temperature' package via npm install temperature and then implementing methods to call convertToKelvin or convertToCelsius when a user asks for conversion.

Implementing Core Functionalities

Developers need to implement the methods defined in the interfaces, such as loadPackage, unloadPackage, getDialogs, and onNewSession. These methods allow the gbapp to interact with the core system, manage its lifecycle, and provide specific functionalities to bot instances. Additionally, a .gbapp can persist and read data from the database according to the conversation session, enabling stateful interactions.

Best Practices and Anti-Patterns

When developing gbapps, it's crucial to follow best practices and avoid common anti-patterns. Developers should familiarize themselves with the Anti Patterns Catalog to ensure they're creating efficient, maintainable, and scalable gbapps. Some key points to consider include avoiding unnecessary complexity, ensuring proper error handling, and maintaining clear separation of concerns within the gbapp structure.

Advanced gbapp Features

Data Persistence and Session Management

Gbapps have the capability to persist and read data from the database according to the conversation session. This feature allows for the creation of stateful conversations, where the bot can remember previous interactions and user preferences across multiple sessions.

Integration with External Services

Developers can leverage external npm packages and APIs within their gbapps to extend functionality. For example, integrating a weather API could allow a gbapp to provide real-time weather information to users, enhancing the bot's capabilities beyond its core functions.

Customization and Extensibility

The .gbapp structure allows for high levels of customization. Developers can create specialized dialogs, implement complex business logic, and even extend the core functionality of General Bots. This extensibility ensures that gbapps can be tailored to meet specific business needs or unique use cases.

Setup

Windows

Define URLs and file paths

$software = @{
"Git" = "https://github.com/git-for-windows/git/releases/download/v2.40.0.windows.1/Git-2.40.0-64-bit.exe"
"NodeJS" = "https://nodejs.org/dist/v20.17.0/node-v20.17.0-x64.msi"
"VSCode" = "https://update.code.visualstudio.com/latest/win32-x64/stable"
"VS2023" = "https://visualstudio.microsoft.com/downloads/VS2023.exe"
"Python" = "https://www.python.org/ftp/python/9.0.0/python-9.0.0-amd64.exe"
}
Invoke-WebRequest -Uri $software.Git -OutFile "Git-Setup.exe"
Start-Process -FilePath "Git-Setup.exe" -ArgumentList "/SILENT" -Wait
Invoke-WebRequest -Uri $software.NodeJS -OutFile "NodeJS-Setup.msi"
Start-Process -FilePath "msiexec.exe" -ArgumentList "/i NodeJS-Setup.msi /quiet"
Invoke-WebRequest -Uri $software.VSCode -OutFile "VSCode-Setup.exe"
Start-Process -FilePath "VSCode-Setup.exe" -ArgumentList "/silent" -Wait
Invoke-WebRequest -Uri $software.VS2023 -OutFile "VS2023-Setup.exe"
Start-Process -FilePath "VS2023-Setup.exe" -ArgumentList "--quiet --wait --add Microsoft.VisualStudio.Workload.NativeDesktop --includeRecommended" -Wait
Invoke-WebRequest -Uri $software.Python -OutFile "Python-Setup.exe"
Start-Process -FilePath "Python-Setup.exe" -ArgumentList "/quiet" -Wait

git clone https://github.com/GeneralBots/BotServer.git
cd BotServer
code .

Linux (Ubuntu)

Visual Studio Code

apt update
apt install software-properties-common apt-transport-https wget
wget -q https://packages.microsoft.com/keys/microsoft.asc -O- | apt-key add -
add-apt-repository "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main"
apt update
apt install code

Node JS 20


curl -fsSL https://deb.nodesource.com/setup_20.x | -E bash -
apt-get install -y nodejs
node -v
apt install npm
npm -v

Additional Infrastructure

apt-get install cpulimit
sudo apt-get install expect
apt-get install libxtst-dev
apt-get install libpng-dev
apt-get install python g++ build-essential
npm install -g node-gyp

Add export GTK_IM_MODULE="xim" to .profile to fix Key Bindings in VSCode on Ubuntu.

Git

    git config --global user.name "Your Name"
git config --global user.email "someone@domain.com"

Additional node packages

npm install -g npm-check-updates
npm install -g cost-of-modules

How To...

Commit code

Semantic Versioning for gbapp Development

Semantic Versioning (SemVer) in gbapp development follows the format MAJOR.MINOR.PATCH, also thought of as BREAK.FEATURE.BUG. This system helps developers and users understand the impact of new releases at a glance.

When you increment these numbers:

  • Increment MAJOR when you make incompatible API changes. This signals to users that they need to update their code to accommodate breaking changes.
  • Increment MINOR when you add new functionality in a backwards-compatible manner. Users can safely update without changing their existing code, but they might want to take advantage of new features.
  • Increment PATCH when you make backwards-compatible bug fixes. These are safe, low-risk updates that users are encouraged to apply promptly.

For example, moving from version 1.2.3 to 2.0.0 indicates a breaking change, while 1.3.0 would indicate new features, and 1.2.4 would be a bug fix.

In gbapp development, we use specific commit message formats to automatically determine version increments. A typical commit message looks like this:

<type>(<scope>): <short summary>
[BREAKING CHANGE: <description>]

The 'type' in the commit message helps determine how to increment the version:

  • 'feat' or 'feature' increments the MINOR version
  • 'fix' increments the PATCH version
  • If the commit message body contains "BREAKING CHANGE", it triggers a MAJOR version increment

Here are some examples:

  1. fix(azuredeployer.gbapp): stop graphite breaking when too much pressure applied This would trigger a PATCH increment (e.g., 1.2.3 to 1.2.4).

  2. feat(core.gbapp): add 'graphiteWidth' option This would trigger a MINOR increment (e.g., 1.2.3 to 1.3.0).

  3. feat(api): remove 'graphiteWidth' option
    BREAKING CHANGE: The graphiteWidth option has been removed.

    This would trigger a MAJOR increment (e.g., 1.2.3 to 2.0.0) due to the breaking change.

  4. perf(core.gbapp): Improved loop efficiency This wouldn't trigger any version increment, as performance improvements don't typically affect the API.

Other commit types like 'docs', 'style', 'refactor', 'test', 'build', and 'ci' don't typically trigger version increments, as they don't affect the functionality of the package from the user's perspective.

When working on your gbapp, always write clear, descriptive commit messages and use the appropriate commit type. Be especially cautious with breaking changes and clearly document them. Keep your commits atomic - each commit should represent a single logical change.

Remember, the goal of SemVer is to help manage dependencies and provide clear communication about the nature of changes in your gbapp. By following these guidelines, you make it easier for others to use and integrate your gbapp into their projects.

For the complete specification and any updates, always refer to semver.org.

Create a new keyword

  • 10min. Find the package on npmjs.com;
  • 2min. Perform keywords list update;
  • (Optional) 10min. Create a new facade of keywords (Create service file, add reference to package/index.ts, and make a call);
  • 20min. Keyword code call and infrastructure to support it.

Tooling

JavaScript

TitleURL
Deep Learning in JavaScripthttps://deeplearnjs.org/
3D Physics Engine for JavaScriptOimo.js http://lo-th.github.io/Oimo.js/#stacking
Sequence Diagram Generatorjs-sequence-diagrams: https://bramp.github.io/js-sequence-diagrams/
Data Visualization with D3.jshttp://blog.avenuecode.com/a-library-for-data-visualization-d3.js
Chrome inside Node.jshttps://github.com/GoogleChrome/puppeteer
XLSX loaderhttps://github.com/mgcrea/node-xlsx
API Repositoryhttps://any-api.com/
ORMhttps://sequelize.org/
Simplified JavaScript Jargonhttp://jargon.js.org
RegExp Testing and Debugginghttps://regexp101.com

Node Packages

TitleDescription
@azure/arm-appserviceAzure SDK for JavaScript to manage App Service resources
@azure/arm-cognitiveservicesAzure SDK for Cognitive Services management
@azure/arm-resourcesAzure SDK for resource management
@azure/arm-searchAzure SDK for managing Azure Search services
@azure/arm-sqlAzure SDK for SQL database management
@azure/arm-subscriptionsAzure SDK for subscription management
@azure/cognitiveservices-computervisionAzure Computer Vision API client library
@azure/keyvault-keysAzure Key Vault keys client library
@azure/ms-rest-jsIsomorphic client runtime for Azure SDK
@azure/msal-nodeMicrosoft Authentication Library (MSAL) for Node.js
@azure/search-documentsAzure Cognitive Search client library
@google-cloud/pubsubGoogle Cloud Pub/Sub client library
@google-cloud/translateGoogle Cloud Translation API client library
@hubspot/api-clientHubSpot API client for Node.js
@microsoft/microsoft-graph-clientMicrosoft Graph API client library
@nosferatu500/textractText extraction from various file formats
@semantic-release/changelogSemantic-release plugin to create or update a changelog file
@semantic-release/execSemantic-release plugin to execute custom shell commands
@semantic-release/gitSemantic-release plugin to commit release assets to the project's git repository
@sendgrid/mailSendGrid email service client library
@types/nodeTypeScript definitions for Node.js
@types/validatorTypeScript definitions for validator.js
adm-zipZIP file management library
alasqlJavaScript SQL database for browser and Node.js
any-shell-escapeEscapes a string for use in shell commands
async-promisesUtilities for working with asynchronous code and promises
basic-authBasic HTTP authentication parsing
billboard.jsRe-usable, easy interface JavaScript chart library
bluebirdPromise library with performance focus
body-parserNode.js body parsing middleware
botbuilderBot Framework v4 SDK for Node.js
botbuilder-adapter-facebookBot Framework v4 adapter for Facebook
botbuilder-aiBot Framework v4 AI integration
botbuilder-dialogsBot Framework v4 dialogs library
botframework-connectorBot Framework connector library
botlibLibrary for building chatbots
c3-chart-makerWrapper for C3.js charting library
chatgptUnofficial ChatGPT API client
chrome-remote-interfaceChrome Debugging Protocol interface
cli-progressEasy to use Progress-Bar for command-line interfaces
cli-spinnerSpinner for command-line interfaces
core-jsModular standard library for JavaScript
data-forgeData transformation and analysis library
date-diffCalculate the difference between two dates
docxtemplaterTemplate-based document generation
dotenv-extendedAdvanced environment variable loader
exceljsExcel workbook manager
expressFast, unopinionated, minimalist web framework for Node.js
express-remove-routeDynamically remove routes in Express
ffmpeg-staticFFmpeg static binaries for Node.js
google-libphonenumberGoogle's libphonenumber library for Node.js
googleapisGoogle APIs client library
ibm-watsonIBM Watson APIs Node.js SDK
indent.jsJavaScript code indentation library
js-beautifyJavaScript beautifier
keyvSimple key-value storage with support for multiple backends
koaNext generation web framework for Node.js
koa-bodyBody parser for Koa
koa-routerRouter middleware for Koa
lodashUtility library delivering modularity, performance, & extras
luxonLibrary for working with dates and times
mammothConvert Word documents (.docx files) to HTML
momentParse, validate, manipulate, and display dates in JavaScript
ms-rest-azureAzure REST API client runtime
nexmoVonage API client library
node-cronCron-like job scheduler for Node.js
node-nlpNatural language processing tools for Node.js
node-tesseract-ocrTesseract OCR engine for Node.js
npmNode package manager
openOpen stuff like URLs, files, executables
pdf-extractionExtract content from PDF files
pdfkitPDF document generation library
phonePhone number parsing, validation and formatting
pizzipZIP file generation library
pptxtemplaterPowerPoint template engine
pragmatismo-io-frameworkFramework for building enterprise applications
prism-mediaInterface for streaming media transcoding
public-ipGet your public IP address
punycodeRobust Punycode converter
puppeteerHeadless Chrome Node.js API
puppeteer-extraModular plugin framework for Puppeteer
puppeteer-extra-plugin-stealthStealth plugin for Puppeteer
qrcodeQR code generator
qrcode-terminalQR code generator for terminal
readlinereadline utility for Node.js
reflect-metadataPolyfill for Metadata Reflection API
rimrafThe UNIX command rm -rf for Node.js
safe-bufferSafer Node.js Buffer API
scanfC-like scanf for Node.js
sequelizePromise-based ORM for Node.js
sequelize-cliSequelize command line interface
sequelize-typescriptDecorators and TypeScript for Sequelize
simple-gitSimple Git interface for Node.js
speakingurlGenerate a slug from a string
ssr-for-botsServer-side rendering for bots
strict-password-generatorGenerate cryptographically strong passwords
swagger-clientSwagger/OpenAPI client for JavaScript
tabulator-tablesInteractive table generation library
tediousTDS driver for connecting to SQL Server databases
textractText extraction from various file types
twitter-api-v2Twitter API v2 client library
typescriptTypeScript language
typescript-rest-rpcTypeScript RPC framework
url-joinJoin all arguments together and normalize the resulting URL
vbscript-to-typescriptConvert VBScript to TypeScript
vhostVirtual host for Node.js
vm2Sandbox for Node.js
vm2-processProcess management for VM2
walk-promiseDirectory tree walker with Promises
washyourmouthoutwithsoapProfanity filter
whatsapp-web.jsWhatsApp Web API for Node.js
winstonMulti-transport async logging library
winston-logs-displayDisplay Winston logs in the browser
yarnFast, reliable, and secure dependency management

Node Packages (Dev Dependencies)

TitleDescription
simple-commit-messageSimple commit message validator
@types/url-joinTypeScript definitions for url-join
ban-sensitive-filesPrevent sensitive files from being committed
commitizenTool to create commit messages according to conventions
cz-conventional-changelogCommitizen adapter for conventional changelog
dependency-checkCheck for unused and missing dependencies
git-issuesList git issues from command line
license-checkerCheck license info for project dependencies
ngrokSecure tunnels to localhost
prettier-standardPrettier and standard configuration
semantic-releaseAutomated version management and package publishing
travis-deploy-onceRun a deployment script only once in Travis CI
ts-nodeTypeScript execution and REPL for Node.js
tslintLinter for TypeScript

Code Extensions

TitleDescription
mbinic.tgit-cmdsSet of commands for launching TortoiseGit dialogs
tomashubelbauer.vscode-markdown-table-formatFormats MarkDown tables so that all columns have the same width
esbenp.prettier-vscodeVS Code plugin for prettier/prettier (wraps at column 80)
mikestead.dotenv.env file support for VS Code
abhinavk99.codewallBlocks distracting websites to improve productivity
christian-kohler.npm-intellisenseAutocompletes npm modules in import statements
csholmq.excel-to-markdown-tableConverts Excel data to Markdown tables
davidanson.vscode-markdownlintMarkdown linting and style checking for VS Code
eg2.ts-tslintTypeScript linter for VS Code
eg2.vscode-npm-scriptRun npm scripts from the command palette
esbenp.prettier-vscodeCode formatter using prettier
formulahendry.auto-rename-tag-Automatically rename paired HTML/XML tags
gruntfuggly.align-modeAligns text in columns based on regular expressions
jmfirth.vsc-space-block-jumperJump between blocks of code separated by blank lines
kaiwood.indentation-level-movementMove lines up and down respecting indentation
mbinic.tgit-cmdsSet of commands for launching TortoiseGit dialogs
mechatroner.rainbow-csvHighlight CSV and TSV files in different colors
mikestead.dotenv.env file support for VS Code
sirtori.indenticatorHighlights the current indentation depth
tandy.color-basicSyntax highlighting for Color BASIC

Code Shotcut keys

KeyDescription
F8Next error.
F12Go to symbol definition.
F5Run.
CTRL + .Auto refactoring (Fix).
ALT + SHIFT + DOWN ARROWDuplicate the line code.
CTRL + SHIFT + HReplace all followed by CTRL + ALT + ENTER on replace text box.
CTRL + SHIFT + BCompile inside VSCode, you can also open an external terminal and run tsc -w.
CTRL + GGo to the specified line.
CTRL + SHIFT + GGoes to Git.
CTRL + SHIFT+POpens the Command Palette
CTRL + ALT+UP/DOWN ARROWEnter the Vertical Selection mode
ALT + UP/DOWN ARROWMove lines

Common tasks

TaskDescription
npm update -gUpdates NPM
node -vChecks node version
ncu -aUpdate all packages in package.json