repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
balovbohdan/fwd-ann
dist/lib/teacher/types.d.ts
<reponame>balovbohdan/fwd-ann import { ANN } from '../ann'; import { Signals } from '../signals'; export declare type Result = { ann: ANN; log: Log; }; export declare type Log = Array<{ epoch: number; cycle: number; RootMSE: number; }>; export declare type PreparedParams = { epoches: number; }; export declare type Params = { epoches?: number; }; export declare type Data = { ann: ANN; sets: Sets; }; export declare type CycleData = { set: Set; epoch: number; cycle: number; }; export declare type Sets = Array<Set>; export declare type Set = { task: Signals; idealOutput: Signals; };
balovbohdan/fwd-ann
src/lib/units/utils.ts
<filename>src/lib/units/utils.ts import { Data as LayerDataRaw } from './create'; export const calcUnitsQtyInRawLayerData = ({ unitsData }:LayerDataRaw):number => unitsData.reduce((totalQty, { qty }) => totalQty + qty, 0);
balovbohdan/fwd-ann
src/utils/object-utils.ts
export const clone = <T extends object>(obj:T):T => JSON.parse(JSON.stringify(obj)); export const assignDeep = <T extends object>(target:object, source:object, concatArrays:boolean = false):T => { const res = {}; const isObject = obj => obj && typeof obj === 'object'; if (!isObject(target) || !isObject(source)) return <T>source; const keys = Object.keys(source).concat(Object.keys(target)) .filter((value, index, self) => self.indexOf(value) === index); keys.forEach(key => { const targetValue = target[key]; const sourceValue = source[key]; if (!targetValue || !sourceValue) res[key] = targetValue || sourceValue; else if (Array.isArray(targetValue) && Array.isArray(sourceValue)) res[key] = concatArrays ? targetValue.concat(sourceValue) : Array.from(sourceValue); else if (isObject(targetValue) && isObject(sourceValue)) res[key] = assignDeep(Object.assign({}, targetValue), sourceValue); else res[key] = sourceValue; }); return <T>res; }; export const freezeDeep = <T extends Object>(obj:{[key:string]:any}&T):Readonly<T> => { const propNames = Object.getOwnPropertyNames(obj); propNames.forEach(name => { const prop:any = obj[name]; if (typeof prop == 'object' && prop !== null) freezeDeep(prop); }); return Object.freeze(obj); };
balovbohdan/fwd-ann
src/lib/signals/SignalsErrors.ts
import { Matrix } from 'matrix-calculus'; export class SignalsErrors { constructor(errors:Matrix) { this.errors = errors; } getMatrix():Matrix { return this.errors; } getSum():number { return this.errors.getUnitsSum(); } private readonly errors:Matrix; }
balovbohdan/fwd-ann
dist/lib/calculators/output-errors/types.d.ts
import { SignalsErrors } from '../../signals'; export declare type OutputErrors = { errors: SignalsErrors | null; };
balovbohdan/fwd-ann
src/lib/weights/layers-pair-weights/index.ts
export { Weights } from './Weights';
balovbohdan/fwd-ann
src/lib/calculators/back-error-propagation/calc-delta-weights.ts
// https://docs.google.com/document/d/1DSlzdK0LM1GqxDPES9GFLvuniNYoJNe5kEUfMS4FWsM import { Matrix } from 'matrix-calculus'; import { ANN } from '../../ann'; import calcDelta from './calc-delta'; import { LayersPair } from '../../layers/types'; import { Signals, SignalsErrors } from '../../signals'; type Data = { ann:ANN; layersPair:LayersPair; errors:SignalsErrors|null; layersOutputs:Array<Signals>; }; const calcDeltaWeights = (data:Data):Matrix|null => { const errors = data.errors || null; const { layersPair, layersOutputs } = data; if (!errors) return null; const delta:Matrix = calcDelta({ errors, layersPair, output: data.layersOutputs[1], }); const inputLayerOutputTransposed:Matrix = layersOutputs[0] .getMatrix() .transpose(); const learningSpeed:number = data.ann.getLearningSpeed(); return delta .multiply(inputLayerOutputTransposed) .multiply(-learningSpeed) .transpose(); }; export default calcDeltaWeights;
balovbohdan/fwd-ann
dist/utils/math-utils/number-capacity.d.ts
export declare const getCapacity: (n: number) => number; export declare const getCapacityBase: (capacity: number) => number; export declare const getNumberByCapacity: (capacity: number) => number; export declare const getBaseCapacityNumber: (n: number) => number; export declare const sign: (n: number) => number;
balovbohdan/fwd-ann
dist/lib/weights/layers-pairs-weights/rnd/create-rnd-layers-weights.d.ts
import { LayersWeights } from '../LayersWeights'; import { Params as RndWeightsParams } from '../../layers-pair-weights/rnd/create-rnd-weights'; export declare type Params = Array<RndWeightsParams>; declare const createRndLayersWeights: (params: RndWeightsParams[]) => LayersWeights; export default createRndLayersWeights;
balovbohdan/fwd-ann
dist/lib/units/utils.d.ts
import { Data as LayerDataRaw } from './create'; export declare const calcUnitsQtyInRawLayerData: ({ unitsData }: LayerDataRaw) => number;
balovbohdan/fwd-ann
dist/lib/activation-funcs/utils.d.ts
import { ActivationFunction } from './types'; export declare const getByName: (name: string) => ActivationFunction | null;
balovbohdan/fwd-ann
src/lib/ann/ANN.ts
import * as T from './types'; import {Layers} from '../layers'; import config from '../../config'; import { Signals } from '../signals'; import { assignDeep } from '../../utils/object-utils'; import { decimal } from '../../utils/math-utils/random-number'; import { LayersWeights } from '../weights/layers-pairs-weights'; import calcAnnOutput from '../calculators/ann-output/calc-ann-output'; import * as layersWeightsUtils from '../weights/layers-pairs-weights/utils'; export class ANN { constructor(data:T.Data, params:T.Params = {}) { const { id, name, layers, layersWeights }:T.DataPrepared = ANN.prepareData(data); this.id = id; this.name = name; this.layers = layers; this.layersWeights = layersWeights; this.params = assignDeep(config.ann.defParams, params); } getId():string|null { return this.id; } setId(id:string) { this.id = id; } getLayers():Layers { return this.layers; } getLayersWeights():LayersWeights { return this.layersWeights; } setLayersWeights(layersWeights:LayersWeights):ANN { layersWeightsUtils.hasTheSameSizeStrict(this.layersWeights, layersWeights); this.layersWeights = layersWeights; return this; } getLearningSpeed():number { return this.params.learningSpeed; } async calcOutput(input:Signals):Promise<Signals> { const data = await this.calcComplexOutput(input); return data.output; } /** * Response consists of calculating process meta data. * It is needed to analyze calculating process and start * other calculation processes based on this meta data. */ calcComplexOutput(input:Signals):Promise<T.ComplexOutput> { return calcAnnOutput({ ann: this, signals: this.prepareInputSignals(input), }); } private prepareInputSignals(input:Signals):Signals { const params = this.params.inputSignals; if (params.needNormalize) input = input.normalize(params.normalizer); if (params.needOffset) input = input.offset(params.offset); return input; } private static prepareData(data:T.Data):T.DataPrepared { data.name = data.name || 'ANN-' + decimal(); data.id = typeof data.id === 'string' ? data.id : null; return <T.DataPrepared>data; } private id:string|null = null; private layersWeights:LayersWeights; private readonly name:string; private readonly layers:Layers; private readonly params:T.ParamsPrepared; }
balovbohdan/fwd-ann
dist/utils/math-utils/arithmetic-average.d.ts
declare type Calculator = (numbers: Array<number>) => number; export declare const simple: (values: number[]) => number; export declare const crossed: (left: number[], right: number[], calc?: Calculator | undefined) => number[]; export {};
balovbohdan/fwd-ann
src/lib/calculators/ann-output/calc-ann-output.ts
import { ANN } from '../../ann'; import { Signals } from '../../signals'; import calcLayersPair from './calc-layers-pair'; export type Res = { output:Signals; layersInputs:Array<Signals>; layersOutputs:Array<Signals>; }; type Data = { ann:ANN; signals:Signals; }; const prepareAnnOutput = (ann:ANN, output:Signals):Signals => { const outputLayer = ann.getLayers().getOutputLayer(); const unitsNames:Array<string> = outputLayer.getNames(); output.setNames(unitsNames); return output; }; const calcAnnOutput = async ({ ann, signals }:Data):Promise<Res> => { const layersInputs:Array<Signals> = []; const layersOutputs:Array<Signals> = []; let layersPairDirtyOutput:Signals|null = null; ann.getLayers().forEachPair(layersPair => { const inputSignals = layersPairDirtyOutput || signals; const result = calcLayersPair({ ann, signals: inputSignals, layersPair: layersPair, }); if (layersPair.left.isInput()) layersOutputs.push(result.layersOutputs[0]); layersPairDirtyOutput = result.dirtyOutput; layersInputs.push(inputSignals); layersOutputs.push(result.layersOutputs[1]); if (layersPair.right.isOutput()) layersInputs.push(result.layersInputs[1]); }); const layersQty = ann.getLayers().getQty(); const output = prepareAnnOutput(ann, layersOutputs[layersQty - 1]); return { output, layersInputs, layersOutputs, }; }; export default calcAnnOutput;
balovbohdan/fwd-ann
dist/lib/calculators/ann-output/weights-to-signals.d.ts
<reponame>balovbohdan/fwd-ann<filename>dist/lib/calculators/ann-output/weights-to-signals.d.ts import { Signals } from '../../signals'; import { Weights } from '../../weights/layers-pair-weights'; declare type Data = { weights: Weights; signals: Signals; }; declare const weightsToSignals: (data: Data) => Signals; export default weightsToSignals;
balovbohdan/fwd-ann
dist/lib/layers/Layers.d.ts
import * as T from './types'; import { Units } from '../units'; export declare class Layers { constructor(layers: T.LayersData); getOutputLayer(): Units | never; getQty(): number; getAll(): T.LayersData; getPairs(): Array<T.LayersPair>; forEach(f: (layer: Units, i?: number, arr?: T.LayersData) => void): void; forEachPair(f: (layersPair: T.LayersPair) => void): void; map(f: (layer: Units, i?: number, arr?: T.LayersData) => any): Array<any>; mapPairs(f: (layersPair: T.LayersPair) => any): Array<any>; private readonly layers; }
balovbohdan/fwd-ann
src/utils/math-utils/numbers-collection-alias.ts
// Encodes/decodes collection of positive numbers (n > 0) to integer alias. import { clone } from '../object-utils'; export const encode = (numbers:Array<number>):number => { const numbersPrepared = clone(numbers) .filter(n => n > 0) .sort(); const maxNumber:number = Math.max.apply(Math, numbersPrepared); const cipherArray:Array<number> = (new Array(maxNumber)).fill(0); numbersPrepared.forEach(number => cipherArray[number - 1] = 1); const cipher:string = cipherArray.reverse().join(''); return parseInt(cipher, 2); }; export const decode = (cipher:number):Array<number> => { const binary:string = Math.round(cipher).toString(2); return binary.split('') .reverse() .map((n, i) => +n ? i + 1 : 0) .filter(n => n); };
balovbohdan/fwd-ann
dist/lib/weights/layers-pairs-weights/create.d.ts
import { LayersWeights } from './LayersWeights'; declare const create: (data: number[][][]) => LayersWeights; export default create;
balovbohdan/fwd-ann
src/lib/weights/layers-pair-weights/Weights.ts
import { Matrix } from 'matrix-calculus'; export class Weights { constructor(weights:Matrix) { this.weights = weights; } getMatrix():Matrix { return this.weights; } private readonly weights:Matrix; }
balovbohdan/fwd-ann
src/lib/weights/layers-pairs-weights/types.ts
<filename>src/lib/weights/layers-pairs-weights/types.ts<gh_stars>0 import { Weights } from '../layers-pair-weights'; export type Data = Array<Weights>; export type DirtyData = Array<Array<Array<number>>>;
balovbohdan/fwd-ann
src/lib/calculators/back-error-propagation/calc-delta.ts
<filename>src/lib/calculators/back-error-propagation/calc-delta.ts // https://docs.google.com/document/d/1DSlzdK0LM1GqxDPES9GFLvuniNYoJNe5kEUfMS4FWsM import { Matrix } from 'matrix-calculus'; import { T } from '../../layers'; import calcTheta from './calc-theta'; import { Signals, SignalsErrors } from '../../signals'; type Data = { output:Signals; errors:SignalsErrors; layersPair:T.LayersPair; }; const calcDelta = ({ output, errors, layersPair }:Data) => { const errorsMatrix:Matrix = errors.getMatrix(); const theta:Matrix = calcTheta({ output, layersPair }); return theta.multiplyTermByTerm(errorsMatrix).multiply(-2); }; export default calcDelta;
balovbohdan/fwd-ann
dist/lib/layers/LayerName.d.ts
<gh_stars>0 export declare class LayerName { static readonly LAYER = "Layer"; static readonly INPUT = "InputLayer"; static readonly OUTPUT = "OutputLayer"; static readonly HIDDEN = "HiddenLayer"; }
balovbohdan/fwd-ann
src/lib/units/create.ts
import * as T from './types'; import { Unit } from './Unit'; import { Units } from './Units'; import {LayerType} from '../layers'; import { ActivationFunction } from '../activation-funcs'; export type SingleData = { qty:number; names?:Array<string>; ActivationFunction:ActivationFunction; }; export type Data = { name?:string; type:LayerType; unitsData:Array<SingleData>; }; const createSingleData = (data:SingleData):T.UnitsData => { const units:Array<Unit> = []; const names = data.names || []; for (let i = 0; i < data.qty; i++) { units.push( new Unit({ name: names[i], ActivationFunction: data.ActivationFunction, }) ); } return units; }; const createData = ({ type, name, unitsData }:Data):T.UnitsRaw => { const resultData:T.UnitsRaw = { name, type, units: [], }; unitsData.forEach(singleData => resultData.units.push(...createSingleData(singleData)) ); return resultData; }; const create = (data:Data):Units => { const unitsData = createData(data); return new Units(unitsData); }; export default create;
balovbohdan/fwd-ann
dist/lib/weights/layers-pairs-weights/rnd/create-params.d.ts
<filename>dist/lib/weights/layers-pairs-weights/rnd/create-params.d.ts import { Params as RandomWeightParam } from '../../layers-pair-weights/rnd/create-rnd-weight'; import { LayersRawData } from '../../../layers/types'; export declare type Data = { layersData: LayersRawData; randomWeightParams?: Array<RandomWeightParam>; }; declare const createParams: (data: Data) => import("../../layers-pair-weights/rnd/create-rnd-weights").Params[]; export default createParams;
balovbohdan/fwd-ann
dist/lib/activation-funcs/activation-funcs.d.ts
<gh_stars>0 import { ActivationFunction } from './types'; export declare const Areasinus: ActivationFunction; export declare const BinaryStep: ActivationFunction; export declare const ReLU: ActivationFunction; export declare const Logistic: ActivationFunction; export declare const HyperbolicTangent: ActivationFunction; export declare const UnitLinear: ActivationFunction; export declare const ZeroLinear: ActivationFunction; export declare const RationalSigmoid: ActivationFunction;
balovbohdan/fwd-ann
src/lib/weights/layers-pairs-weights/rnd/create-rnd-layers-weights-from-layers-raw-data.ts
<reponame>balovbohdan/fwd-ann<filename>src/lib/weights/layers-pairs-weights/rnd/create-rnd-layers-weights-from-layers-raw-data.ts import { T as TLayers } from '../../../layers'; import { LayersWeights } from '../LayersWeights'; import { calcUnitsQtyInRawLayerData } from '../../../units/utils'; import createRndLayersWeights, { Params as BaseParams } from './create-rnd-layers-weights'; import { Params as RndWeightsParams } from '../../layers-pair-weights/rnd/create-rnd-weight'; type Params = { layersData:TLayers.LayersRawData; rndWeightParams?:RndWeightsParams; }; const createBaseParams = ({ layersData, rndWeightParams }:Params):BaseParams => { const res:BaseParams = []; for (let i = 0; i < layersData.length; i++) { const leftLayerData = layersData[i]; const rightLayerData = layersData[i + 1]; if (!leftLayerData || !rightLayerData) continue; res.push({ rndWeightParams, leftUnitsQty: calcUnitsQtyInRawLayerData(leftLayerData), rightUnitsQty: calcUnitsQtyInRawLayerData(rightLayerData), }); } return res; }; const createRndLayersWeightsFromLayersRawData = (params:Params):LayersWeights => { const baseParams = createBaseParams(params); return createRndLayersWeights(baseParams); }; export default createRndLayersWeightsFromLayersRawData;
balovbohdan/fwd-ann
dist/lib/units/create.d.ts
import { Units } from './Units'; import { LayerType } from '../layers'; import { ActivationFunction } from '../activation-funcs'; export declare type SingleData = { qty: number; names?: Array<string>; ActivationFunction: ActivationFunction; }; export declare type Data = { name?: string; type: LayerType; unitsData: Array<SingleData>; }; declare const create: (data: Data) => Units; export default create;
balovbohdan/fwd-ann
src/lib/calculators/back-error-propagation/calc-layer-output-errors.ts
import { Matrix } from 'matrix-calculus'; import { ANN } from '../../ann'; import { Units } from '../../units'; import { SignalsErrors } from '../../signals'; import { Weights } from '../../weights/layers-pair-weights'; type Data = { ann:ANN; aimLayer:Units; layersPairIndex:number|null; nextLayerOutputErrors:SignalsErrors; }; const getWeightsShareOfParticipation = (weights:Weights|null):Matrix|null => { if (weights === null) return null; const weightsMatrix:Matrix = weights.getMatrix(); const weightsMatrixColsSums:Array<number> = weightsMatrix.reduceCols((prev, unit) => prev + unit, 0); return weightsMatrix.mutate((unit:number, row?:number, col?:number) => unit / weightsMatrixColsSums[col || 0] ); }; const calcLayerOutputErrors = (data:Data):SignalsErrors|never|null => { const { ann, aimLayer, layersPairIndex, nextLayerOutputErrors } = data; const weights = ann.getLayersWeights().get(layersPairIndex); if (aimLayer.isInput()) return null; if (aimLayer.isOutput()) return nextLayerOutputErrors; const weightsShareOfParticipation:Matrix|null = getWeightsShareOfParticipation(weights); const errors:Matrix|null = nextLayerOutputErrors && weightsShareOfParticipation ? weightsShareOfParticipation.multiply(nextLayerOutputErrors.getMatrix()) : null; return errors ? new SignalsErrors(errors) : null; }; export default calcLayerOutputErrors;
balovbohdan/fwd-ann
dist/lib/weights/layers-pairs-weights/rnd/create.d.ts
import { LayersWeights } from '../LayersWeights'; import { Data } from './create-params'; declare const create: (data: Data) => LayersWeights; export default create;
balovbohdan/fwd-ann
dist/lib/units/types.d.ts
<gh_stars>0 import { Unit } from './Unit'; import { LayerType } from '../layers'; export declare type UnitsData = Array<Unit>; export declare type UnitsRaw = { name?: string; type: LayerType; units: UnitsData; };
balovbohdan/fwd-ann
dist/utils/math-utils/random-number.d.ts
declare type FloatingParams = { min?: number; max?: number; exclude?: Array<number>; }; declare type DecimalParameterizedParams = { min?: number; max?: number; exclude?: Array<number>; }; export declare const decimal: () => number; export declare const sign: () => 1 | -1; export declare const decimalWithParams: (params?: DecimalParameterizedParams) => number; export declare const floating: (params?: FloatingParams | undefined) => number; export {};
balovbohdan/fwd-ann
dist/lib/signals/normalize.d.ts
<gh_stars>0 import { Signals } from './Signals'; import { Mutator } from './mutators'; declare const normalize: (signals: Signals, mutator?: Mutator | null) => Signals; export default normalize;
balovbohdan/fwd-ann
dist/lib/ann/types.d.ts
<gh_stars>0 import { Layers } from '../layers'; import { Mutator } from '../signals'; import { LayersWeights } from '../weights/layers-pairs-weights'; import { Res as AnnOutputCalculatorRes } from '../calculators/ann-output/calc-ann-output'; export declare type ComplexOutput = AnnOutputCalculatorRes; export declare type Params = { learningSpeed?: number; inputSignals?: { offset?: number; needOffset?: boolean; needNormalize?: boolean; normalizer?: Mutator | null; }; }; export declare type ParamsPrepared = Params & { learningSpeed: number; inputSignals: { offset: number; needOffset: boolean; needNormalize: boolean; normalizer: Mutator | null; }; }; export declare type Data = { name?: string; layers: Layers; id?: string | null; layersWeights: LayersWeights; }; export declare type DataPrepared = Data & { name: string; id: string | null; };
balovbohdan/fwd-ann
dist/lib/weights/layers-pairs-weights/types.d.ts
import { Weights } from '../layers-pair-weights'; export declare type Data = Array<Weights>; export declare type DirtyData = Array<Array<Array<number>>>;
balovbohdan/fwd-ann
src/lib/weights/layers-pairs-weights/utils.ts
<gh_stars>0 import { Matrix } from 'matrix-calculus'; import { LayersWeights } from './LayersWeights'; import { Weights } from '../layers-pair-weights'; export const isIdentical = async (left:LayersWeights, right:LayersWeights):Promise<boolean> => { const leftStr = JSON.stringify(left.getAllDirty()); const rightStr = JSON.stringify(right.getAllDirty()); return leftStr === rightStr; }; export const hasTheSameSizeStrict = (left:LayersWeights, right:LayersWeights):boolean|never => { if (hasTheSameSize(left, right)) return true; throw new LayersWeightsError('ANN layers weights datasets has different sizes.'); }; export const hasTheSameSize = (left:LayersWeights, right:LayersWeights) => { const leftWeights:Array<Weights> = left.getAll(); const rightWeights:Array<Weights> = right.getAll(); const leftWeightsQty:number = leftWeights.length; if (leftWeightsQty !== rightWeights.length) return false; for (let i = 0; i < leftWeightsQty; i++) { const matrix:Matrix = leftWeights[i].getMatrix(); const rightMatrix:Matrix = rightWeights[i].getMatrix(); if (!matrix.hasTheSameDimensions(rightMatrix)) return false; } return true; }; class LayersWeightsError extends Error { constructor(message:string) { super(message); Object.setPrototypeOf(this, LayersWeightsError.prototype); } }
balovbohdan/fwd-ann
src/lib/weights/layers-pairs-weights/rnd/create.ts
import { LayersWeights } from '../LayersWeights'; import createParams, { Data } from './create-params'; import createRndLayersWeights from './create-rnd-layers-weights'; const create = (data:Data):LayersWeights => { const params = createParams(data); return createRndLayersWeights(params); }; export default create;
balovbohdan/fwd-ann
dist/lib/weights/layers-pair-weights/rnd/create-weights-params.d.ts
import { Params as Res } from './create-rnd-weights'; import { Data as LayerData } from '../../../units/create'; import { Params as RndWeightParams } from './create-rnd-weight'; declare type Data = { leftLayerData: LayerData; rightLayerData: LayerData; randomWeightParams?: RndWeightParams; }; declare const createWeightsParams: (data: Data) => Res; export default createWeightsParams;
balovbohdan/fwd-ann
src/lib/activation-funcs/activation-funcs.ts
<reponame>balovbohdan/fwd-ann<filename>src/lib/activation-funcs/activation-funcs.ts import { Matrix } from 'matrix-calculus'; import { funcs } from 'math-funcs-calculus'; import { ActivationFunction } from './types'; export const Areasinus:ActivationFunction = { func: funcs.Areasinus, calc: funcs.Areasinus.calc, calcComplexDerivative: (matrix:Matrix):Matrix => { const mutator = n => funcs.Areasinus.calcDerivative(n); return matrix.mutate(mutator); }, }; export const BinaryStep:ActivationFunction = { func: funcs.BinaryStep, calc: funcs.BinaryStep.calc, calcComplexDerivative: (matrix:Matrix):Matrix => matrix.mutate(funcs.BinaryStep.calcDerivative), }; export const ReLU:ActivationFunction = { func: funcs.ReLU, calc: funcs.ReLU.calc, calcComplexDerivative: (matrix:Matrix):Matrix => matrix.mutate(funcs.ReLU.calcDerivative), }; export const Logistic:ActivationFunction = { func: funcs.Logistic, calc: funcs.Logistic.calc, calcComplexDerivative: (matrix:Matrix):Matrix => { const right = matrix.inverseSigns().sum(1); return matrix.multiplyTermByTerm(right); }, }; export const HyperbolicTangent:ActivationFunction = { func: funcs.HyperbolicTangent, calc: funcs.HyperbolicTangent.calc, calcComplexDerivative: (matrix:Matrix):Matrix => { const left = matrix.sum(1); const right = matrix.inverseSigns().sum(1); return left.multiplyTermByTerm(right); }, }; export const UnitLinear:ActivationFunction = { func: funcs.UnitLinear, calc: funcs.UnitLinear.calc, calcComplexDerivative: (matrix:Matrix):Matrix => matrix, }; export const ZeroLinear:ActivationFunction = { func: funcs.ZeroLinear, calc: funcs.ZeroLinear.calc, calcComplexDerivative: (matrix:Matrix):Matrix => matrix, }; export const RationalSigmoid:ActivationFunction = { func: funcs.RationalSigmoid, calc: funcs.RationalSigmoid.calc, calcComplexDerivative: (matrix:Matrix):Matrix => matrix, };
balovbohdan/fwd-ann
dist/lib/signals/SignalsErrors.d.ts
import { Matrix } from 'matrix-calculus'; export declare class SignalsErrors { constructor(errors: Matrix); getMatrix(): Matrix; getSum(): number; private readonly errors; }
balovbohdan/fwd-ann
src/lib/activation-funcs/utils.ts
import { ActivationFunction } from './types'; import * as activationFuncs from './activation-funcs'; export const getByName = (name:string):ActivationFunction|null => activationFuncs[name] || null;
balovbohdan/fwd-ann
dist/lib/weights/layers-pairs-weights/LayersWeights.d.ts
<reponame>balovbohdan/fwd-ann import * as T from './types'; import { Weights } from '../layers-pair-weights'; export declare class LayersWeights { constructor(layersWeights: T.Data); get(layersPairIndex: number | null): Weights | null; getAllDirty(): T.DirtyData; getAll(): Array<Weights>; private readonly weights; }
balovbohdan/fwd-ann
dist/lib/units/Unit.d.ts
import { ActivationFunction } from '../activation-funcs'; declare type Params = { name?: string; ActivationFunction: ActivationFunction; }; export declare class Unit { constructor(params: Params); getName(): string; getActivationFunction(): ActivationFunction; private readonly name; private readonly ActivationFunction; } export {};
balovbohdan/fwd-ann
dist/lib/activation-funcs/types.d.ts
<gh_stars>0 import { Matrix } from 'matrix-calculus'; export declare type ActivationFunction = { func: Func; calc: (n: number) => number; calcComplexDerivative: (matrix: Matrix) => Matrix; }; declare type Func = { calc: (n: number) => number; }; export {};
balovbohdan/fwd-ann
src/lib/weights/layers-pair-weights/rnd/create-weights-params.ts
<reponame>balovbohdan/fwd-ann import { Params as Res } from './create-rnd-weights'; import { Data as LayerData } from '../../../units/create'; import { assignDeep } from '../../../../utils/object-utils'; import { Params as RndWeightParams } from './create-rnd-weight'; type Data = { leftLayerData:LayerData; rightLayerData:LayerData; randomWeightParams?:RndWeightParams; }; const calcUnitsQty = (data:LayerData):number => data.unitsData.reduce((sum, item) => sum + item.qty, 0); const prepareRndWeightParams = (leftUnitsQty, params:RndWeightParams = {}):RndWeightParams => assignDeep(params, { leftUnitsQty }); const createWeightsParams = (data:Data):Res => ({ leftUnitsQty: calcUnitsQty(data.leftLayerData), rightUnitsQty: calcUnitsQty(data.rightLayerData), rndWeightParams: prepareRndWeightParams(data.randomWeightParams), }); export default createWeightsParams;
balovbohdan/fwd-ann
src/lib/units/Unit.ts
<gh_stars>0 import { ActivationFunction } from '../activation-funcs'; import { decimal } from '../../utils/math-utils/random-number'; type Params = { name?:string; ActivationFunction:ActivationFunction; }; export class Unit { constructor(params:Params) { this.name = params.name || ('Unit-' + decimal()); this.ActivationFunction = params.ActivationFunction; } getName():string { return this.name; } getActivationFunction():ActivationFunction { return this.ActivationFunction; } private readonly name:string; private readonly ActivationFunction:ActivationFunction; }
YourBetterAssistant/yourbetterassistant
commands/Music/leave.ts
<reponame>YourBetterAssistant/yourbetterassistant<gh_stars>0 "use strict"; import { Client, Message } from "discord.js"; module.exports = { name: "leave", description: "Leaves a voice channel", category: "Music", memberpermissions: ["CONNECT", "SPEAK"], adminPermOverride: true, cooldown: 2, usage: "leave", run: async (client: Client, message: Message) => { if (!message.guild?.me?.voice.channel) { return message.channel.send("I am not in a vc "); } if ( message.member?.voice?.channel?.id !== message.guild.me.voice.channel.id ) return message.channel.send( "To run this command you need to be in the same voice channel" ); let server_queue = client.queue.get(message.guild.id); try { await server_queue.player.disconnect(); await server_queue.player.destroy(); client.queue.delete(message.guild.id); await message.reply("I have left"); } catch (err) { return message.reply("An error occured try to disconenct me manually"); } }, };
YourBetterAssistant/yourbetterassistant
commands/Economy/deposit.ts
"use strict"; import Discord, { Client, Message } from "discord.js"; import money from "../../Constructors/economy"; const currency = new money(); import { reply } from "../../exports"; module.exports = { name: "deposit", aliases: ["dep"], description: "deposits YMCs to the bank", category: "Economy", guildOnly: true, memberpermissions: "VIEW_CHANNEL", adminPermOverride: true, cooldown: 5, usage: "deposit <amount>", run: async (client: Client, message: Message, args: string[]) => { let coins = args[0]; let user = message.author; reply(`Withdrawing ${coins}YMCs from the bank!`, true, message); if (coins === "all" ?? coins === "." ?? coins === "*" ?? coins === "max") { await currency.deposit( user.id, ( await currency.findUser(message.author.id) )?.coins!, message ); return; } if (isNaN(parseInt(coins))) { return message.reply("that is not a number"); } await currency.deposit(user.id, parseInt(coins), message); return; }, };
YourBetterAssistant/yourbetterassistant
lib/logger.ts
import chalk from "chalk"; export default class Logger { private defaultFormat: string; private errorFormat: string; private infoFormat: string; private warnFormat: string; constructor(private command: string) { this.defaultFormat = `${chalk.blue(`[%commandname]`)} - ${chalk.green( "%message" )}`; this.command = command; this.log(`Logger initialized for ${command}`); this.errorFormat = `${chalk.blue(`[%commandname]`)} ${chalk.bold( `${chalk.red("- ERROR -")} ${chalk.redBright("%message")}` )}`; this.infoFormat = `${chalk.blue(`[%commandname] - INFO`)} - ${chalk.green( "%message" )}`; this.warnFormat = `${chalk.blue(`[%commandname] - WARN`)} - ${chalk.yellow( "%message" )}`; } public log(message: string, bold?: boolean, format?: string): void { if (!format) format = this.defaultFormat; if (bold) message = chalk.bold(message); format = format.replace("%commandname", this.command); format = format.replace("%message", message); console.log(format); } public error(message: string): void { let format = this.errorFormat; format = format .replace("%commandname", this.command) .replace("%message", message); console.error(format); } public warn(message: string): void { let format = this.warnFormat; format = format .replace("%commandname", this.command) .replace("%message", message); console.warn(format); } public info(message: string): void { let format = this.infoFormat; format = format .replace("%commandname", this.command) .replace("%message", message); console.info(format); } }
YourBetterAssistant/yourbetterassistant
Schemas/onJoin.ts
"use strict"; import mongoose from "mongoose"; const joinroles = new mongoose.Schema({ guildId: { type: String, required: true, unique: true, }, roleId: { type: String, required: true, }, }); export default mongoose.model<Ijoinroles>("joinroles", joinroles); interface Ijoinroles extends mongoose.Document { guildId: string; roleId: string; }
YourBetterAssistant/yourbetterassistant
Utils/count.ts
import countSchema from "../Schemas/countSchema"; import mongo from "../botconfig/mongo"; import { Message } from "discord.js"; async function count(message: Message) { try { await mongo().then(async () => { let countInfo = await countSchema.findOne({ _id: message.guild?.id }); if (countInfo) { const vc = countInfo.voiceChannelID; setInterval(function () { var memberCount = message.guild?.members.cache.filter( (m) => !m.user.bot ).size; var memberCountChannel = message.guild?.channels.cache.get(vc); if (!memberCountChannel) return; memberCountChannel.setName(`${memberCount} members`); }, 1000); } }); } catch (err) { require("../handlers/errorHandler"); } } export default count;
YourBetterAssistant/yourbetterassistant
Schemas/serverConfSchema.ts
<gh_stars>0 "use strict"; import mongoose from "mongoose"; const serverConfSchema = new mongoose.Schema({ _id: { type: String, required: true, }, memberroleID: { type: String, required: true, }, adminroleID: { type: String, required: true, }, ownerroleID: { type: String, required: true, }, }); export default mongoose.model<IServerConf>( "serverConfSchema", serverConfSchema ); interface IServerConf extends mongoose.Document { _id: string; memberroleID: string; adminroleID: string; ownerroleID: string; }
YourBetterAssistant/yourbetterassistant
typings/global.d.ts
<reponame>YourBetterAssistant/yourbetterassistant import { Collection, PermissionResolvable } from "discord.js"; import { Node } from "lavaclient"; module "discord.js" { export interface Client { lavalink: Node; queue: Map<string, any>; commands: Collection<unknown, command>; aliases: Collection<unknown, unknown>; categories: string[]; cooldowns: Collection<unknown, any>; interactions: Collection<unknown, interaction>; Token: string; prefix: { [key: string]: string }; cache: { id: string; prefix: string }[]; api: any; } } module "config.json" { export const mongoPath: string; export const prefix: string; export const nodes: node[]; } type interaction = { name: string; guild: boolean; description: string; permissions: boolean; options: { type: number; name: string; description: string; required?: boolean; }[]; run: (client: Client, interaction: CommandInteraction) => void; }; type node = { id: string; host: string; port: string; password: string; }; type command = { name: string; description: string; aliases: string[]; category: string; cooldown: number; memberpermissions: PermissionResolvable; usage: string; run: (client: Client, message: Message, args: string[]) => void; }; declare module "@felipebutcher/node-os-info" { type cpu = (cpu: number) => void; type mem = (memory: number) => void; }
YourBetterAssistant/yourbetterassistant
Schemas/workSchema.ts
'use strict'; import mongoose from 'mongoose'; const workScehma=new mongoose.Schema({ userID: { type: String, required: true }, job: { type: String, required: true } }) const WorkSchema=mongoose.model<IworkSchema>('workSchema', workScehma) export default WorkSchema interface IworkSchema extends mongoose.Document{ userID:string, job:string }
YourBetterAssistant/yourbetterassistant
commands/Economy/hire.ts
"use strict"; import { Client, Message, MessageEmbed, MessageFlags } from "discord.js"; import { reply, hiremongo } from "../../exports"; import id from "../../botconfig/id.json"; module.exports = { name: "hire", description: "get a job", category: "Economy", memberpermissions: "VIEW_CHANNEL", cooldown: 60 * 60 * 2, usage: "hire", run: async (client: Client, message: Message, args: string[]) => { let embed = new MessageEmbed() .setTitle("Jobs!") .addFields( { name: "Instructions:", value: "tell me the id, just send it it chat", }, { name: "ID:1", value: "Apprentice Commoner - Salary - 1000YBCs", inline: true, }, { name: "ID:2", value: "Couple - Salary - 2000YBCs", inline: true }, { name: "ID:3", value: "Walmart Employee - Salary - 4000YBCs", inline: true, } ) .setColor("RANDOM"); message.channel.send({ embeds: [embed] }); let filter = (m: Message) => m.author.id === message.author.id; message.channel .awaitMessages({ filter, max: 1, time: 20000, errors: ["time"], }) .then(async (m) => { const msg = m.first(); if (isNaN(parseInt(msg?.content!))) return message.reply( "Not a number lost your chance try again in a couple of hours" ); if (msg?.content.startsWith("1")) { let j = id[1]; hiremongo(msg, j); } if (msg?.content.startsWith("2")) { let j = id[2]; hiremongo(msg, j); } if (msg?.content.startsWith("3")) { let j = id[3]; hiremongo(msg, j); } }) .catch((collected) => { if (collected) return; message.channel.send( "Breh The Time Ended Try Again in a couple of hours" ); }); }, };
YourBetterAssistant/yourbetterassistant
commands/Information/support.ts
"use strict"; import { Client, Message } from "discord.js"; import { reply } from "../../exports"; module.exports = { name: "support", description: "Sends support server link", category: "Information", guildOnly: true, memberpermissions: "VIEW_CHANNEL", adminPermOverride: true, cooldown: 5, usage: "support", run: async (client: Client, message: Message, args: string[]) => { const guild = await client.guilds.cache.get("879927834058043492"); //Replace the id with the support server of your bot const inv = await guild?.invites.create(guild.rulesChannelId!); //if the rules does not exist replace it with your rules channel id reply(`${inv}`, true, message); }, };
YourBetterAssistant/yourbetterassistant
slash/botinfo.ts
"use strict"; import funcs from "../handlers/functions"; const osinfo = require("@felipebutcher/node-os-info"); import packageJson from "../package.json"; import Discord, { Client, CommandInteraction } from "discord.js"; module.exports = { name: "botinfo", description: "Shows Bot Info", run: async (client: Client, interaction: CommandInteraction) => { const version = []; version.push(packageJson.version); let embed = new Discord.MessageEmbed() .setTitle("Bot-Info") .addField( "Users", `**${client.users.cache.size}** users being watched`, true ) .addField( "Servers", `${client.guilds.cache.size} servers being watched`, true ) .addField("Gateway", `${client.ws.gateway}`, true) .addField("Ping", `${client.ws.ping}ms`, true) .addField("Shards", `${client.ws.shards.size} shards being used`, true) .addField("Websocket Status", `${client.ws.status}`, true) .addField("Uptime", `${funcs.duration(client.uptime!)}`, true) .addField("Command Size", client.commands.size.toString(), true) .addField("Slash Commands Size", client.interactions.size.toString()) .addField("Version", version[0]) .addField("** **", "** **") .setColor("BLUE") .setAuthor(`Requested By ${interaction.user.username}`); osinfo.cpu((cpu: number) => { embed.addField("CPU-Load", `${Math.round(cpu * 100)}%`, true); }); osinfo.mem((memory: number) => { embed.addField("Memory Used", `${Math.round(memory * 100)}%`, true); }); await interaction.deferReply(); await interaction.editReply({ embeds: [embed] }); }, };
YourBetterAssistant/yourbetterassistant
Utils/prefix-load.ts
import { Client } from "discord.js"; import commandPrefixSchema from "../Schemas/prefixSchema"; const cache: { id: string; prefix: string }[] = []; export async function prefixLoad( client: Client, guildPrefixes: { [key: string]: string | undefined }, globalPrefix: string ) { client.cache = cache; try { /** * @param client * The Client * */ for (const guild of client.guilds.cache) { let guildID = guild[1].id; if (cache.length !== 0 && cache.length === client.guilds.cache.size) { let c = cache.find((c) => c.id == guildID); guildPrefixes[guildID] = c?.prefix; } else { const result = await commandPrefixSchema.findOne({ _id: guildID }); if (result) { guildPrefixes[guildID] = result.prefix; cache.push({ id: guildID, prefix: result.prefix }); } else { guildPrefixes[guildID] = globalPrefix; cache.push({ id: guildID, prefix: globalPrefix }); } } } } catch (err: any) { return; } } export async function clearCache() { cache.length = 0; }
YourBetterAssistant/yourbetterassistant
start.ts
<gh_stars>0 require("dotenv").config(); import axios from "axios"; const url: string[] = []; url.push(process.env.URL); async function push() { if (process.env.URL) { await axios.post( url[0], { content: ">>> Uptime For YourBetterAssistant" }, { headers: { "Content-Type": "application/json" } } ); } } push(); require("./index");
YourBetterAssistant/yourbetterassistant
commands/Games/chess.ts
<reponame>YourBetterAssistant/yourbetterassistant "use strict"; import { DiscordTogether } from "discord-together"; import { Client, Message } from "discord.js"; module.exports = { name: "chess", description: "Play chess with your buds", category: "Games", guildOnly: true, memberpermissions: "VIEW_CHANNEL", cooldown: 10, usage: "chess", run: async (client: any, message: Message) => { client.discordTogether = new DiscordTogether(client); if (!message.member?.voice.channel) return message.reply("You need to be in a VC"); client.discordTogether .createTogetherCode(message.member.voice.channel.id, "chess") .then(async (invite: { code: string }) => { if (invite.code == "https://discord.com/invite/50013") return message.channel.send( "An error occured while creating that invite, make sure I have the permission: `CREATE-INVITE` and that this channel allows me to send invites" ); else return message.channel.send(`${invite.code}`); }); }, };
YourBetterAssistant/yourbetterassistant
events/guild/voiceStateUpdate.ts
import { Client } from "discord.js"; module.exports = async (client: Client, oldState: any, newState: any) => { const server_queue = client.queue.get(oldState.guild.id); if ( server_queue && newState.id == client.user?.id && oldState.channelId && !newState.channelId ) { server_queue?.player.stop(); return (server_queue.player.queue.tracks.length = 0); } else if ( (newState.id === client.user?.id && newState.channelId && !newState.selfDeaf && !newState.serverDeaf) || (newState.id === client.user?.id && newState.channelId && !newState.serverDeaf) ) { await newState.setDeaf(true); await newState.setMute(false); } };
YourBetterAssistant/yourbetterassistant
commands/Music/play.ts
<filename>commands/Music/play.ts "use strict"; require("@lavaclient/queue/register"); import { Client, Message, MessageEmbed } from "discord.js"; module.exports = { name: "play", description: "plays music", category: "Music", memberpermissions: ["CONNECT", "SPEAK"], cooldown: 5, usage: "play <song>", run: async (client: Client, message: Message, args: string[]) => { const voice_channel = message.member?.voice.channel; if (!voice_channel) { return message.channel.send("You need to be in a voice channel"); } if (!message.guild?.me?.voice.channel) { return message.channel.send( `I am not in a voice channel do ${ client.prefix[message.guild?.id!] }join` ); } if (message.member.voice.channel.id !== message.guild.me.voice.channel.id) return message.channel.send( "You are not in the same voice channel as me, join this VC: " + `<#${message.guild.me.voice.channel.id}>` ); if (!args[0]) return message.channel.send("What song do you want me to do?"); const results = await client.lavalink.rest.loadTracks( `ytsearch:${args.join(" ")}` ); let server_queue = client.queue.get(message.guild.id); if (!server_queue) { let player = await client.lavalink.createPlayer(message.guild.id); const queue_constructor = { voice_channel: message.member.voice.channel, player, songs: [] as any[], }; //Add our key and value pair into the global queue. We then use this to get our server queue. client.queue.set(message.guild.id, queue_constructor); queue_constructor.songs.push(`${results.tracks[0].track}`); } else { client.queue.get(message.guild.id).songs.push(results.tracks[0].track); } if (!server_queue) { server_queue = client.queue.get(message.guild.id); } server_queue.player.queue.add([results.tracks[0]], { requester: message.author, }); // you can pass the requester in the second parameter if (!server_queue.player.playing) { server_queue.player.queue.start({ deaf: true }); } let embed = new MessageEmbed() .setTitle("Now Playing") .addField("Now Playing:", server_queue.player.queue.current.title) .setColor("GREEN"); if (server_queue.player.queue.tracks.length > 0) { embed.addField( "Next Song", `${server_queue.player.queue.tracks[0].title}` ); } if (server_queue.player.playing) { message.channel.send( `Added to queue: \`${results.tracks[0].info.title}\` ` ); } message.channel.send({ embeds: [embed] }); }, };
YourBetterAssistant/yourbetterassistant
commands/levels/rank.ts
<filename>commands/levels/rank.ts "use strict"; import Levels from "discord-xp"; import Discord, { Client, Message } from "discord.js"; module.exports = { name: "rank", description: "Shows the rank of the user", category: "levels", guildOnly: true, memberpermissions: "VIEW_CHANNEL", cooldown: 2, usage: "rank [user]", run: async (client: Client, message: Message) => { const canvacord = require("canvacord"); const target = message.mentions.members?.first() || message.member; // Grab the target. const user = await Levels.fetch(target?.id!, message.guild?.id!, true); // Selects the target from the database. if (!user) return message.channel.send("You don't have a level"); const rank = new canvacord.Rank() .setStatus(target?.presence ? target.presence.status : "online") // Build the Rank Card .setAvatar(target?.user.displayAvatarURL({ format: "png", size: 512 })) .setCurrentXP(user.xp) // Current User Xp .setRequiredXP(Levels.xpFor(user.level + 1)) // We calculate the required Xp for the next level .setLevel(user.level) // Current Level of the user .setProgressBar("#FFFFFF") .setUsername(target?.user.username) .setDiscriminator(target?.user.discriminator); rank.build().then((data: any) => { let attachement = new Discord.MessageAttachment(data, "Rank.png"); message.channel.send({ files: [attachement] }); }); }, };
YourBetterAssistant/yourbetterassistant
events/guild/interactionCreate.ts
"use strict"; import rrSchema from "../../Schemas/rrSchema"; import Discord, { Interaction, Client, GuildMemberRoleManager, } from "discord.js"; module.exports = async (client: Client, interaction: Interaction) => { if (interaction.isCommand()) { let cmd = client.interactions.get(interaction.commandName); if (!cmd) return; cmd.run(client, interaction); } else if (interaction.isButton()) { if (interaction.guild) { const possibleReaction = await rrSchema.findOne({ guildId: interaction.guild.id, }); if ( possibleReaction && interaction.message.id === possibleReaction.messageId ) { if (interaction.customId == possibleReaction.role1.name) { interaction.guild.roles.fetch(); const role = interaction.guild.roles.cache.get( possibleReaction.role1.id ); if ( (interaction.member?.roles as GuildMemberRoleManager).cache.get( possibleReaction.role1.id ) ) { (interaction.member?.roles as GuildMemberRoleManager).remove(role!); interaction.reply({ content: `The role ${role} has been removed from you click the button again to get it back`, ephemeral: true, }); } else { (interaction.member?.roles as GuildMemberRoleManager).add(role!); interaction.reply({ content: `The role ${role} has been added to you click the button again to lose it`, ephemeral: true, }); } } else if (interaction.customId === possibleReaction.role2.name) { interaction.guild.roles.fetch(); const role = interaction.guild.roles.cache.get( possibleReaction.role2.id ); if ( (interaction.member?.roles as GuildMemberRoleManager).cache.get( possibleReaction.role2.id ) ) { (interaction.member?.roles as GuildMemberRoleManager).remove(role!); interaction.reply({ content: `The role ${role} has been removed from you click the button again to get it back`, ephemeral: true, }); } else { (interaction.member?.roles as GuildMemberRoleManager).add(role!); interaction.reply({ content: `The role ${role} has been added to you click the button again to lose it`, ephemeral: true, }); } } } } } };
YourBetterAssistant/yourbetterassistant
commands/OWNER/servers.ts
<reponame>YourBetterAssistant/yourbetterassistant<gh_stars>0 "use strict"; import { Client, Message, MessageEmbed } from "discord.js"; module.exports = { name: "servers", aliases: ["guilds", "list-guilds"], description: "lists the guild names of all the guilds the bot is in", category: "OWNER", memberpermissions: "VIEW_CHANNEL", cooldown: 20, usage: "servers", run: async (client: Client, message: Message) => { if (message.author.id != "8<PASSWORD>") return message.channel.send("This Commnd is Not For You"); let embed = new MessageEmbed().setTitle("Servers").setColor("RANDOM"); await client.guilds.cache.forEach((guild) => { embed.addField("Server:", `${guild.name}`, true); }); const user = await client.users.fetch("827388013062389761"); user.send({ embeds: [embed] }); }, };
YourBetterAssistant/yourbetterassistant
index.ts
//Importing all needed Commands import Discord from "discord.js"; //this is the official discord.js wrapper for the Discord Api, which we use! require("dotenv").config(); import { Node } from "lavaclient"; import Logger from "./lib/logger"; require("@weky/inlinereply"); let token = process.env.TOKEN; import fs from "fs"; //this package is for reading files and getting their inputs //Creating the Discord.js Client for This Bot with some default settings ;) and with partials, so you can fetch OLD messages const client = new Discord.Client({ partials: ["USER", "CHANNEL", "GUILD_MEMBER", "MESSAGE", "REACTION"], intents: /*["GUILDS", "GUILD_MESSAGES",'GUILD_MESSAGE_REACTIONS', 'GUILD_VOICE_STATES', 'GUILD_PRESENCES', 'GUILD_MEMBERS', 'GUILD_BANS', 'GUILD_INVITES']*/ [ "GUILDS", "GUILD_MEMBERS", "GUILD_BANS", "GUILD_INTEGRATIONS", "GUILD_WEBHOOKS", "GUILD_INVITES", "GUILD_VOICE_STATES", "GUILD_PRESENCES", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS", "GUILD_MESSAGE_TYPING", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING", ], }); const clientId = process.env.NODE_ENV === "testing" ? "858606774658924555" : "862143828920369172"; const info = { host: "10.23.86.27", port: 2333, password: "<PASSWORD>" }; const lavalink = new Node({ connection: info, sendGatewayPayload: (id, payload) => client.guilds.cache.get(id)?.shard?.send(payload), }); lavalink.connect(clientId); lavalink.once("connect", () => { logger.log("Lavalink Connected!"); }); //Client variables to use everywhere const logger = new Logger("main"); client.lavalink = lavalink; client.queue = new Map(); client.commands = new Discord.Collection(); //an collection (like a digital map(database)) for all your commands client.aliases = new Discord.Collection(); //an collection for all your command-aliases client.categories = fs.readdirSync("./commands/"); //categories client.cooldowns = new Discord.Collection(); //an collection for cooldown commands of each user client.interactions = new Discord.Collection(); client.Token = token; //Loading files, with the client variable like Command Handler, Event Handler, ... ["events", "command"].forEach(async (handler) => { await require(`./handlers/${handler}`)(client); }); client.ws.on( "VOICE_STATE_UPDATE", async (data) => await lavalink.handleVoiceUpdate(data) ); client.ws.on( "VOICE_SERVER_UPDATE", async (data) => await lavalink.handleVoiceUpdate(data) ); client.login(token); /** Template by Tomato#6966 | https://github.com/Tomato6966/Discord-Js-Handler-Template */
YourBetterAssistant/yourbetterassistant
commands/Fun/snake.ts
<reponame>YourBetterAssistant/yourbetterassistant<filename>commands/Fun/snake.ts "use strict"; import { Client, Message } from "discord.js"; import { reply } from "../../exports"; module.exports = { name: "snake", description: "snake game", category: "Fun", memberpermissions: "VIEW_CHANNEL", cooldown: 5, usage: "snake", run: async (client: Client, message: Message, args: string[]) => { reply("Starting", true, message); const djsGames = require("djs-games"); const SnakeGame = new djsGames.SnakeGame(); SnakeGame.startGame(message); }, };
YourBetterAssistant/yourbetterassistant
events/guild/messageCreate.ts
<reponame>YourBetterAssistant/yourbetterassistant<filename>events/guild/messageCreate.ts "use strict"; import Levels from "discord-xp"; import count from "../../Utils/count"; import level from "../../Utils/level"; import check from "../../Utils/checkChatChannel"; import Logger from "../../lib/logger"; import Trainer from "../../lib/trainer"; import { prefixLoad, clearCache as newCache } from "../../Utils/prefix-load"; let process = require("process"); import config from "../../botconfig/config.json"; //loading config file with token and prefix, and settings import { prefix as globalPrefix } from "../../botconfig/config.json"; import ee from "../../botconfig/embed.json"; //Loading all embed settings like color footertext and icon ... import Discord, { Client, Message, TextChannel } from "discord.js"; //this is the official discord.js wrapper for the Discord Api, which we use! import funcs from "../../handlers/functions"; //Loading all needed functions Levels.setURL(config.mongoPath); import unknownCommand from "../../Schemas/unknownCommand"; import { checkAutoMod, forceNewCache as forceAutoCacheMod, } from "../../Utils/checkAutoMod"; import autoMod from "../../Constructors/autoModUser"; import levellingEnabled from "../../Schemas/levellingEnabled"; //here the event starts let prefix; const logger = new Logger("Events - MessageCreate"); module.exports = async (client: Client, message: Message) => { const automod = new autoMod(message); const guildPrefixes: { [key: string]: string } = {}; try { //if the message is not in a guild (aka in dms), return aka ignore the inputs // if the message author is a bot, return aka ignore the inputs setInterval(newCache, 3600000); setInterval(forceAutoCacheMod, 3600000); if (message.author.bot) return; //if the channel is on partial fetch it if (message.channel.partial) await message.channel.fetch(); //if the message is on partial fetch it if (message.partial) await message.fetch(); //get the current prefix from the botconfig/config.json if (!message.guild) { const embed = new Discord.MessageEmbed() .setTitle("Support DM") .setDescription(message.content) .setFooter(`Asked By ${message.author.username}`) .setColor("RED"); const owner = await client.users.fetch("827388013062389761"); owner.send(message.content + "\nAsked by " + message.author.tag); const channel = (await client.channels.fetch( "879949650415722556" )) as TextChannel; channel?.send({ embeds: [embed] }); return message.channel.send( "My DMS are for support messages only, the message sent will be forwarded to the owner and to our support server for an answer please join our server at https://discord.gg/h2YfQbKFTR" ); } Trainer(message.content); await prefixLoad(client, guildPrefixes, globalPrefix); await count(message); await check(message); await checkAutoMod(message).then(async (found) => { if (found?.strictmode === "true") { await automod.checkProfanity(); await automod.allCaps(); } else if (found?.strictmode === "false") { await automod.allCaps(); } }); if ( message.content.toLowerCase() === "ded chat" || message.content.toLowerCase() === "dead chat" ) return message.channel.send( "Good Eye Why Not Try To Start A Conversation?" ); const levelTrue = await levellingEnabled.findOne({ guildID: message.guild.id, }); if (levelTrue) { await level(message); const randomAmountOfXp = Math.floor(Math.random() * 29) + 1; // Min 1, Max 30 const hasLeveledUp = await Levels.appendXp( message.author.id, message.guild.id, randomAmountOfXp ); if (hasLeveledUp) { const user = await Levels.fetch(message.author.id, message.guild.id); message.channel.send( `${message.author}, congratulations! You have leveled up to **${user.level}**. :tada:` ); } } prefix = guildPrefixes[message.guild.id] || globalPrefix; //comment ||guildPrefixes[message.guild.id] to be able to only use b! client.prefix = guildPrefixes || globalPrefix; //the prefix can be a Mention of the Bot / The defined Prefix of the Bot const prefixRegex = new RegExp( `^(<@!?${client.user?.id}>|${funcs.escapeRegex(prefix)})\\s*` ); //if its not that then return if (!prefixRegex.test(message.content)) return; //now define the right prefix either ping or not ping const [_null, matchedPrefix] = message.content.match( prefixRegex ) as RegExpMatchArray; //create the arguments with sliceing of of the rightprefix length const args = message.content.slice(matchedPrefix.length).trim().split(/ +/); //creating the cmd argument by shifting the args by 1 const cmd = args.shift()?.toLowerCase(); //if no cmd added return error if (cmd?.length! === 0) { let embed = new Discord.MessageEmbed() .setColor("BLUE") .setFooter(ee.footertext, ee.footericon) .setTitle(`Hugh? I got pinged? Imma give you some help`) .setDescription( `To see all Commands type: \`${client.prefix[message.guild.id]}help\`` ); if (message.content.startsWith(`<@!${client.user?.id}>`)) return message.channel.send({ embeds: [embed] }); return; } //get the command from the collection let command = client.commands.get(cmd); //if the command does not exist, try to get it by his alias if (!command) command = client.commands.get(client.aliases.get(cmd)); //if the command is now valid if (command) { if (!client.cooldowns.has(command.name)) { //if its not in the cooldown, set it too there client.cooldowns.set(command.name, new Discord.Collection()); } const now = Date.now(); //get the current time const timestamps = client.cooldowns.get(command.name); //get the timestamp of the last used commands const cooldownAmount = (command.cooldown || 2) * 1000; //get the cooldownamount of the command, if there is no cooldown there will be automatically 1 sec cooldown, so you cannot spam it^^ if (timestamps.has(message.author.id)) { //if the user is on cooldown const expirationTime = timestamps.get(message.author.id) + cooldownAmount; //get the amount of time he needs to wait until he can run the cmd again if (now < expirationTime) { //if he is still on cooldonw const timeLeft = expirationTime - now; //get the lefttime let embed = new Discord.MessageEmbed() .setColor("RED") .setFooter(ee.footertext, ee.footericon) .setTitle( `❌ Please wait ${funcs.duration( timeLeft )} before reusing the \`${command.name}\` command.` ); return message.channel.send({ embeds: [embed] }); //send an information message } } timestamps.set(message.author.id, now); //if he is not on cooldown, set it to the cooldown setTimeout(() => timestamps.delete(message.author.id), cooldownAmount); //set a timeout function with the cooldown, so it gets deleted later on again try { //if Command has specific permission return error if ( command.memberpermissions && !message.member?.permissions.has(command.memberpermissions) ) { let e = new Discord.MessageEmbed() .setColor("RED") .setFooter(ee.footertext, ee.footericon) .setTitle("❌ Error | You are not allowed to run this command!") .setDescription("You Do Not Have The Required Perms!"); return message.channel.send({ embeds: [e] }).then((msg) => setTimeout(() => { msg .delete() .catch(() => logger.error("Couldn't Delete --> Ignore")); }, 1000) ); } //if the Bot has not enough permissions return error // let required_perms = ["ADD_REACTIONS","VIEW_CHANNEL","SEND_MESSAGES", // "EMBED_LINKS", "CONNECT", "SPEAK"] // if(!message.guild.me.permissions.has(required_perms)){ // try{ message.react("❌"); }catch{} // let embed=new Discord.MessageEmbed() // .setColor(ee.wrongcolor) // .setFooter(ee.footertext, ee.footericon) // .setTitle("❌ Error | I don't have enough Permissions!") // .setDescription("Please give me just `ADMINISTRATOR`, because I need it to delete Messages, Create Channel and execute all Admin Commands.\n If you don't want to give me them, then those are the exact Permissions which I need: \n> `" + required_perms.join("`, `") +"`") // message.channel.send({embeds:[embed] // }) // } //run the command with the parameters: client, message, args, user, text, prefix, command.run(client, message, args); } catch (e: any) { logger.error(e.stack); let em = new Discord.MessageEmbed() .setColor("RED") .setFooter(ee.footertext, ee.footericon) .setTitle( "❌ Something went wrong while, running the: `" + command.name + "` command" ) .setDescription(`\`\`\`${e.message}\`\`\``) .addField("Guild:", message.guild.id.toString()) .addField("GuildName", message.guild.name) .setTimestamp(new Date()); const channel = client.channels.cache.get( "889101477421912064" ) as TextChannel; message.channel.send( `Something happened while running \`${command.name}\`, This has been logged and reported to the developers` ); return channel?.send({ embeds: [em] }); } } else { //if the command is not found send an info msg const d = await unknownCommand.findOne({ guildId: message.guild.id }); if (d) { let embed = new Discord.MessageEmbed() .setColor("RED") .setFooter(ee.footertext, ee.footericon) .setTitle(`❌ Unkown command, try: **\`${prefix}help\`**`) .setDescription( `To get help on a specific command, type \`${prefix}help [command name]\`` ); const m = await message.channel.send({ embeds: [embed] }); setTimeout(function () { m.delete(); }, 2000); } } } catch (e) { const { erroHandler: err } = require("../../handlers/errorHandler"); err(e, message); } /** * @INFO * Bot Coded by Tomato#6966 | https://github.com/Tomato6966/Discord-Js-Handler-Template * @INFO * Work for Milrato Development | https://milrato.eu * @INFO * Please mention Him / Milrato Development, when using this Code! * @INFO */ };
YourBetterAssistant/yourbetterassistant
commands/Economy/leaderboard.ts
"use strict"; import money from "../../Constructors/economy"; import funcs from "../../handlers/functions"; import { Client, GuildMember, Message, MessageEmbed } from "discord.js"; const currency = new money(); module.exports = { name: "rich", description: "Currency Leaderboard first q0", category: "Economy", memberpermissions: "VIEW_CHANNEL", usage: "leaderboard", run: async (client: Client, message: Message, args: string[]) => { const { numberWithCommas } = funcs; let leaderboard = await currency.generateLeaderboard(1, message); if (leaderboard.length < 1) return message.channel.send("Nobody's on the leaderboard."); function fullUser(u: GuildMember) { return `${u.user.username}#${u.user.discriminator}`; } const embed = new MessageEmbed().setTitle(`Leaderboard`).setColor("RANDOM"); let i = 1; leaderboard.forEach((item) => { if (i >= 10) { return; } else { embed.addField( `${i++}`, `${fullUser( message.guild?.members.cache.get(item.userID)! )}:${numberWithCommas(item.coins)}YBCs` ); } }); message.channel.send({ embeds: [embed] }); }, };
YourBetterAssistant/yourbetterassistant
commands/Fun/weather.ts
"use strict"; import Discord, { Client, Message } from "discord.js"; module.exports = { name: "weather", description: "Shows the weather of a country", category: "Fun", memberpermissions: "VIEW_CHANNEL", cooldown: 5, usage: "weather <country>", run: async (client: Client, message: Message, args: string[]) => { var weather = require("weather-js"); if (!args[0]) return message.reply("Humph I quit, just tell me the country!"); let place = args.slice(0).join(" "); weather.find( { search: place, degreeType: "C" }, function (err: any, result: any) { if (err) return message.channel.send(err); try { let embed = new Discord.MessageEmbed() .setTitle(`Weather - ${result[0].location.name}`) .setColor("RANDOM") .setDescription("Temperature units can may be differ some time") .addField("Timezone", `${result[0].location.timezone}`) .addField( "Temperature", `${result[0].current.temperature} Celcius`, true ) .addField("Sky Text", result[0].current.skytext, true) .addField("Humidity", result[0].current.humidity, true) .addField("Wind Speed", result[0].current.windspeed, true) //What about image .addField( "Observation Time", result[0].current.observationtime, true ) .addField("Wind Display", result[0].current.winddisplay, true) .setThumbnail(result[0].current.imageUrl); message.channel.send({ embeds: [embed] }); } catch (err) { message.channel.send("error"); } } ); }, };
YourBetterAssistant/yourbetterassistant
events/guild/guildMemberAdd.ts
"use strict"; import { Client, GuildMember, TextChannel } from "discord.js"; import welcomeSchema from "../../Schemas/welcomeSchema"; import logSchema from "../../Schemas/logSchema"; import countSchema from "../../Schemas/countSchema"; import joinRoles from "../../Schemas/onJoin"; import mongo from "../../botconfig/mongo"; import Discord from "discord.js"; import Logger from "../../lib/logger"; const logger = new Logger("Events - GuildMemberAdd"); module.exports = async (client: Client, member: GuildMember) => { const onJoin = async (member: GuildMember) => { const guild = client.guilds.cache.get(member.guild.id); await mongo().then(async () => { try { //Look for vc await guild?.members.fetch({ force: true }); let countInfo = await countSchema.findOne({ _id: member.guild.id }); if (!countInfo) return; const vc = countInfo.voiceChannelID; setInterval(function () { var memberCount = guild?.members.cache.filter( (member) => !member.user.bot ).size; var memberCountChannel = guild?.channels.cache.get(vc); memberCountChannel?.setName(`${memberCount} members!`); }, 1000); //Member log let logInfo = await logSchema.findOne({ _id: member.guild.id }); let logChannelID = logInfo?.channelID; const logChannel = member.guild.channels.cache.get(logChannelID!); let embed = new Discord.MessageEmbed() .setTitle("New Member") .setDescription(`Our Newest Member!`) .addField("Member", `${member}`) .setColor("RANDOM"); (logChannel as TextChannel).send({ embeds: [embed] }); //Start the Welcome Message let info = await welcomeSchema.findOne({ _id: member.guild.id }); let channelID = info?.channelID; let text = info?.text; let option = info?.DM; const channel = member.guild.channels.cache.get(channelID!); if (option === "true") { member.send(`>>> <@!${member.id}> ${text}`); } else { (channel as TextChannel).send(`>>> <@!${member.id}> ${text}`); } // add roles if any const role = await joinRoles.findOne({ guildId: member.guild.id }); if (role) { member.roles.add(role.roleId, "Joined Server"); } } catch (err: any) { logger.error(`${err.stack}`); } }); }; await onJoin(member); };
YourBetterAssistant/yourbetterassistant
events/guild/guildMemberRemove.ts
"use strict"; import { Client, GuildMember, TextChannel } from "discord.js"; import countSchema from "../../Schemas/countSchema"; import Logger from "../../lib/logger"; import logSchema from "../../Schemas/logSchema"; import mongo from "../../botconfig/mongo"; import Discord from "discord.js"; const logger = new Logger("Events - GuildMemberRemove"); module.exports = async (client: Client, member: GuildMember) => { await mongo().then(async () => { try { const guild = client.guilds.cache.get(member.guild.id); let countInfo = await countSchema.findOne({ _id: member.guild.id }); const vc = countInfo?.voiceChannelID; let logInfo = await logSchema.findOne({ _id: member.guild.id }); let logChannelID = logInfo?.channelID; const logChannel = member.guild.channels.cache.get(logChannelID!); let embed = new Discord.MessageEmbed() .setTitle("Member Left") .setDescription("Goodbye person hope we see you again") .addField("Member", `${member}`) .setColor("RANDOM"); (logChannel as TextChannel).send({ embeds: [embed] }); setInterval(async function () { try { await guild?.members.fetch({ force: true }); var memberCount = guild?.members.cache.filter( (member) => !member.user.bot ).size; var memberCountChannel = guild?.channels.cache.get(vc!); memberCountChannel?.setName(`${memberCount} members!`); } catch (err) { return; } }, 1000); } catch (err: any) { logger.error(err.stack); } }); };
YourBetterAssistant/yourbetterassistant
commands/Fun/image.ts
"use strict"; import Discord, { Client, Message } from "discord.js"; import fetch from "node-fetch"; //@ts-check interface Image_Results { _type: "Images"; readLink: string; webSearchUrl: string; queryContext: Object; totalEstimatedMatches: number; nextOffset: number; currentOffset: number; value: { webSearchUrl: string; name: string; thumbnailUrl: string; datePublished: string; isFamilyFriendly: boolean; contentUrl: string; hostPageUrl: string; contentSize: string; encodingFormat: string; hostPageDisplayUrl: string; width: number; height: number; thumbnail: { width: number; height: number; }; imageInsightsToken: string; insightsMetadata: { shoppingSourcesCount: number; recipeSourcesCount: number; pagesIncludingCount: number; availableSizesCount: number; }; imageId: string; accentColor: string; }[]; queryExpansions: Object[]; pivotSuggestions: Object[]; relatedSearches: Object[]; errors?: { code: string; subCode: string; message: string; moreDetails: string; }[]; } module.exports = { name: "image", description: "displays an image searched from the web", category: "Fun", memberpermissions: ["VIEW_CHANNEL", "ATTACH_FILES"], cooldown: 10, usage: "image <query>", run: async (client: Client, message: Message, args: string[]) => { const image_query = args.join(" "); if (!image_query) return message.channel.send("Query Is Not Specified"); message.channel.send("Searching ..."); const image_results: Image_Results = (await ( await fetch( `https://api.bing.microsoft.com/v7.0/images/search?q=${image_query}&safeSearch=Strict`, { method: "GET", headers: { "Ocp-Apim-Subscription-Key": process.env.BINGAPIKEY, Accept: "application/json", }, } ) ).json()) as Image_Results; const BestImage = returnAppropriateImage(image_results); if (BestImage === undefined) return message.channel.send("No suitable image found"); let embed = new Discord.MessageEmbed() .setTitle(BestImage.name) .setURL(BestImage.contentUrl) .setImage(BestImage.thumbnailUrl); message.channel.send({ embeds: [embed] }); }, }; function returnAppropriateImage(image_results: Image_Results) { for (const image of image_results.value) { if (image.isFamilyFriendly) { return image; } else { continue; } } }
YourBetterAssistant/yourbetterassistant
commands/Information/help.ts
import { Client, Message, MessageEmbed } from "discord.js"; import config from "../../botconfig/config.json"; import ee from "../../botconfig/embed.json"; import Logger from "../../lib/logger"; const logger = new Logger("Commands - Help"); module.exports = { name: "help", description: "help command for text commands", category: "Information", guildOnly: true, memberpermissions: "VIEW_CHANNEL", cooldown: 5, usage: "help [command]", run: async (client: Client, message: Message, args: string[]) => { try { if (args[0]) { const embed = new MessageEmbed(); const cmd = client.commands.get(args[0].toLowerCase()) || client.commands.get(client.aliases.get(args[0].toLowerCase())); if (!cmd) { embed .setColor("RED") .setDescription( `No Information found for command **${args[0].toLowerCase()}**` ); return message.reply({ embeds: [embed] }); } if (cmd.name) embed.addField("**Command :**", `\`${cmd.name}\``); if (cmd.name) embed.setTitle(`Detailed Information about:\`${cmd.name}\``); if (cmd.description) embed.addField("**Description**", `\`${cmd.description}\``); if (cmd.aliases) embed.addField( "**Aliases**", `\`${cmd.aliases.map((a) => `${a}`).join("`, `")}\`` ); if (cmd.cooldown) embed.addField("**Cooldown**", `\`${cmd.cooldown} Seconds\``); else embed.addField("**Cooldown**", `\`2 Seconds\``); if (cmd.usage) { embed.addField( "**Usage**", `\`${client.prefix[message.guild?.id!] || config.prefix}${ cmd.usage }\`` ); embed.setFooter("Syntax: <> = required, [] = optional"); } if (cmd.usage) { embed.addField( "**Usage**", `\`${client.prefix[message.guild?.id!] || config.prefix}${ cmd.usage }\`` ); embed.setFooter("Syntax: <> = required, [] = optional"); } embed.setColor("BLUE"); return message.reply({ embeds: [embed] }); } else { const embed = new MessageEmbed() .setColor("BLUE") .setThumbnail(client.user?.displayAvatarURL()!) .setTitle("HELP MENU 🔰 Commands") .setFooter( `To see command descriptions and inforamtion, type: ${ client.prefix[message.guild?.id!] || config.prefix }help [CMD NAME]`, client.user?.displayAvatarURL() ); const commands = (category: any) => { return client.commands .filter((cmd) => cmd.category === category) .map((cmd) => `\`${cmd.name}\``); }; try { for (let i = 0; i < client.categories.length; i += 1) { const current = client.categories[i]; const items = commands(current); const n = 3; const result: any[] = [[], [], []]; const wordsPerLine = Math.ceil(items.length / 3); for (let line = 0; line < n; line++) { for (let i = 0; i < wordsPerLine; i++) { const value = items[i + line * wordsPerLine]; if (!value) continue; result[line].push(value); } } embed.addField( `**${current.toUpperCase()} [${items.length}]**`, `> ${result[0].join("\n> ")}`, true ); embed.addField( `\u200b`, `${result[1].join("\n") ? result[1].join("\n") : "\u200b"}`, true ); embed.addField( `\u200b`, `${result[2].join("\n") ? result[2].join("\n") : "\u200b"}`, true ); } } catch (e: any) { logger.error(String(e.stack)); } message.reply({ embeds: [embed] }); } } catch (e: any) { logger.error(String(e.stack)); let embed = new MessageEmbed() .setColor("RED") .setFooter(ee.footertext, ee.footericon) .setTitle(`❌ ERROR | An error occurred`) .setDescription(`\`\`\`${e.stack}\`\`\``); return message.reply({ embeds: [embed] }); } }, };
YourBetterAssistant/yourbetterassistant
slash/unmute.ts
<reponame>YourBetterAssistant/yourbetterassistant import { Client, CommandInteraction, GuildMember, MessageEmbed, } from "discord.js"; import serverConfSchema from "../Schemas/serverConfSchema"; const roles: { [key: string]: any } = {}; module.exports = { name: "unmute", description: "unmute", options: [{ name: "user", description: "user", type: 6, required: true }], run: async (client: Client, interaction: CommandInteraction) => { if (!interaction.guild) return; let user = interaction.options.getMember("user") as GuildMember; let result = await serverConfSchema.findOne({ _id: interaction.guild.id, }); let admin = result?.adminroleID; let member = result?.memberroleID; let owner = result?.ownerroleID; roles[interaction.guild.id] = { admin, member, owner }; let memberrole = roles[interaction.guild.id].member; if (!memberrole) return interaction.reply({ content: "I cannot unmute without a member role, please do b!serverconfig to set up `ROLES` so that i can give the user the specified roles for member when their unmute is up", ephemeral: true, }); if (!interaction?.member?.permissions.toString().includes("MANAGE_ROLES")) return interaction.reply({ content: "Invalid Permissions, Expected Perms `MANAGE_ROLES`", ephemeral: true, }); if (user.permissions.has("MANAGE_GUILD")) return interaction.reply({ content: "The user who you attempted to unmute has the permissions `MANAGE_GUILD` I am not allowed to unmute people with such permissions", ephemeral: true, }); user.roles.set([memberrole]); let embed = new MessageEmbed() .setTitle("Unmute") .setDescription(`${user}'s mute has ended`) .setColor("RANDOM"); interaction?.channel?.send({ embeds: [embed] }); }, }; //https://api.weky.xyz/canvas/whodidthis?image=${img}
YourBetterAssistant/yourbetterassistant
commands/Fun/say.ts
"use strict"; import { Client, Message, MessageEmbed } from "discord.js"; import { MessageMentions } from "discord.js"; import ee from "../../botconfig/embed.json"; import Logger from "../../lib/logger"; module.exports = { name: "say", category: "Fun", cooldown: 2, usage: "say <TEXT>", description: "Resends your Text", run: async (client: Client, message: Message, args: string[]) => { const logger = new Logger("Commands - Say"); const text = args[0]; try { if (!args[0]) return message.channel.send({ embeds: [ new MessageEmbed() .setColor("RED") .setFooter(ee.footertext, ee.footericon) .setTitle(`❌ ERROR | You didn't provided a Text`) .setDescription(`Usage: \`say <TEXT>\``), ], }); if ( MessageMentions.USERS_PATTERN.test(text) || MessageMentions.ROLES_PATTERN.test(text) ) return message.reply("I am not allowed to mention roles or users"); message.channel.send(text); } catch (e: any) { logger.error(String(e.stack)); return message.channel.send({ embeds: [ new MessageEmbed() .setColor("RED") .setFooter(ee.footertext, ee.footericon) .setTitle(`❌ ERROR | An error occurred`) .setDescription(`\`\`\`${e.stack}\`\`\``), ], }); } }, }; /** Template by Tomato#6966 | https://github.com/Tomato6966/Discord-Js-Handler-Template */
YourBetterAssistant/yourbetterassistant
commands/Economy/daily.ts
<reponame>YourBetterAssistant/yourbetterassistant "use strict"; import { Client, Message, MessageEmbed } from "discord.js"; import funcs from "../../handlers/functions"; import economySchema from "../../Schemas/economySchema"; module.exports = { name: "daily", description: "Get your daily YBCs", category: "Economy", guildOnly: true, memberpermissions: "VIEW_CHANNEL", adminPermOverride: true, cooldown: 60 * 60 * 24, usage: "daily", run: async (client: Client, message: Message, args: string[]) => { const { duration } = funcs; let db = await economySchema.findOne({ userID: message.author.id }); await economySchema.updateOne( { userID: message.author.id }, { coins: db?.coins! + 50000, } ); const embed = new MessageEmbed() .setTitle("You have gotten 50,000YBCs!") .setDescription("Redeem again in 24 hours!") .setColor("GREEN"); message.channel.send({ embeds: [embed] }); }, };
YourBetterAssistant/yourbetterassistant
commands/Information/uptime.ts
"use strict"; import { Client, Message, MessageEmbed } from "discord.js"; import ee from "../../botconfig/embed.json"; import funcs from "../../handlers/functions"; module.exports = { name: "uptime", category: "Information", aliases: [""], cooldown: 10, usage: "uptime", description: "Returns the duration on how long the Bot is online", run: async (client: Client, message: Message) => { const { duration } = funcs; try { let embed = new MessageEmbed() .setColor("BLUE") .setFooter(ee.footertext, ee.footericon) .setTitle( `:white_check_mark: **${ client.user?.username }** is since:\n ${duration(client.uptime!)} online` ); message.channel.send({ embeds: [embed] }); } catch (e: any) { let embed = new MessageEmbed() .setColor("RED") .setFooter(ee.footertext, ee.footericon) .setTitle(`❌ ERROR | An error occurred`) .setDescription(`\`\`\`${e.stack}\`\`\``); return message.channel.send({ embeds: [embed] }); } }, }; /** Template by Tomato#6966 | https://github.com/Tomato6966/Discord-Js-Handler-Template */
YourBetterAssistant/yourbetterassistant
commands/Music/join.ts
"use strict"; import { Client, Message } from "discord.js"; module.exports = { name: "join", description: "Joins a voice channel", category: "Music", guildOnly: true, memberpermissions: ["CONNECT", "SPEAK"], cooldown: 5, usage: "join", run: async (client: Client, message: Message, args: string[]) => { let server_queue = client.queue.get(message.guild?.id!); if (!server_queue) { let player = await client.lavalink.createPlayer(message.guild?.id!); const queue_constructor = { voice_channel: message.member?.voice.channel, player, songs: [] as any[], }; //Add our key and value pair into the global queue. We then use this to get our server queue. client.queue.set(message.guild?.id!, queue_constructor); } if (!server_queue) { server_queue = client.queue.get(message.guild?.id!); } const voice_channel = message.member?.voice.channel; if (!voice_channel) { return message.channel.send("You need to be in a voice channel"); } if (!message.guild?.me?.voice.channel) { server_queue.player.connect(message.member.voice.channel.id); message.reply("I have joined"); } else { return message.channel.send( "I am already in a voiceChannel join that voicechannel" ); } }, };
YourBetterAssistant/yourbetterassistant
Schemas/countSchema.ts
'use strict'; import mongoose from 'mongoose'; const countSchema=new mongoose.Schema({ _id:{ type:String, required:true }, voiceChannelID:{ type:String, required:true } }) export default mongoose.model<IcountSchema>('countSchema', countSchema) interface IcountSchema extends mongoose.Document{ _id:string, voiceChannelID:string }
YourBetterAssistant/yourbetterassistant
slash/mute.ts
import { Client, CommandInteraction, GuildMember, MessageEmbed, } from "discord.js"; import serverConfSchema from "../Schemas/serverConfSchema"; const roles: { [key: string]: { admin: string; member: string; owner: string }; } = {}; module.exports = { name: "mute", description: "Mute", options: [ { name: "user", description: "user", type: 6, required: true }, { name: "duration", description: "duration", type: 10, required: true, choices: [ { name: "1 Day", value: 86400000 }, { name: "10 hours", value: 36000000 }, { name: "5 hours", value: 18000000 }, { name: "1 Hour", value: 3600000 }, { name: "10 minutes", value: 600000 }, { name: "1 minute", value: 60000 }, ], }, { name: "reason", description: "reason", type: 3 }, ], run: async (client: Client, interaction: CommandInteraction) => { const user = interaction.options.getMember("user") as GuildMember; const reason = interaction.options.getString("reason"); const duration = interaction.options.getNumber("duration") as number; if (interaction.guild?.roles.everyone.permissions.has("SEND_MESSAGES")) return interaction.reply({ content: "The `@everyone` role has the permissions `SEND_MESSAGES` leaving this on will make muting users useless, TO fix this error un-toggle send messages for `@everyone`", ephemeral: true, }); let result = await serverConfSchema.findOne({ _id: interaction.guild?.id, }); if (!result) return interaction.reply({ content: "I cannot mute without a member role, please do b!serverconfig to set up `ROLES` so that i can give the user the specified roles for member when their mute is up", ephemeral: true, }); let admin = result.adminroleID; let member = result.memberroleID; let owner = result.ownerroleID; roles[interaction.guild?.id!] = { admin, member, owner }; let memberrole = roles[interaction.guild?.id!].member; if (!interaction.member?.permissions.toString().includes("MANAGE_ROLES")) return interaction.reply({ content: "Invalid Permissions, Expected Perms `MANAGE_ROLES`", ephemeral: true, }); if (user.permissions.has("MANAGE_GUILD")) return interaction.reply({ content: "The user who you attempted to mute has the permissions `MANAGE_GUILD` I am not allowed to mute people with such permissions", ephemeral: true, }); let muterole = interaction.guild?.roles.cache.find( (role) => role.name === "muted" ); if (!muterole) { interaction.guild?.roles .create({ name: "muted", color: "BLUE", permissions: ["VIEW_CHANNEL"], reason: "muted role does not exist", }) .catch(console.error); } user.roles.set([muterole!]); const stringedDuration = duration?.toString(); const embed = new MessageEmbed() .setTitle("Mute") .setDescription(`${user} was muted by ${interaction.member}`) .addField("Reason:", reason ? reason : "Not Specified", true) .addField( "Duration:", stringedDuration == "86400000" ? "1 Day" : stringedDuration == "36000000" ? "10 Hours" : stringedDuration === "18000000" ? "5 Hours" : stringedDuration === "3600000" ? "1 Hour" : stringedDuration === "600000" ? "10 Minutes" : stringedDuration === "60000" ? "1 Minute" : "Infinity(ERR_UNKNOWN)", true ) .setColor("RANDOM"); interaction.reply({ embeds: [embed] }); setTimeout(function () { user.roles.set([memberrole]); let embed = new MessageEmbed() .setTitle("Unmute") .setDescription( `${user}'s mute has ended. The mute lasted ${ stringedDuration == "86400000" ? "1 Day" : stringedDuration == "36000000" ? "10 Hours" : stringedDuration === "18000000" ? "5 Hours" : stringedDuration === "3600000" ? "1 Hour" : stringedDuration === "600000" ? "10 Minutes" : stringedDuration === "60000" ? "1 Minute" : "Infinity(ERR_UNKNOWN)" }` ) .setColor("RANDOM"); interaction.channel?.send({ embeds: [embed] }); }, duration); }, };
YourBetterAssistant/yourbetterassistant
commands/Information/roleinfo.ts
import { Client, Message, MessageEmbed } from "discord.js"; module.exports = { name: "roleinfo", description: "Shows Information About a Role", category: "Information", memberpermissions: ["VIEW_CHANNEL"], cooldown: 2, usage: "roleinfo <role mentioned or typed>", run: async (client: Client, message: Message, args: string[]) => { if (!args[0]) return message.reply("Role Was Not Specified"); else { const embed = new MessageEmbed(); if (message.mentions.roles.first()) { const role = message.mentions.roles.first(); embed .setTitle("Role Information for " + `${role?.name}`) .addField("Name", role?.name!, true) .addField("ID", role?.id.toString()!, true) .addField("Created At", `<t:${role?.createdTimestamp}:R>`, true) .addField("Color", role?.color?.toString()!, true) .addField("Display Seperate", role?.hoist ? "Yes" : "No", true) .addField( "Members Who Have This Role", role?.members.size.toString()!, true ) .addField("Mentionable", role?.mentionable ? "Yes" : "No", true); embed .setColor("LUMINOUS_VIVID_PINK") .setFooter(`Requested By ${message.author.tag}`); message.reply({ embeds: [embed] }); } else { const roleToBeFound = args.join(" ").toLowerCase(); const role = message.guild?.roles.cache.find( (r) => r.name.toLowerCase() === roleToBeFound ); if (!role) return message.channel.send("Invalid Role"); else { embed .setTitle("Role Information for " + `${role.name}`) .addField("Name", role.name, true) .addField("ID", role.id.toString(), true) .addField( "Created At", `<t:${Math.floor(role.createdTimestamp / 1000)}:R>`, true ) .addField("Color", role.color.toString(), true) .addField("Display Seperate", role.hoist ? "Yes" : "No", true) .addField( "Members Who Have This Role", role.members.size.toString(), true ) .addField("Mentionable", role.mentionable ? "Yes" : "No", true); embed .setColor("LUMINOUS_VIVID_PINK") .setFooter(`Requested By ${message.author.tag}`); message.reply({ embeds: [embed] }); } } } }, };
YourBetterAssistant/yourbetterassistant
commands/Administration/serverconfig.ts
<filename>commands/Administration/serverconfig.ts "use strict"; import { Client, Message } from "discord.js"; module.exports = { name: "serverconfig", description: "DEPRECATED USE WEBSITE", category: "Administration", memberpermissions: "MANAGE_GUILD", run: async (client: Client, message: Message, args: string[]) => { message.channel.send( "This command is deprecated please use the website https://yourbetterassistant.me" ); }, };
YourBetterAssistant/yourbetterassistant
typings/enviroment.d.ts
declare namespace NodeJS { interface ProcessEnv { TOKEN: string; URL: string; TOPGGTOKEN: string; APISECRET: string; BINGAPIKEY: string; } }
YourBetterAssistant/yourbetterassistant
Constructors/economy.ts
import mongo from "../botconfig/mongo"; import economySchema from "../Schemas/economySchema"; import errHandler from "../handlers/errorHandler"; import inventory from "../Schemas/inventory"; import { Message } from "discord.js"; async function createUser( userID: string, coins: number, bank: number, bs: number ) { /** * @param userID nothing much lol */ await mongo().then(async () => { try { await economySchema.findOneAndUpdate( { userID: userID }, { userID: userID, coins: coins, bank: bank, bankSpace: bs }, { upsert: true } ); await inventory.findOneAndUpdate( { userId: userID }, { inventory: [] }, { upsert: true } ); } catch (err: any) { errHandler(err); } }); //code } class economy { /** * @param userID * id of the the user * @param coins * the amoutn of coins to be added */ async donate(userID: string, coins: number, message: Message) { await mongo().then(async () => { try { let f = await economySchema.findOne({ userID: userID }); let u = await economySchema.findOne({ userID: message.author.id }); if (!f) { message.channel.send( "That user doesn't have a economy account. I have made him an account and also added the coins needed" ); createUser(userID, 10000 + coins, 0, 1000); } else if (!u) { message.channel.send( "Sorry mate no account found, I'll make you an account but you can't give your friend the money" ); createUser(message.author.id, 10000 + coins, 0, 1000); } else { message.channel.send("Transaction Processeing").then(async (msg) => { msg.edit({ content: "Transcation Approved" }); await this.addCoins(userID, coins); await this.deductCoins(message.author.id, coins); }); } } catch (err: any) { errHandler(err, message); } }); } async addCoins(userID: string, coins: number) { let ua = await economySchema.findOne({ userID: userID }); if (!ua) return await createUser(userID, 10000 + coins, 10000, 10000); let ec = ua.coins; await economySchema.updateOne({ userID: userID }, { coins: ec + coins }); } async deductCoins(userID: string, coins: number) { let ua = await economySchema.findOne({ userID: userID }); if (!ua) return await createUser(userID, 10000, 10000, 10000); let ec = ua.coins; if (ec < coins) return false; await createUser(userID, ec - coins, ua.bank, ua.bankSpace); return true; } async deposit( userID: string, coins: number | "all" | "max" | "." | "*", message: Message ) { let msg = await message.channel.send("Transaction Processing..."); let ua = await economySchema.findOne({ userID: userID }); if (!ua) { await createUser(userID, 10000, 10000, 10000); } let bank = ua?.bank as number; let bankSpace = ua?.bankSpace as number; if (coins === "all" || coins === "max" || coins === "." || coins === "*") { coins = ua?.coins as number; } let tot = coins + bank!; if (tot > bankSpace) { msg.edit("Transaction Failed :x:"); let cb = coins - bankSpace; message.channel.send( `I am sorry but the amount of coins to be deposited cannot be deposited\nas you don't have enough bank space\nYBCs to be deposited:${ coins - bankSpace }` ); this.deductCoins(userID, cb); this.addMoneyBank(userID, cb); return; } msg.edit("Transaction Success ✔️"); this.deductCoins(userID, coins); this.addMoneyBank(userID, coins + bank); } async withdraw( userID: string, coins: number | "all" | "max" | "." | "*", message: Message ) { let msg = await message.channel.send("Transaction Processing"); let ua = await economySchema.findOne({ userID: userID }); if (!ua) { await createUser(userID, 10000, 10000, 10000); return; } let bank = ua.bank; let bankSpace = ua.bankSpace; if (coins === "all" || coins === "max" || coins === "." || coins === "*") { coins = ua.bank; } let tot = bank - coins; if (tot < 0) { msg.edit("Transaction Failed :x:"); let cb = coins - bankSpace; message.channel.send(`Your taking more money then you own.`); return; } msg.edit("Transaction Success✔️"); await this.addCoins(userID, coins); await this.removeMoneyBank(userID, coins); } async addMoneyBank(userID: string, coins: number) { let ua = await economySchema.findOne({ userID: userID }); if (!ua) return await createUser(userID, 10000, 10000, 10000); let eb = ua.bank; await economySchema.updateOne({ userID }, { bank: eb + coins }); } async removeMoneyBank(userID: string, coins: number) { let ua = await economySchema.findOne({ userID: userID }); if (!ua) return await createUser(userID, 10000, 10000, 10000); let eb = ua.bank; await economySchema.updateOne({ userID }, { bank: eb - coins }); } async increaseBankSpace(userID: string, coins: number) { let ua = await economySchema.findOne({ userID: userID }); if (!ua) return await createUser(userID, 10000, 10000, 10000); let ec = ua.coins; let eb = ua.bankSpace; await economySchema.updateOne({ userID }, { bankSpace: eb + coins }); } async decreaseBankSpace(userID: string, coins: number) { let ua = await economySchema.findOne({ userID: userID }); if (!ua) return await createUser(userID, 10000, 10000, 10000); let ec = ua.coins; let eb = ua.bankSpace; await economySchema.updateOne({ userID }, { bankSpace: eb - coins }); } async createUser(userID: string, coins: number, bank: number, bs: number) { await createUser(userID, coins, bank, bs); } async findUser(userID: string) { return await economySchema.findOne({ userID: userID }); } async generateLeaderboard(amount: number, message: Message) { const filter = {}; const allUsers = await economySchema.find(filter); let similarUsers: { userID: string; coins: number }[] = []; allUsers.forEach((result) => { message.guild?.members.cache.get(result.userID) ? similarUsers.push({ userID: result.userID, coins: result.coins }) : null; }); function compare(b: { coins: number }, a: { coins: number }) { if (a.coins < b.coins) { return -1; } if (a.coins > b.coins) { return 1; } return 0; } let done = similarUsers.sort(compare); return done; } } export default economy;
YourBetterAssistant/yourbetterassistant
Schemas/prefixSchema.ts
<filename>Schemas/prefixSchema.ts<gh_stars>0 "use strict"; import mongoose from "mongoose"; const commandPrefixSchema = new mongoose.Schema({ _id: { type: String, required: true, }, prefix: { type: String, required: true, }, }); const PrefixSchema = mongoose.model<IprefixSchema>( "guild-prefixes", commandPrefixSchema ); export default PrefixSchema; interface IprefixSchema extends mongoose.Document { _id: string; prefix: string; }
YourBetterAssistant/yourbetterassistant
commands/Economy/bal.ts
"use strict"; import money from "../../Constructors/economy"; import Discord, { Client, Message } from "discord.js"; import { reply } from "../../exports"; const currency = new money(); module.exports = { name: "bal", aliases: ["balance"], description: "shows your balance", category: "Economy", memberpermissions: "VIEW_CHANNEL", cooldown: 5, usage: "bal [user]", run: async (client: Client, message: Message, args: string[]) => { let member = message.mentions?.members?.first(); if (!args[0]) { let member = message.author; const user = await currency.findUser(member.id); // Get the user from the database. if (!user) { await currency.createUser(member.id, 10000, 10000, 10000); reply( "A new account has been created for you with a balance of 1000YBCs", true, message ); await currency.addCoins(member.id, 10000); return; } const embed = new Discord.MessageEmbed(); embed.setTitle(`Your Balance`); embed.addFields( { name: "Wallet", value: `${user.coins}` }, { name: "Bank", value: `${user.bank}/${user.bankSpace}` }, { name: "Total", value: `${user.coins + user.bank}` } ); embed.setColor("RANDOM"); message.channel.send({ embeds: [embed] }); } else { const user = await currency.findUser(member?.id!); // Get the user from the database. if (!user) { await currency.createUser(member?.id!, 10000, 10000, 10000); let mony = "10,000"; message.reply( `A new account has been created for you with a balance of ${mony}YBCs` ); return; } const embed = new Discord.MessageEmbed() .setTitle(`${member?.user.username}'s Balance`) .addFields( { name: "Wallet", value: `${user.coins}`, inline: true }, { name: "Bank", value: `${user.bank}/${user.bankSpace}`, inline: true, }, { name: "Total", value: `${user.bank + user.coins}`, inline: true } ) .setColor("RANDOM"); message.reply({ embeds: [embed] }); } }, };
YourBetterAssistant/yourbetterassistant
events/client/disconnect.ts
"use strict"; //here the event starts module.exports = () => { console.log(`You have been disconnected at ${new Date()}.`.red); }; /** Template by Tomato#6966 | https://github.com/Tomato6966/Discord-Js-Handler-Template */
YourBetterAssistant/yourbetterassistant
Schemas/autoMod.ts
<filename>Schemas/autoMod.ts 'use strict'; import mongoose from 'mongoose'; const automod=new mongoose.Schema({ guildId: { type: String, required: true }, strictMode: { type: Boolean, required: true } }) export interface IUser extends mongoose.Document { guildId:string, strictMode:boolean }; const model=mongoose.model<IUser>('autoMod',automod) export default model
YourBetterAssistant/yourbetterassistant
commands/Fun/gtn.ts
"use strict"; import { Client, Message } from "discord.js"; import { reply } from "../../exports"; const djsGames = require("djs-games"); module.exports = { name: "gtn", aliases: ["guessthenumber"], description: "guess the number game", memberpermissions: "VIEW_CHANNEL", adminPermOverride: true, cooldown: 2, usage: "gtn", run: async (client: Client, message: Message, args: string[]) => { reply("Starting Game", true, message); const guessTheNumber = new djsGames.GuessTheNumber(); guessTheNumber.startGame(message); }, };
YourBetterAssistant/yourbetterassistant
exports.ts
<gh_stars>0 import workSchema from "./Schemas/workSchema"; import mongo from "./botconfig/mongo"; import errHandler from "./handlers/errorHandler"; import { Message } from "discord.js"; /** * @param content what the message is * @param mention type in true or false this determines if you are pinging the member or not * @param message The message paramater * */ export function reply(content: string, mention: boolean, message: Message) { message.reply({ content: content, allowedMentions: { repliedUser: mention }, }); } /** * @param msg message * @param j job * */ export async function hiremongo(msg: Message, j: string) { await mongo().then(async () => { try { await workSchema.findOneAndUpdate( { userID: msg.author.id, }, { userID: msg.author.id, job: j, }, { upsert: true } ); msg.channel.send(`Your job is now ${j}`); } catch (err: any) { errHandler(err, msg); } }); }
YourBetterAssistant/yourbetterassistant
slash/clear.ts
import { Client, CommandInteraction } from "discord.js"; module.exports = { name: "clear", description: "Mass Clear Messages", options: [ { type: 10, name: "limit", description: "Number of messages to clear", required: true, }, ], run: async (client: Client, interaction: CommandInteraction) => { if (!interaction.memberPermissions?.has("MANAGE_MESSAGES")) { return interaction.reply({ content: "Misisng Perms: `MANAGE_MESSAGES`", ephemeral: true, }); } const limit = interaction.options.getNumber("limit") as number; if (limit > 100) return interaction.reply({ content: "You can't remove more than 100 messages!", ephemeral: true, }); if (limit < 1) return interaction.reply({ content: "You have to delete at least one message!", ephemeral: true, }); try { await interaction.channel?.messages .fetch({ limit }) .then(async (messages) => { if (interaction.channel?.type === "DM") return; await interaction.channel?.bulkDelete(messages); }); } catch (err) { return interaction.reply({ content: `An Error Occured! These are the possible reasons, \n 1. Message is older than 14 days \n 2. I don't have the permission \`MANAGE_MESSAGES\` \n 3. If those don't work file a bug report in the support server`, ephemeral: true, }); } interaction.reply({ content: `Successfully deleted ${limit} messages!`, ephemeral: true, }); }, };
YourBetterAssistant/yourbetterassistant
commands/Fun/mcserver.ts
<reponame>YourBetterAssistant/yourbetterassistant<filename>commands/Fun/mcserver.ts<gh_stars>0 "use strict"; import util from "minecraft-server-util"; import Discord, { Client, Message } from "discord.js"; module.exports = { name: "mcserver", aliases: ["miencraft", "server"], description: "Display stats bout teh server you asked for", category: "Fun", cooldown: 2, usage: "mcserver <ip> <port>", run: async (client: Client, message: Message, args: string[]) => { if (!args[0]) return message.channel.send("the server ip mate"); if (!args[1]) return message.channel.send("and the port(normally 25565)"); const ip = args[0]; const port = parseInt(args[1]); util .status(ip, port) .then((response) => { const embed = new Discord.MessageEmbed() .setColor("#00F5D4") .setTitle("MC SERVER RESULTS!") .addFields( { name: "Players Online:", value: `${response.players.online}/${response.players.max}`, inline: true, }, { name: "Version Required:", value: response.version.name, inline: true, }, { name: "Description:", value: response.motd.raw, inline: true, }, { name: "Max Players:", value: `${response.players.max}`, inline: true, } ); message.channel.send({ embeds: [embed] }); }) .catch((error) => { message.channel.send("Something Happened"); throw error; }); }, };
YourBetterAssistant/yourbetterassistant
commands/Fun/profilep.ts
"use strict"; import Discord, { Client, Message } from "discord.js"; module.exports = { name: "profilepic", category: "Fun", cooldown: 1, aliases: ["picture", "av", "avatar"], usage: "profilepic <username>", description: "gets the profile pic of the person asked", run: async (client: Client, message: Message, args: string[]) => { let embed = new Discord.MessageEmbed().setColor("RANDOM"); if (!args[0]) { embed .setImage(message.author.displayAvatarURL()) .setTitle(`${message.author.username}'s Profile Image`); message.channel.send({ embeds: [embed] }); } else if (args[0]) { let user = message.mentions.users.first(); embed.setImage(user?.displayAvatarURL()!).setTitle(`Profile Image`); message.channel.send({ embeds: [embed] }); } }, };
YourBetterAssistant/yourbetterassistant
slash/vr.ts
"use strict"; import { Client, CommandInteraction, MessageEmbed } from "discord.js"; module.exports = { name: "vr", description: "VR", options: [{ name: "user", description: "user", type: 6 }], run: async (client: Client, interaction: CommandInteraction) => { let user = interaction.options.getUser("user"); const embed = new MessageEmbed().setTitle("VR").setColor("GREEN"); if (!user) { let img = interaction.user.displayAvatarURL(); img = img.replace(".webp", ".png"); embed.setImage(`https://api.weky.xyz/canvas/vr?image=${img}`); interaction.reply({ embeds: [embed] }); return; } else { let img = user.displayAvatarURL(); img = img.replace(".webp", ".png"); embed.setImage(`https://api.weky.xyz/canvas/vr?image=${img}`); interaction.reply({ embeds: [embed] }); } }, }; //https://api.weky.xyz/canvas/whodidthis?image=${img}
YourBetterAssistant/yourbetterassistant
commands/Information/invitelink.ts
<filename>commands/Information/invitelink.ts "use strict"; import Discord, { Client, Message } from "discord.js"; module.exports = { name: "invitelink", aliases: ["invite", "link"], description: "sends the invitelink of the bot", category: "Information", memberpermissions: "VIEW_CHANNEL", cooldown: 2, usage: "invitelink", run: async (client: Client, message: Message, args: string[]) => { const embed = new Discord.MessageEmbed() .setTitle("InviteLink") .setFooter("YourBetterAssistant") .setURL("https://dsc.gg/betterassistant") .setColor("AQUA"); message.channel.send({ embeds: [embed] }); }, };
YourBetterAssistant/yourbetterassistant
handlers/command.ts
<filename>handlers/command.ts<gh_stars>0 "use strict"; import { Client, Message } from "discord.js"; import color from "chalk"; import { readdirSync } from "fs"; import Table from "cli-table"; import logger from "../lib/logger"; import { command, interaction } from "../typings/global"; const commandtable = new Table(); const slashtable = new Table(); module.exports = async function (client: Client) { const Logger = new logger("Handler - Command"); Logger.info(color.bold(color.green("Starting Command Handler... \n"))); commandtable.push([ color.bold(color.green("Command")), color.bold(color.green("Category")), color.bold(color.green("Description")), ]); slashtable.push([ color.bold(color.red("Slash-Command")), color.bold(color.red("Description")), ]); Logger.log(color.cyan("Text-Commands")); readdirSync("dist/commands/").forEach((dir: string) => { const commands = readdirSync(`./dist/commands/${dir}/`).filter((file) => file.endsWith(".js") ); for (const file of commands) { const command: command = require(`../commands/${dir}/${file}`); const commandName = command.name; commandtable.push([ color.blue(commandName.toString()), color.bgCyan(dir), color.red(command.description.toString()), ]); client.commands.set(commandName, command); continue; } }); console.log(commandtable.toString() + "\n"); Logger.log(color.blue("Slash-Commands")); const commands = readdirSync("dist/slash"); for (const file of commands) { const command: interaction = require(`../slash/${file}`); slashtable.push([ color.blue(command.name), color.yellow(command.description), ]); client.interactions.set(command.name, command); } console.log(slashtable.toString()); }; // /** Template by Tomato#6966 | https://github.com/Tomato6966/Discord-Js-Handler-Template */
YourBetterAssistant/yourbetterassistant
Schemas/inventory.ts
'use strict'; import mongoose from 'mongoose'; const inventory=new mongoose.Schema({ userId: { type: String, required: true, }, inventory: { type: Array, required: true, } }) const Inventory=mongoose.model<Iinventory>('inventory', inventory) export default Inventory interface Iinventory extends mongoose.Document{ userId:string, inventory:Array<string> }
YourBetterAssistant/yourbetterassistant
handlers/functions.ts
<reponame>YourBetterAssistant/yourbetterassistant<gh_stars>0 "use strict"; import { GuildMemberManager, Message, User } from "discord.js"; export default { duration: function (ms: number) { const sec = Math.floor((ms / 1000) % 60).toString(); const min = Math.floor((ms / (60 * 1000)) % 60).toString(); const hrs = Math.floor((ms / (60 * 60 * 1000)) % 60).toString(); const days = Math.floor((ms / (24 * 60 * 60 * 1000)) % 60).toString(); return `\`${days}Days\`,\`${hrs}Hours\`,\`${min}Minutes\`,\`${sec}Seconds\``; }, secondsToHMS: function secondsToHms(d: number) { d = Number(d); var h = Math.floor(d / 3600); var m = Math.floor((d % 3600) / 60); var s = Math.floor((d % 3600) % 60); var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : ""; var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : ""; var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : ""; return hDisplay + mDisplay + sDisplay; }, //get a member lol getMember: function (message: Message, toFind = "") { try { toFind = toFind.toLowerCase(); let target = (message.guild?.members as GuildMemberManager).cache.get( toFind ); if (!target && message.mentions.members) target = message.mentions.members.first(); if (!target && toFind) { target = message.guild?.members.cache.find((member) => { return ( member.displayName.toLowerCase().includes(toFind) || member.user.tag.toLowerCase().includes(toFind) ); }); } if (!target) target = message.member!; return target; } catch (e: any) { console.log(e.stack); } }, //Function to wait some time delay: function (delayInms: number) { try { return new Promise((resolve) => { setTimeout(() => { resolve(2); }, delayInms); }); } catch (e: any) { console.log(String(e.stack)); } }, //randomnumber between 0 and x escapeRegex: function (str: string) { try { return str.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`); } catch (e: any) { console.log(String(e.stack)); } }, getPrettyDate: function () { var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ]; var d = new Date(); var day = days[d.getDay()]; var hr = d.getHours(); var min = d.getMinutes(); if (min < 10) { min = 0 + min; } var ampm = "am"; if (hr > 12) { hr -= 12; ampm = "pm"; } var date = d.getDate(); var month = months[d.getMonth()]; var year = d.getFullYear(); const time = day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year; return time; }, numberWithCommas: function (x: number) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }, }; /** Template by Tomato#6966 | https://github.com/Tomato6966/Discord-Js-Handler-Template */
YourBetterAssistant/yourbetterassistant
Schemas/logSchema.ts
"use strict"; import mongoose from "mongoose"; const logSchema = new mongoose.Schema({ _id: { type: String, required: true, }, channelID: { type: String, required: true, }, }); export default mongoose.model<IlogSchema>("logschemas", logSchema); interface IlogSchema extends mongoose.Document { _id: string; channelID: string; }
YourBetterAssistant/yourbetterassistant
commands/levels/leaderboard.ts
"use strict"; import Levels from "discord-xp"; import { Client, Message, MessageEmbed } from "discord.js"; module.exports = { name: "leaderboard", description: "Shows the leaderboard", category: "levels", guildOnly: true, memberpermissions: "VIEW_CHANNEL", cooldown: 2, usage: "leaderboard", run: async (client: Client, message: Message) => { const rawLeaderboard = await Levels.fetchLeaderboard( message.guild?.id!, 10 ); // We grab top 10 users with most xp in the current server. if (rawLeaderboard.length < 1) return message.reply("Nobody's in leaderboard yet."); const leaderboard = await Levels.computeLeaderboard( client, rawLeaderboard, true ); // We process the leaderboard. const lb = leaderboard.map( (e) => `${e.position}. ${e.username}#${e.discriminator}\nLevel: ${ e.level }\nXP: ${e.xp.toLocaleString()}` ); // We map the outputs. let embed = new MessageEmbed() .setTitle("Leaderboard") .setDescription(`**Leaderboard**:\n\n${lb.join("\n\n")}`) .setColor("RANDOM"); message.channel.send({ embeds: [embed] }); }, };