0.3.1 • Published 6 years ago

helper-modules v0.3.1

Weekly downloads
4
License
MIT
Repository
github
Last release
6 years ago

npm.io

npmjs license github Codacy Badge discord

Library for handling various things like commands, localization, logging etc.

Contents

Installation

  • To install the package simply run:
    • npm i helper-modules
  • If you are installing from the repo, you'd probably need to install dependencies:
    • npm i
  • To build module files, use build script:
    • npm run build

Features

  • Logging actions and info with Log module
  • Bot localization on different servers with Lang module
  • Bot command handling with Command module
  • Generating flexible config file with Config module

Some of the library features use asynchronous functions, be sure to handle them properly with then()/catch() or async/await

This library is highly WIP, things might change throughout the time

Latest buildable version of package will always be located in 'develop' branch, 'master' is for stable and fully tested versions

Documentation and examples

Autogenerated documentation for this project is located here

This reference is WIP and may not contain all and latest information all the time

Importing module features

TypeScript

import * as helpers from 'helper-modules'

JavaScript (ES6 modules)

import helpers from 'helper-modules'

JavaScript (CommonJS)

const helpers = require('helper-modules')

Log handling

Log module (namespace) is used for logging errors, warnings and any other additional information on demand.

Module definitions

Writing log messages

const log = helpers.Log

log.log('This is a simple log message')
log.logError('This message will appear red in console and will have [ERROR] prefix in the log file')
log.logWarning('Yellow message with [WARNING] prefix')

log.logToFile('Something important that you want to log into separate file', './path-to-the-file')
.then(() => log.log('This will not appear in the log file', true, true, false))
.catch(() => log.logError('And this will not appear in the console, neither will have a timestamp', false, false))

Getting last log messages

var lastlog = log.showLastLog(10) // will return maximum of 10 log messages
var lastlogmessage = `${lastlog[0].time.toString()} : ${lastlog[0].type} : ${lastlog[0].message}`

Setting new prefix for the log file

const reserved = log.Utility.reservedCharacters // these chars cannot be located in the logfile prefix
log.setPrefix('newprefix') // now the default log file will be named as 'newprefix_day_month_year.log'

Getting current time

const currentTime = new log.Utility.TimeStamp()
var currentTimeString = currentTime.toString() // returns '[hour:minute:second]'
currentTimeString = log.Utility.TimeStamp.toString(currentTime) // same result, but through static method

Localizing messages of your bot

Lang module provides features for automatic handling of message localization based on user or server id.

Registering localization dictionaries

Before accessing language messages you obviously need to add language data.

lang.registerLanguage([
    ['Hello', 'world'],
    ['Goodbye', 'my darling'],
    ['Yet another example message key', 'Yet another example message value']
], 'en') // will add english localization and create new language file in the ./helper-modules/locales folder. 'en' localization is default and can be omitted

lang.registerLanguage([
    ['Hello', '世界'],
    ['Goodbye', '愛しいあなた'],
    ['Yet another example message key', 'さらに別のメッセージ値の例']
], 'jp') // adds japanese localization
  • You do not need to check if localization exists already, if it does - module will be checked for unexisting keys and add them if necessary
  • Once new internal class in the module is created (usually when module function is executed in the first time), folder ./helper-modules/locales will be checked for files matching lang_<some localization literal>.json>. They automatically will be considered message dictionaries. To add new localization bot hoster does not need to change the code, just add such a file with proper structure.

Setting language preferences for precific userid

lang.setLanguage('1234567', 'jp')

Getting localized messages

lang.getMessage('1234', 'Hello') // returns 'world'
lang.getMessage('1234567', 'Hello') //returns '世界'

lang.getMessage('1234', 'unexisting key') //returns 'unexisting key', because this message does not exist

Handling commands

Command module is meant to help you handle commands entered through console or discord messages

Every call to onConsoleMessage or onDiscordMessage (or to universal onMessage functions which is union for previously listed methods) returns CommandResolveResult object which contains following properties:

export class CommandResolveResult<T extends string | Message> {
public readonly args: undefined | string[] // undefined only when message is not a command, otherwise string[] with lenght >= 0
public readonly argsCount: number // >= 0
public readonly calledIn: CommandType // Console/server/DM
public readonly cmd: undefined | string //first part of the command, separated from prefix if it exists
public readonly executeResult: any // callback function returns
public readonly isCommand: boolean // does message start with a prefix (if it's a discord message, not console command which is always considered command)
public readonly message: T // full message
public readonly nativeType: undefined | CommandType // type command was registered of
public readonly wasExecuted: boolean // was callback executed or not
public readonly callback: undefined | ((...args: any[]) => any) // callback function if it exists

Registering commands

There are few method signatures for callbacks which needs to be observed:

  • Console command callback:
    • (string[]) => any
    • () => any
  • Discord command callback:
    • (Discord.Message, string[]) => any
    • (Discord.Message) => any)
    • () => any
const cmd = helpers.Command
const commandtype = helpers.Command.Utility.CommandType

cmd.registerCommand('simple', commandtype.console, simpleCallback)
cmd.registerCommand('simple', commandtype.shared, simpleCallback)

cmd.registerCommand('cnsl', commandtype.console, consoleCommandCallback)

cmd.registerCommand('dscrd', commandtype.server, discordCommandCallback)

function simpleCallback() {
    console.log('This is simple callback with no arguments, it could be executed from anywhere')
}

function consoleCommandCallback(args) {
    if (args.lenght > 0)  { // all parameters passed into callbacks are never undefined (if callback follows given signature ofcourse)
        console.log(args.toString())
    }
    else{
        console.log('no arguments passed =(')
    }
}

function discordCommandCallback(message, args) {
    if (message.author.id === '1234') {
        console.log('1234 said: '+ message.content)
    }
    console.log(args)
}

NodeJS console commands

process.stdin.setEncoding('utf-8')

process.stdin.on('data', data => cmd.onConsoleMessage(data)
.then(result => {
    if (result.wasExecuted) {
        console.log(JSON.stringify(result.executeResult, null, '\t'))
    }
})
.catch(ex => console.error(ex)))

Discord commands

client.on('message', async (message) => {
    var result = await cmd.onDiscordMessage(message)
    console.log(JSON.stringify(result))
})

Roadmap

  • Logging
  • Language handling
  • Command handling
  • Migrating to async filesystem operations and async API methods for command handling
  • Improving language handler with new helper methods, such as getting available localizations, validating localization object, appending new entries to the localization file without overwriting it
  • Advanced command parsing with single quotation marks and arrays (not sure if needed)
  • Configuration module
  • Auto permission handling (refused)

Credits

  • General idea and structure (partially) of this library was inspired by Oxide/uMod modding platform, code from Oxide.Core.dll licensed under the MIT license
  • All dependencies belong to their developer teams, and keep original licenses

Links

Community

npm.io

0.3.1

6 years ago

0.3.0

6 years ago

0.2.0

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago