codigoencasa / builderbot

🤖 Crear Chatbot WhatsApp en minutos. Únete a este proyecto OpenSource
https://www.builderbot.app
MIT License
2.41k stars 826 forks source link

Add support to TypeScript! #610

Closed binhodev closed 11 months ago

binhodev commented 1 year ago

¿Que versión estas usando?

v2

¿Sobre que afecta?

Otro

Describe tu problema

Hello everything is fine?

Is a version of the code planned for TypeScript?

Reproducir error

No response

Información Adicional

No response

leifermendez commented 1 year ago

@silvinhofranca everything ok! Yes we are working on a typescript version https://github.com/codigoencasa/bot-whatsapp/tree/feat/typescript

binhodev commented 1 year ago

Hello @leifermendez! Hmm, I'll check. Gracias!

jhonatanmacazana commented 1 year ago

Hey, I am interested in this project and I would love for it to have proper types. I would like to know if there's room for adding types in your roadmap.

If it's possible, I would be thrilled to work in a PR to add this.

I am asking because I saw that the other PR wasn't merge, but just closed after a while.

edgarvaldez99 commented 1 year ago

Hola a todos, ya tenemos template para typescript ?

leifermendez commented 1 year ago

Hola a todos, ya tenemos template para typescript ?

Aun oficialmente no tenemos pero si tu tienes un proyecto ocn TS puedes perfectamente implementarlo te dejo un ejemplo en un codigo TS que lo uso

import "dotenv/config";
import BotWhatsapp from "@bot-whatsapp/bot";
import MockAdapter from "@bot-whatsapp/database/mock";
import BaileysProvider from "@bot-whatsapp/provider/baileys";
import loadFlows from "./flows";
import AiSerivce from "./ai/ai.class";
import TenantService from "./service/tenant";
import ServerAPI from "./http";
import { generateImage } from "./service/generate.pdf";
import { saveVector } from "./service/langchain";

const ID_TENANT = process.env.ID_TENANT ?? "";
const OPENAI_API_KEY = process.env.OPENAI_API_KEY ?? "";
const PORT = process.env.PORT ?? "4000";

console.log(`TENANT:${ID_TENANT}`);

const tenant = new TenantService(ID_TENANT);

const http = new ServerAPI(ID_TENANT, PORT);
/**
 * Main scripts
 */
const run = async () => {
  const info = await tenant.getInfo(ID_TENANT);
  const ai = new AiSerivce(OPENAI_API_KEY, {
    company: info.company,
    delivery: info.delivery,
    drinks: info.drinks,
    meals: info.meals,
    schedule: info.schedule,
    website: info.website,
    location: info.location,
    botName: info.botName,
  });

  ai.on(
    "gas_token",
    async (res) => await tenant.registerToken(ID_TENANT, res.amount)
  );

  const adapterDB = new MockAdapter();
  const adapterFlow = BotWhatsapp.createFlow(loadFlows);

  const adapterProvider = BotWhatsapp.createProvider(BaileysProvider, {
    name: ID_TENANT,
  });

  adapterProvider.on("require_action", () => console.log("PING"));
  adapterProvider.on("ready", async () => {
    await tenant.sync();
    await generateImage(info);
    await saveVector(info.meals, info.drinks);
    console.log('Menu generado')
  });

  const settings = {
    globalState: {
      status: true,
    },
    extensions: {
      ai,
      tenant,
      info,
      database: adapterDB,
    },
  };

  await BotWhatsapp.createBot(
    {
      flow: adapterFlow,
      provider: adapterProvider,
      database: adapterDB,
    },
    settings
  );

  http.start();
};

run();
edgarvaldez99 commented 1 year ago

Hola @leifermendez Gracias por tu respuesta.

Implementé como me dijiste pero VSCode me tira este error:

No se encontró ningún archivo de declaración para el módulo '@bot-whatsapp/bot'. 
'/../base-baileys-mongo/node_modules/@bot-whatsapp/bot/lib/bundle.bot.cjs' tiene un tipo "any" de forma implícita.
Pruebe "npm i --save-dev @types/bot-whatsapp__bot" si existe o 
agregue un nuevo archivo de declaración (.d.ts) que incluya "declare module '@bot-whatsapp/bot';".ts(7016)

Por si caso tendrías declarado el .d.ts para @bot-whatsapp/bot, @bot-whatsapp/database/mongo, @bot-whatsapp/provider/baileys ?

edgarvaldez99 commented 1 year ago

Según chatgpt puedo hacer esto:

// @types/index.d.ts     <- nombre del archivo

interface MongoAdapterOptions {
  dbUri: string;
  dbName: string;
}

export class MongoAdapter {
  constructor(options: MongoAdapterOptions);
}

export class BaileysProvider {}

declare module "@bot-whatsapp/database/mongo" {
  export default class MongoAdapter {
    constructor(options: MongoAdapterOptions);
  }
}

declare module "@bot-whatsapp/provider/baileys" {
  export default class BaileysProvider {}
}

declare module "@bot-whatsapp/portal" {
  export default function QRPortalWeb(): void;
}

declare module "@bot-whatsapp/bot" {
  export interface AnswerOptions {
    media?: string | null;
    buttons?: Array<any>;
    capture?: boolean;
    child?: string | null;
    delay?: number;
  }

  export interface FlowContext {
    addAnswer: (
      answer: string[],
      options: AnswerOptions,
      cb?: Function | null,
      nested?: Function[]
    ) => this;
    addAction: (cb: () => null, flagCb: () => null) => this;
  }

  export interface BotOptions {
    flow: FlowContext;
    provider: BaileysProvider;
    database: MongoAdapter;
  }

  export function createFlow(flow: any[]): any;

  export function createProvider(provider: BaileysProvider): any;

  export function createBot(options: BotOptions): any;

  export function addKeyword(keywords: string[]): FlowContext;
}

Por si alguien tenga el mismo problema con VSCode

También deben agregar en el archivo tsconfig.json lo siguiente:

{
  ...
  "compilerOptions": {
    "types": [
      "node",
      "./@types",
    ],
    "module": "commonjs",   // <- esta línea es importante para que todo funcione
    "esModuleInterop": true,   // <- esta línea es importante para que todo funcione
    ...
  }
}
binhodev commented 1 year ago

Re-open

github-actions[bot] commented 11 months ago

¿Alguna novedad sobre esta ISSUE?

VigilioYonatan commented 11 months ago

we hope a typescript support

edu-amr commented 3 months ago

Alguma novidade?