DiscordCompact

From Support Wiki
Jump to navigation Jump to search

DiscordCompact is a widget for Wikis to display a Discord server widget. It is similar to DiscordWidget, but instead displays a much smaller, simplified widget. This is useful for wikis that don't have a lot of space to fit content into the main page.

Dependencies

  • [[Template:DiscordCompact]]
  • MediaWiki:Common.js
  • MediaWiki:DiscordCompact.js

Setup

On the Discord server you wish to use with this widget, have an administrator enable Widgets for that server (if it is not already enabled).

If you are an administrator on the Discord server, you can do this by going into it's Server Settings, selecting the Widget tab, and clicking on the Enable Server Widget slider so that it becomes green.
If you want users to be able to join the server by clicking on your widget, make sure to set an Invite Channel there too!

Make sure to copy the Server ID down somewhere too; you'll need it for the later steps.

Copy the below code into the Template:DiscordCompact page of your wiki:

<noinclude>
Usage: <code><nowiki>{{DiscordCompact|id=<server-id>}}</nowiki></code><br>
Requires [[MediaWiki:DiscordCompact.js]], which should be loaded from [[MediaWiki:Common.js]].<br>
Also requires the given Discord server to have Widgets enabled in the Server Settings.
</noinclude><!--
--><div id="discord-compact-widget" data-id="{{{id|}}}"></div>

Copy the below code into the MediaWiki:DiscordCompact.js page of your wiki:

/**
 * DiscordCompact.js
 * ----------------------
 * A very simple script to display a Discord widget.
 * Version 0.0.2
 * https://support.wiki.gg/wiki/DiscordCompact
 * ----------------------
 */

mw.hook('wikipage.content').add(function($content) {
	var widget = $content.find("#discord-compact-widget");

    // Bail out if we didn't find a widget.
    if (!widget.length) return;

	var id = widget.attr("data-id");
	
	// Ensure that the id is not blank.
	if (id === "") throw new Error("DiscordCompact has a blank server id!");
	// Ensure that the id consists only of numbers and is at least 17 characters long.
	if (!new RegExp("^[0-9]{17}[0-9]+$").test(id)) throw new Error("DiscordCompact has an invalid server id!");
	
	var apiBase = `https://discord.com/api/guilds/${id}`;
	// Get some information about the server, such as online member count and invite url.
	// This also tells us if the server exists or has widgets disabled, so we look out for that too.
	$.ajax(`${apiBase}/widget.json`).fail(function(req){
        if (!req.responseJSON) throw new Error(`DiscordCompact encountered an unknown error whilst fetching widget.json (status: ${req.status})`);
		switch (req.responseJSON.code) {
            case 10004:
                throw new Error("DiscordCompact has a valid server id, but no such server exists!");
            case 50004:
                throw new Error("DiscordCompact has a valid server id, but that server has widgets disabled!");
            default:
                throw new Error(`DiscordCompact encountered an unknown error whilst fetching widget.json (status: ${req.status}; code: ${req.responseJSON.code})`);
        }
	}).done(function(res){
		const inviteURL = res.instant_invite;

        // Warn if we can't get an invite URL.
        if (inviteURL == null) console.warn("DiscordCompact cannot get an invite URL; does this server have an invite channel set in Widget settings?");
        
        // Now get the widget image.
        $.ajax({url: `${apiBase}/widget.png?style=banner2`, xhrFields: {responseType: "blob"}}).fail(function(req){
            if (!req.responseJSON) throw new Error(`DiscordCompact encountered an unknown error whilst fetching widget.png! (status: ${req.status}`);
            throw new Error(`DiscordCompact encountered an unknown error whilst fetching widget.png! (status: ${req.status}; code: ${req.responseJSON.code})`);
        }).done(function(blob){
            // Convert the image data into base64. This prevents us having to make the client request it a second time.
            const imageReader = new FileReader();
            imageReader.readAsDataURL(blob);
            imageReader.onloadend = () => {
                const b64Data = imageReader.result;

                // Replace the widget with an <a> tag
                widget.replaceWith(function() {
                    return $("<a>", {
                        id: widget.attr("id"),
                        class: widget.attr("class"),
                        style: widget.attr("style"),
                        alt: "Discord server widget",
                        href: inviteURL
                    });
                });

                // We need to grab the widget again to update it.
                widget = $("#discord-compact-widget");

                // Setup the CSS so that the image is displayed.
                widget.css("display", "block");
                widget.css("max-height", "76px");
                widget.css("max-width", "320px");

                // Create the image.
                const widgetImage = document.createElement("img");
                widgetImage.src = b64Data;
                widgetImage.style.width = "100%";
                widgetImage.style.height = "100%";
                widgetImage.style.borderRadius = "5px";
                widget.append(widgetImage);

                // Prevent image dragging.
                widget.on("dragstart", function(e) { e.preventDefault(); });

                // We're done here.
                console.log("DiscordCompact loaded successfully!");
            }
        });
	});
});

Copy the below code into the MediaWiki:Common.js page of your wiki:

importScript("MediaWiki:DiscordCompact.js");

To use the widget, simply include the DiscordCompact template on the page you want to use it on (for example, the Main Page of your wiki). Make sure to set the id parameter to the Server ID you copied during Prerequisites!

Example:

{{DiscordCompact|id=81384788765712384}}

If needed, you can target the widget in your MediaWiki:Common.css with the following selector:

#discord-compact-widget {
    /* widget css rules go here */
}

Troubleshooting

If you have followed all of the steps listed on this page, this widget should log any errors it encounters to the Console. You can view the Console in most browsers by pressing F12 and selecting the Console tab. Look for the phrase "DiscordCompact".