Jump to content

[TUTORIAL] Sending Server logs to Discord with webhook


Captien

Recommended Posts

This tutorial aims to give you knowledge about how to use a webhook to log important events from your server right into a discord channel.

  • Creating a Webhook
  1.  Create a channel.
  2. Go to: Edit channel -> Integrations ->view webhooks -> New webhook
  3.  Copy the webhook URL.

I'll call mine Spicy.

image.png

  • Using the Webhook

Now we'll create a small server-side function that'll help us use the webhook.

  • Notes:
  1. Replace <webhook URL> with the webhook URL that you just copied
  2. Replace <serverLogo URL> with the desired server logo picture URL.

 

Spoiler
const webhook = '<webhook URL>';
const serverLogo = '<serverLogo URL>'
const {
    request
} = require('https');
const requestOptions = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    timeout: 1000,
};

// Global discord object bound to mp namespace
mp.discord = {
    colors: { // For more colors check: https://gist.github.com/thomasbnt/b6f455e2c7d743b796917fa3c205f812
        RED: 13632027,
        GREEN: 4289797,
        BLUE: 4886754,
        ORANGE: 16098851,
        BLACK: 1,
        WHITE: 16777215,
        GREY: 10197915,
        YELLOW: 16312092,
        BROWN: 9131818,
        CYAN: 5301186
    }
};

/*
 * @function Our nice function send some logs
 * @params:
 * title: string (Title of the embed)
 * msg: string (description of the log)
 * fields: array of objects optional [{name: string, value: string, inline: boolean}, ...]
 * color: int optional (Default: GREY color) use mp.discord.colors.color for more colors
 */

mp.discord.sendMessage = (title, msg, fields = [], color = mp.discord.colors.GREY) => {
    const embed = JSON.stringify({
        // More embed options: https://birdie0.github.io/discord-webhooks-guide/structure/embeds.html
        "embeds": [{
            "author": {
                "name": mp.config.name, // Server's name
                "icon_url": serverLogo // Server's logo
            },
            "title": title,
            "description": msg,
            "thumbnail": {
                "url": serverLogo
            },
            "fields": fields,
            "color": color
        }]
    });
    requestOptions.headers['Content-Length'] = embed.length;
    const req = request(webhook, requestOptions, (res) => {
        if (res.statusCode < 200 || res.statusCode > 299) {
            console.error('[ERROR] Unable to process request: ' + res.statusCode + '\nReason: ' + res.statusMessage);
        }
    });

    req.on('error', (err) => {
        console.error(err);
    })

    req.on('timeout', () => {
        req.destroy()
        console.error('[ERROR] Request timedout');
    })

    req.write(embed);
    req.end();
};

Now here's a small example of how to use it:
 

// Triggers once player joins the server...
// Simple log when player joins server
mp.events.add('playerJoin', (player) => {
	mp.discord.sendMessage(`Player Joined`, player.name, [], mp.discord.colors.GREY);
});

// Another one with fields included
mp.events.add('playerJoin', (player) => {
  let fields = [{
    name: `Player's IP`,
    value: player.ip,
    inline: false
  }]
  mp.discord.sendMessage(`Player joined the server [${mp.players.toArray().length}/${mp.config.maxplayers}]`, player.name, fields, mp.discord.colors.GREEN);
});

 

image.png

Enjoy spamming discord....

Regards,
Keptin

Edited by Captien
Removed the got package
  • Like 3
Link to comment
Share on other sites

  • 11 months later...
  • 5 months later...
  • 1 year later...

i use this code and i get an error. can any one help me ?

 

[2022-08-23 20:31:13] [ERROR] Failed loading file "discordlog.js" from "scripts": Must use import to load ES Module: D:\server-files-gangwar\node_modules\got\dist\source\index.js
require() of ES modules is not supported.
require() of D:\server-files-gangwar\node_modules\got\dist\source\index.js from D:\server-files-gangwar\packages\thewire\scripts\discordlog.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from D:\server-files-gangwar\node_modules\got\package.json.

 

Link to comment
Share on other sites

  • Captien changed the title to [TUTORIAL] Sending Server logs to Discord with webhook
On 8/23/2022 at 6:02 PM, IccY said:

i use this code and i get an error. can any one help me ?

 

[2022-08-23 20:31:13] [ERROR] Failed loading file "discordlog.js" from "scripts": Must use import to load ES Module: D:\server-files-gangwar\node_modules\got\dist\source\index.js
require() of ES modules is not supported.
require() of D:\server-files-gangwar\node_modules\got\dist\source\index.js from D:\server-files-gangwar\packages\thewire\scripts\discordlog.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from D:\server-files-gangwar\node_modules\got\package.json.

 

Yeah... its due to changing the way to import it.. Saved us the hassle and removed it totally. Try to the new updated version...

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...