Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

How to make a customize facebook messenger Chatbot integration with nestjs

Monday, 1 September 2025
|
Read: Completed in minutes

How to make a customize facebook messenger Chatbot integration with nestjs

💖 Hello everyone welcome back to Webzone Tech Tips blogspot, today I will share with you my experience how to create a customize Chatbot integration with Facebook Messenger, Ollama NestJS and Prisma for free, after you understand the step you can easy cho switch Ollama with ChatGPT, the purpose I dont use ChatGPT here because ChatGPT need a subscribe and Ollama is free now, you can download it on your local and try, 

How to make a customize facebook messenger Chatbot integration with nestjs


If you don't know how to run Ollama, you can check this tutorial for know Ollama work first. it very easy to learn.

Let's started now

  1. First, set up your project structure and install dependencies:

bash
npm install -g @nestjs/cli
nest new facebook-chatbot
cd facebook-chatbot
npm install @prisma/client prisma axios
  1. Create Prisma schema (prisma/schema.prisma):

prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model ChatMessage {
  id        Int      @id @default(autoincrement())
  senderId  String
  message   String
  response  String
  timestamp DateTime @default(now())
  pageId    String
}
  1. Set up environment variables (.env):

env
DATABASE_URL="mysql://USER:PASSWORD@HOST:PORT/DATABASE"
FACEBOOK_PAGE_ACCESS_TOKEN=your_page_access_token
FACEBOOK_VERIFY_TOKEN=your_verify_token
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=llama2
  1. Create the main chatbot service (src/chat/chat.service.ts):

typescript
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import axios from 'axios';

@Injectable()
export class ChatService {
  constructor(private prisma: PrismaService) {}

  async handleMessage(senderId: string, message: string, pageId: string) {
    // Get response from Ollama
    const response = await this.getOllamaResponse(message);

    // Store message in database
    await this.prisma.chatMessage.create({
      data: {
        senderId,
        message,
        response,
        pageId,
      },
    });

    // Send response back to Facebook
    await this.sendFacebookMessage(senderId, response);
  }

  private async getOllamaResponse(prompt: string): Promise<string> {
    try {
      const response = await axios.post(
        `${process.env.OLLAMA_BASE_URL}/api/generate`,
        {
          model: process.env.OLLAMA_MODEL,
          prompt,
          stream: false,
        },
      );
      return response.data.response;
    } catch (error) {
      console.error('Error getting response from Ollama:', error);
      return "I'm having trouble connecting to my AI service. Please try again later.";
    }
  }

  private async sendFacebookMessage(recipientId: string, message: string) {
    try {
      await axios.post(
        `https://graph.facebook.com/v19.0/me/messages?access_token=${process.env.FACEBOOK_PAGE_ACCESS_TOKEN}`,
        {
          recipient: { id: recipientId },
          message: { text: message },
        },
      );
    } catch (error) {
      console.error('Error sending message to Facebook:', error);
    }
  }
}
  1. Create webhook controller (src/webhook/webhook.controller.ts):

typescript
import { Controller, Get, Post, Body, Query } from '@nestjs/common';
import { ChatService } from '../chat/chat.service';

@Controller('webhook')
export class WebhookController {
  constructor(private readonly chatService: ChatService) {}

  @Get()
  verifyWebhook(
    @Query('hub.mode') mode: string,
    @Query('hub.verify_token') token: string,
    @Query('hub.challenge') challenge: string,
  ) {
    if (mode === 'subscribe' && token === process.env.FACEBOOK_VERIFY_TOKEN) {
      return challenge;
    }
    return 'Verification failed';
  }

  @Post()
  async handleWebhook(@Body() body: any) {
    const entry = body.entry[0];
    const messaging = entry.messaging[0];

    if (messaging.message) {
      await this.chatService.handleMessage(
        messaging.sender.id,
        messaging.message.text,
        entry.id,
      );
    }

    return 'EVENT_RECEIVED';
  }
}
  1. Set up Prisma module (src/prisma/prisma.module.ts):

typescript
import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';

@Module({
  providers: [PrismaService],
  exports: [PrismaService],
})
export class PrismaModule {}
  1. Create Prisma service (src/prisma/prisma.service.ts):

typescript
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  async onModuleInit() {
    await this.$connect();
  }

  async onModuleDestroy() {
    await this.$disconnect();
  }
}
  1. Update app module (src/app.module.ts):

typescript
import { Module } from '@nestjs/common';
import { WebhookController } from './webhook/webhook.controller';
import { ChatService } from './chat/chat.service';
import { PrismaModule } from './prisma/prisma.module';

@Module({
  imports: [PrismaModule],
  controllers: [WebhookController],
  providers: [ChatService],
})
export class AppModule {}
  1. Update main.ts to enable appropriate settings:

typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  await app.listen(3000);
}
bootstrap();

To use this system:

  1. Set up your Facebook App and Page:

  2. Run Ollama:

    bash
    ollama pull llama2
    ollama serve
  3. Set up your database and run migrations:

    bash
    npx prisma migrate dev --name init
  4. Start your NestJS application:

    bash
    npm run start

Important considerations:

  • Add proper error handling and validation

  • Implement security measures (rate limiting, authentication)

  • Handle different message types (images, attachments)

  • Add message queuing for better performance

  • Implement proper logging

  • Add unit tests

  • Follow Facebook's Messenger Platform policies

Remember to:

  1. Replace environment variables with your actual values

  2. Set up proper SSL certificate for your webhook URL

  3. Configure your Facebook webhook to subscribe to appropriate events

  4. Handle Facebook's message delivery and read receipts

  5. Implement additional features like typing indicators if needed

This provides a basic structure for your chatbot. You'll need to expand it based on your specific requirements and error handling needs.

If you have any unclear above, leave your comment below on this article, I will support you

💖 Thanks for reading 💖

I am Zidane


🙇🏼🙇🏼 We Appreciate Your Comments and Suggestions - Webzone, all things Tech Tips web development
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com