Skip to content

TypeError: nsfwjs.load is not a functions #879

@GhostWasFound13

Description

@GhostWasFound13

My code is following a error idk the issue its

import {
  Client,
  GatewayIntentBits,
  Collection,
  ColorResolvable,
} from "discord.js";
import db from "best.db";
import Replicate from "replicate";
import { ConfigDataService } from "./services/ConfigDataService.js";
import { LoggerService } from "./services/LoggerService.js";
import { ClusterClient, getInfo } from "discord-hybrid-sharding";
import { Metadata } from "./@types/Metadata.js";
import { ManifestService } from "./services/ManifestService.js";
import { PrefixCommand, SlashCommand } from "./@types/Command.js";
import { Config } from "./@types/Config.js";
import { config } from "dotenv";
import { initHandler } from "./handlers/index.js";
import utils from "node:util";
import { Canvas } from "./services/plugin/CanvaService.js";
import { DeployService } from "./services/DeployService.js";
import * as tf from "@tensorflow/tfjs-node"; // Import TensorFlow for image decoding
import * as nsfwjs from "nsfwjs";
config();

const loggerService = new LoggerService().init();
const configData = new ConfigDataService().data;

loggerService.info("Booting client...");

interface NSFWPrediction {
  className: string;
  probability: number;
}

export class Manager extends Client {
  db!: QuickDB;
  token: string;
  canvas: Canvas;
  replicate: Replicate | null;
  metadata: Metadata;
  config: Config;
  logger: any;
  owner: string;
  color: ColorResolvable;
  prefix: string;
  shard_status: boolean;
  slash: Collection<string, SlashCommand>;
  commands: Collection<string, PrefixCommand>;
  aliases: Collection<string, string>;
  cluster?: ClusterClient<Client>;
  nsfwModel: nsfw.NSFWJS | null = null;

  constructor() {
    super({
      shards: process.env.IS_SHARING == "true" ? getInfo().SHARD_LIST : "auto",
      shardCount: process.env.IS_SHARING == "true" ? getInfo().TOTAL_SHARDS : 1,
      allowedMentions: {
        parse: ["roles", "users", "everyone"],
        repliedUser: false,
      },
      intents: configData.features.MESSAGE_CONTENT.enable
        ? [
            GatewayIntentBits.Guilds,
            GatewayIntentBits.GuildVoiceStates,
            GatewayIntentBits.GuildMessages,
            GatewayIntentBits.MessageContent,
          ]
        : [
            GatewayIntentBits.Guilds,
            GatewayIntentBits.GuildVoiceStates,
            GatewayIntentBits.GuildMessages,
          ],
    });

    this.logger = loggerService;
    this.config = configData;
    this.metadata = new ManifestService().data.metadata.bot;
    
    
    this.token = this.config.bot.TOKEN;
    this.owner = this.config.bot.OWNER_ID;
    this.color = (this.config.bot.EMBED_COLOR || "#2b2d31") as ColorResolvable;
    this.prefix = this.config.features.MESSAGE_CONTENT.commands.prefix || "d!";

    this.shard_status = false;
    this.canvas = new Canvas();
    this.slash = new Collection();
    this.commands = new Collection();
    this.aliases = new Collection();

    this.replicate = new Replicate({
      auth: process.env.replicateToken,
    });
    if (!this.replicate) {
      this.logger.error("Failed to initialize Replicate.");
      return;
    }

    

    
    this.db = db;

    this.cluster =
      process.env.IS_SHARING == "true" ? new ClusterClient(this) : undefined;

    process.on("unhandledRejection", (error) =>
      this.logger.log({ level: "error", message: utils.inspect(error) })
    );
    process.on("uncaughtException", (error) =>
      this.logger.log({ level: "error", message: utils.inspect(error) })
    );

    new DeployService(this);
    new initHandler(this);
    this.initializeNSFWModel();
  }

  async initializeNSFWModel() {
    this.nsfwModel = await nsfwjs.load();
  }

  async isNSFW(imageBuffer: Buffer): Promise<boolean> {
    if (!this.nsfwModel) return false;

    const imageTensor = tf.node.decodeImage(imageBuffer); // Decode the image
    const squeezedTensor = imageTensor.squeeze(); // Remove unnecessary dimensions

    // Make sure squeezedTensor has 4 dimensions
    // If necessary, add dimensions:
    const reshapedTensor = squeezedTensor.reshape([
      1,
      squeezedTensor.shape[0] ?? 0,
      squeezedTensor.shape[1] ?? 0,
      3,
    ]);

    const predictions = await this.nsfwModel.classify(
      reshapedTensor as tf.Tensor3D
    );

    return predictions.some(
      (prediction: NSFWPrediction) =>
        prediction.className === "Porn" && prediction.probability > 0.7
    );
  }

  connect() {
    super.login(this.token);
  }
}

Error console

Run echo "Starting bot
Starting the bot
npm warn config only Use `--omit=dev` to omit dev dependencies from the install.

> byteblaze@1.0.0 start:docker
> tsx ./src/index.ts

2024-08-10 00:01:20.987480: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
10-08-2024 12:01:21:037 - INFO         - Booting client...
10-08-2024 12:01:21:1[5](https://github.com/GhostWasFound13/DogeBot/actions/runs/10327189522/job/28591956844#step:5:6)7 - DEPLOY_SLASH - Reading interaction files...
10-08-2024 12:01:21:195 - ERROR        - TypeError: nsfwjs.load is not a function
    at Manager.initializeNSFWModel (file:///home/runner/work/DogeBot/DogeBot/src/manager.ts:120:35)
    at new Manager (file:///home/runner/work/DogeBot/DogeBot/src/manager.ts:11[6](https://github.com/GhostWasFound13/DogeBot/actions/runs/10327189522/job/28591956844#step:5:7):10)
    at file:///home/runner/work/DogeBot/DogeBot/src/index.ts:2:16
    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
    at ModuleLoader.import (node:internal/modules/esm/loader:323:24)
    at loadESM (node:internal/process/esm_loader:28:[7](https://github.com/GhostWasFound13/DogeBot/actions/runs/10327189522/job/28591956844#step:5:8))
    at handleMainPromise (node:internal/modules/run_main:120:12)
{
  level: 'error',
  message: 'TypeError: nsfwjs.load is not a function\n' +
    '    at Manager.initializeNSFWModel (file:///home/runner/work/DogeBot/DogeBot/src/manager.ts:120:35)\n' +
    '    at new Manager (file:///home/runner/work/DogeBot/DogeBot/src/manager.ts:116:10)\n' +
    '    at file:///home/runner/work/DogeBot/DogeBot/src/index.ts:2:16\n' +
    '    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)\n' +
    '    at ModuleLoader.import (node:internal/modules/esm/loader:323:24)\n' +
    '    at loadESM (node:internal/process/esm_loader:2[8](https://github.com/GhostWasFound13/DogeBot/actions/runs/10327189522/job/28591956844#step:5:9):7)\n' +
    '    at handleMainPromise (node:internal/modules/run_main:120:12)',
  timestamp: '10-08-2024 12:01:21:1[9](https://github.com/GhostWasFound13/DogeBot/actions/runs/10327189522/job/28591956844#step:5:10)6'
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions