Development, Strapi, Discord··x·x

Strapi v4 Discord Webhook Integration

Learn how to integrate Discord webhooks with Strapi v4 to send notifications when content is created, updated, or deleted.

Strapi Lifecycles and Discord Webhook integration

Strapi is a headless CMS (Content Management System) that allows developers to build APIs quickly and easily. In this tutorial, we will guide you through the installation process of Strapi V4 and create your first API.

Prerequisites

Before we start, make sure you have the following prerequisites installed on your computer:

  • Node.js (v16 or above)
  • NPM or Yarn package manager

Step 1: Install Strapi V4 and Create Your First API

Installation

To install Strapi V4, open your terminal or command prompt and run the following command:

yarn create strapi-app my-project --quickstart or npx create-strapi-app@latest my-project --quickstart

Replace my-project with the name of your project. This command will create a new Strapi project with the quickstart template, which includes all the necessary files and dependencies to get started.

Once the installation process is complete, navigate to your project directory by running:

cd my-project

Starting Strapi

To start Strapi, run the following command:

yarn develop or npm run develop

This will start the Strapi server and launch the development environment. Once the server is started, you can access the Strapi dashboard by navigating to http://localhost:1337/admin in your web browser.

Creating Your First API

From the Strapi dashboard, you can create a new API. Click on "Content Type Builder" in the left-hand menu and then click the "Create new collection type" button.

You will be prompted to enter a name for your new content type. For this example, let's call it "Blog".

Next, you can add fields to your content type. Click the "Add another field" button and choose a field type. For this example, let's add the following fields:

  1. "Title" field, which should be of type "Text".
  2. "Description" field, which should be of type "Text".
  3. "Slug" field, which should be of type "UID", select the newly created "Title" in the next window.
  4. "Author" field, which should be of type "Text".
  5. "Image" field, which should be of type "Media", select 'Single file' in the next window.
  6. "Content" field, which should be of type "Rich Text".

Once you have added your fields, click the "Save" button to create your new content type.

Now, you can create entries for your new Blog content type by clicking on "Content" in the left-hand menu and then clicking the "Add new Blog" button.

Congratulations, you have successfully installed Strapi V4 and created your first API! From here we will jump over to your Discord Server so we can set it up for Webhook integrations.

Step 2: Create a Webhook in Your Discord Server

Discord webhooks allow you to send automated messages and notifications from external sources to a text channel in your Discord server. In this tutorial, we'll walk you through the steps of creating a webhook in your Discord server.

Prerequisites

Before we begin, make sure you have the following:

  • A Discord account
  • Permission to manage webhooks in your Discord server
  • A webhook URL (if you're using an external service)

Creating a Webhook in Discord

  1. First, navigate to your Discord server and select the text channel where you want to send webhook messages.
  2. Click on the gear icon next to the channel name to open the "Channel Settings" menu.
  3. Scroll down to the "Integrations" section and click the "Create Webhook" button.
  4. In the "Webhook Setup" dialog, give your webhook a name and an avatar (optional).
  5. Click the "Copy Webhook URL" button to copy the webhook URL to your clipboard.
  6. Click the "Save" button to create your webhook.

Your webhook is now set up and ready to receive messages from external sources. Let's move back to Strapi so we can start extending it by adding some custom code to our project.

Step 3: Using Strapi Lifecycles to update Discord whenever you create and save a new Blog entry.

1. Create a lifecycle.js file

Now that we have a new API endpoint, we can create a lifecycles.js file to add custom logic to our API requests.

  1. Open your Strapi project in a code editor of your choice.
  2. Navigate to the api/blog/content-types/blog/ directory.
  3. Create a new file named lifecycles.js in this directory.
  4. Open the lifecycles.js file in your code editor.

2. Add a beforeCreate function

Let's start by adding a beforeCreate function to our lifecycles.js file. This function will be executed before a new record is created in our API endpoint.

  1. Add the following code to your lifecycle.js file:
module.exports = {
    async beforeCreate(event) {
      console.log(`Creating a new record with title "${data.title}"`);
      // Add your custom logic here
    },
};

In this code, we're exporting an object that contains a lifecycles property. This property is an object that contains the beforeCreate function. The beforeCreate function takes a event parameter, which contains the data that is about to be saved to the database.

In this example, we're logging a message to the console with the title of the new record, and we can add our custom logic here.

3. Add an afterCreate function

Let's now add an afterCreate function to our lifecycles.js file. This function will be executed after a new record is created in our API endpoint.

  1. Add the following code to your lifecycles.js file:
async afterCreate(event, data) { 
   console.log(`A new record with title "${data.title}" was created`); 
   // Add your custom logic here 
},

The code in your lifecycles.js file should look like this:

module.exports = {
    async beforeCreate(event) {
      console.log(`Creating a new record with title "${data.title}"`);
      // Add your custom logic here
    },
    async afterCreate(event, data) {
      console.log(`A new record with title "${data.title}" was created`);
      // Add your custom logic here
    },
};

We've added an afterCreate function to the lifecycles object. The afterCreate function takes two parameters: result, which contains the newly created record object, and data, which contains the original data that was saved.

At this point, we're logging a message to the console with the title of the new record, and we can add our custom logic here. We're almost there.

4. Adding and using Axios to reach the Discord Webhook

  1. Add the following code at the top of the 'lifecycles.js' file.
const axios = require("axios");
  1. From this point we will be using the 'event' data to create a nice Discord Post. First we will setup the payload for our Discord Webhook. Copy the following code inside your afterCreate function:
const payload = {
    "username": "Webhook Bot Username",
    "avatar_url": "image-url-for-profile-pic",
    "content": "A new Blog article is available.",
    "embeds": [{
        "author": {
            "name": result.author,
            "url": 'url-of-blog-site' + result.slug,
            "icon_url": `image-url-for-profile-pic`,
        },
        "title": result.title,
        "url": 'url-of-blog-site' + result.slug,
        "description": result.description,
        "color": 15258703,
        "thumbnail": {
            "url": 'url-of-strapi-upload' + result.image.formats.thumbnail.url,
        },
        "image": {
            "url": 'url-of-strapi-upload' + result.image.url,
        },
        "footer": {
            "text": "Happy coding! :fire:",
        }
    }]
}
  1. Add the following request settings for Axios:
const settings = {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
};
  1. Finally add the axios post request with the payload and the settings object:
try {
    const response = await axios.post("Replace-W-Your-Discord-Webhook", JSON.stringify(payload), settings);
    console.log(response)
} catch (error) {
    console.log(error)
}
  1. Restart your server and create a new Blog entry, after creating a new entry, the lifecycle function will call your Discord Webhook and display the message.

Here's the entire lifecycles.js file:

const axios = require("axios");

module.exports = {
    async beforeCreate(event) {
    },
    async afterCreate(event, data) {
     const { result, params, state } = event;
        const payload = {
            "username": "Your-Webhook-Bot-Username",
            "avatar_url": "image-url-for-profile-pic",
            "content": "A new Blog article is available.",
            "embeds": [{
                "author": {
                    "name": result.author,
                    "url": 'url-of-blog-site' + result.slug,
                    "icon_url": `image-url-for-profile-pic`,
                },
                "title": result.title,
                "url": 'url-of-blog-site' + result.slug,
                "description": result.description,
                "color": 15258703,
                "thumbnail": {
                    "url": 'url-of-strapi' + result.image.formats.thumbnail.url,
                },
                "image": {
                    "url": 'url-of-strapi' + result.image.url,
                },
                "footer": {
                    "text": "Happy coding! :fire:",
                }
            }]
        };
        
        const settings = {
            method: "POST",
            headers: {
            "Content-Type": "application/json"
            },
        };
        
        try {
            const response = await axios.post("Replace-W-Your-Discord-Webhook", JSON.stringify(payload), settings);
            console.log(response)
        } catch (error) {
            console.log(error)
        }
    },
};

Services

Copyright © 2024. All rights reserved.