Coder Social home page Coder Social logo

fuma-nama / discord-bot-dashboard-next Goto Github PK

View Code? Open in Web Editor NEW
173.0 8.0 59.0 5.08 MB

The Most Powerful Discord bot Dashboard Template

Home Page: https://demo-bot.vercel.app

License: MIT License

JavaScript 0.31% TypeScript 96.24% CSS 3.45%
discord discord-bot-dashboard discord-bot-dashboard-nextjs nextjs react reactjs typescript discord-bot

discord-bot-dashboard-next's Introduction

Deprecated

Please consider other alternatives. You may continuously use it but no support will be provided.

banner

Discord Bot Dashboard Template

Using Typescript, Next.js 13, React 18 and Chakra ui 2.0

  • Support Light/Dark theme
  • Multi languages support (i18n)
  • Typescript support
  • Nice UI & UX + Fast performance
  • Flexiable and Customizable
  • Detailed Documentation

Video: https://youtu.be/IdMPjT5PzVk
Live Demo: https://demo-bot.vercel.app

  • Only 'Welcome message' Feature is Supported

Review (not the latest version)

Light Dark
light-mode dark-mode

Getting Started

As a template, you need to customize a few things in order to get it work

Before that

  • Install Node.js, and a Package Manager (ex: npm or pnpm)

Required Skills

  • Basic knowledge about React.js
  • Able to read javascript/typescript

Set up

  1. Clone the repo
    git clone https://github.com/fuma_nama/discord-bot-dashboard-next.git

  2. Install dependencies
    We always prefer PNpm

    NPM PNPM
    npm install pnpm install
  3. Customize files
    The file structure of this project

    Path Description
    src/pages/* All the pages
    src/components/* Components
    src/api/* API utils
    src/config/* Common configurations
  4. Define Features
    The dashboard has built-in support for configuring features
    Users are able to enable/disable features and config the feature after enabling it

    Customize all typings in src/config/types/custom-types.ts
    CustomFeatures is used for defining features and options, see the example for more details

    Open src/config/features
    You can see how a feature is configured

    'feature-id': {
         name: 'Feature name',
         description: 'Description about this feature',
         icon: <Icon as={BsMusicNoteBeamed} />, //give it a cool icon
         useRender: (data) => {
             //render the form
         },
     }

    The useRender property is used to render Feature Configuration Panel
    Take a look at here for examples

  5. Configure General Information
    Modify src/config/common.tsx

  6. Configure Environment variables
    Those variables in .env.example are required
    You can define environment variables by creating a .env file

  7. Setup Backend Server
    In order to let the dashboard connected with your discord bot, you will need a backend server
    You can implement it in any programming languages

    Read here for a guide to develop your own server

  8. Done!
    Start the app by pnpm run dev (depends on your package manager)
    Then you should see the app started in port 3000

    Localization | Forms

Authorization

We are using the API Routes of Next.js to handle Authorization

Configure the Application

  1. Open Discord Developer Portal

  2. Create your OAuth2 application in https://discord.com/developers/applications

  3. In <Your Application> -> OAuth2 -> Redirects

    Add <APP_URL>/api/auth/callback url to the redirects

    For Example: http://localhost:3000/api/auth/callback
    This is required for Authorization

Authorization Flow

Login -> Discord OAuth -> API Routes -> Client

  • Login (/api/auth/login)
    • Redirects user to discord oauth url
  • Open Discord OAuth url
    • User authorizes the application
    • Redirect back to /api/auth/callback
  • API Routes
    • Store the access token in http-only cookies
    • Redirect back to home page

Token Expiration

The Discord access token can be expired or unauthorized by the user
We will require the user to login again after getting 401 error from the Discord API

The refresh token won't be used, but you are able to customize the Authorization Flow

Backend Development

Check src/api/bot.ts, it defined a built-in API for fetching data

You can use express.js (Node.js), Rocket (Rust) or any libraries/languages to develop your own server
Usually the server runs along with your discord bot (in the same program)
Moreover, you can use redis instead of connecting to the bot server directly

Official Example

Node.js (Typescript)

Authorization

The client will pass their access token via the Authorization header

Bearer MY_TOKEN_1212112

Required Routes

You may extend it for more functions

GET /guilds/{guild}

  • Get guild info (custom-types.ts > CustomGuildInfo)
  • Respond 404 or null if bot hasn't joined the guild

GET /guilds/{guild}/features/{feature}

  • Get Feature options (custom-types.ts > CustomFeatures[K])
  • Respond 404 if not enabled

PATCH /guilds/{guild}/features/{feature}

  • Update feature options
  • With custom body (defined in config/features)
  • Respond updated feature options

POST /guilds/{guild}/features/{feature}

  • Enable a feature

DELETE /guilds/{guild}/features/{feature}

  • Disable a feature

GET /guilds/{guild}/roles

  • Get Roles of the guild
  • Responds a list of Role Object (Same as discord documentation)

GET /guilds/{guild}/channels

  • Get Channels of the guild
  • Responds a list of Guild Channel (Same as discord documentation)

Any issues?

Feel free to ask a question by opening a issue

Love this project? Give this repo a star!

discord-bot-dashboard-next's People

Contributors

fuma-nama avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

discord-bot-dashboard-next's Issues

Trying to figure out backend server

Hi there!

I followed the tutorial and have gotten stuck on the backend server part of it. The official example link doesn't go anywhere, so I figured I would ask here if there is some example server I could learn from.

Thanks!

Backend Development

I don't know how to use Backend Development. Is there any support or documentation to help me?

Forms' States (isRequired, isDisabled, ...)

Hello. I don't quite understand where or how I can add states in the component forms that I will be using, for example isRequired, etc.

SwitchFieldForm

<SwitchFieldForm
  control={{ 
    label: 'Pinging', 
    description: 'Toggle the role pinging when a new fruit stock has arrived'
  }}
  controller={{
    control,
    name: 'ping_toggle',
  }}
/>

Again, using the provided code above, how or where should I add the states that I want to use in the form? Thank you!

Default export is deprecated

Describe the bug
When I launch the dashboard in dev mode, I receive a warning.

To Reproduce
Simply run the command "pnpm run dev" and visit a page of the dashboard while logged in.

Expected behavior
Here's what we get in the console:

root@debian:~/discord-bot-dashboard-next# pnpm run dev

> [email protected] dev /root/discord-bot-dashboard-next
> next dev

  โ–ฒ Next.js 13.5.6
  - Local:        http://localhost:3000
  - Environments: .env

 โœ“ Ready in 7.6s
 โœ“ Compiled /src/middleware in 639ms (59 modules)
 โ—‹ Compiling /user/home ...
 โœ“ Compiled /user/home in 11.2s (1505 modules)
[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`.
[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`.
 โœ“ Compiled /api/auth in 1520ms (231 modules)
 โ—‹ Compiling /guilds/[guild] ...
 โœ“ Compiled /guilds/[guild] in 7.3s (1699 modules)
[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`.
[DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`.

The problem is [DEPRECATED] Default export is deprecated. Instead use `import { create } from 'zustand'`.

Additional context
My Node.js version is 18.18.2.
I should note that I don't have a backend in place yet.

Save is not saving

Describe the bug
I know this sounds odd.
I haven't had this issue until now.
I created on welcomer-message an embed, all working so far.
Saw backend was no longer getting the "save" call, meaning the "save" button was not sending the request, checked with both:
Network tab

@Patch('/features/welcome-message')
  async updateFeature(
    @Req() req: AuthRequest,
    @Param('guild') guild: string,
    @Body() body: Partial<WelcomeMessage>,
  ) {
    console.log('got a patch')
    await this.bot.checkPermissions(req.session, guild);

    const updated = await this.prisma.welcomeMessage.update({
      where: {
        id: guild,
      },
      data: {
        ...body,
        id: undefined,
      },
    });

    return updated;
  }

To Reproduce
Steps to reproduce the behavior:

Last things I remember I did:
Tried converting to use mysql instead of prisma
Saw the error
CTRL+Zed everything to revert.
Save button still not sending requests.

Expected behavior
Saving the data

Screenshots
Video recording:
https://streamable.com/ix5rl1

Device:

  • OS: Windows 10
  • Chrome
  • Version: 119.0.6045.160 (Official Build) (64-bit)

Additional context
The video says it all.

use design on other project?

Hey, I wanted to ask if I can use your design on my own dashboard, because I use js and react instead of ts and next and I don't understand some things like your queries, so I'm reprogramming it for myself and just wanted to know if I need a new design xD

ws cant connect

Hi, trying to run this on a cpanel server, and trying to proxy the connections to node. The webpage loads fine, however i get alot of errors saying

websocket.js:60 WebSocket connection to 'wss://*****/_next/webpack-hmr' failed:

any suggestions?
thanks

{"client_id": ["Value \"\" is not snowflake."]}

Describe the bug
it keeps giving me this error when i sign in : {"client_id": ["Value "" is not snowflake."]}

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Device:

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Refusing to connect

Whenever I try and connect to the website, it just says it couldn't connect and such, even though it successfully starts โ€” there are no errors in console and everything seems to be setup correctly. One minor detail tho, this is running inside a Pterodactyl node.js egg. Though, other websites have worked perfectly on it and such, so I know it's possible, as well as the ports work fine with other applications so it likely isn't a firewall issue. I've been going at it for a couple hours and can't figure it out, so please help lol

Demo not working

The demo crashes because ยจThe bot has reached max servers and needs to be verifiedยจ

Small tutorial on how to make our own module/page?

Is your feature request related to a problem? Please describe.
A basic example how to make a "feature" using prisma

Describe the solution you'd like
Where to edit files, what to add
Describe alternatives you've considered
I have attempted, and basic knowledge of node/next. I get the page to display but i am struggling to add any functions. I want to read from another DB(which I've managed to add) but I am struggling to understand how to make the pages read etc...

Feature page stuck on "Loading"

Issue Summary:
I'm encountering an issue with my custom feature. The problem arises when I try to configure the feature, as it gets stuck on "Loading."

KDOAKDA

Code Files:

  • features.tsx in config folder
  • custom-types.tsx in config folder
  • FruitStocksFeature.tsx in config > use-features folder
  • Backend server implementation

Description:
I've created a custom feature called "Fruit Stocks" for my bot. The feature itself works well, including the enable feature button. However, when attempting to configure the feature, it gets stuck on "Loading."

features.tsx

config > features.tsx

import { Icon } from '@chakra-ui/react';
import { FaAppleAlt } from 'react-icons/fa';
import { FeaturesConfig } from './types';
import { provider } from '@/config/translations/provider';
import { createI18n } from '@/utils/i18n';
import { useFruitStocksFeature } from "./use-features/FruitStocksFeature";

/**
 * Support i18n (Localization)
 */
const { T } = createI18n(provider, {
  en: {
    fruitStocks: "Fruit Stocks",
    'fruitStocks description': 'Blox Fruit\'s stock notifier',
  },
});

/**
 * Define information for each features
 *
 * There is an example:
 */
export const features: FeaturesConfig = {
  fruitStocks: {
    name: <T text="fruitStocks" />,
    description: <T text="fruitStocks description" />,
    icon: <Icon as={FaAppleAlt} />,
    useRender: useFruitStocksFeature,
  }
};

custom-types.tsx

config > types

/***
 * Custom types that should be configured by developer
 ***/

import { z } from 'zod';
import { GuildInfo } from './types';

export type CustomGuildInfo = GuildInfo & {};

/**
 * Define feature ids and it's option types
 */
export type CustomFeatures = {
  fruitStocks: FruitStocksFeature;
};

/**
 * Define feature ids and it's option types
 */
export type FruitStocksFeature = {
  channel?: string;
};

FruitStocksFeature.tsx

config > use-features
Note: use-feature is a folder that I made to store all of my custom features.

import { SimpleGrid } from '@chakra-ui/layout';
import { TextAreaForm } from '@/components/forms/TextAreaForm';
import { UseFormRender, FruitStocksFeature } from '@/config/types';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { ColorPickerForm, SmallColorPickerForm } from '@/components/forms/ColorPicker';
import { DatePickerForm } from '@/components/forms/DatePicker';
import { FilePickerForm } from '@/components/forms/FilePicker';
import { SwitchFieldForm } from '@/components/forms/SwitchField';
import { ChannelSelectForm } from '@/components/forms/ChannelSelect';

const schema = z.object({
  channel: z.string(),
  danger: z.boolean(),
});

type Input = z.infer<typeof schema>;

export const useFruitStocksFeature: UseFormRender<FruitStocksFeature> = (data, onSubmit) => {
  const { register, reset, handleSubmit, formState, control } = useForm<Input>({
    resolver: zodResolver(schema),
    shouldUnregister: false,
    defaultValues: {
      channel: data.channel,
      danger: false,
    },
  });

  console.log("HELLO FRUIT STOCKS")

  return {
    component: (
      <SimpleGrid columns={{ base: 1, lg: 2 }} gap={3}>
        <ChannelSelectForm
          control={{
            label: 'Channel',
            description: 'Where to send the welcome message',
          }}
          controller={{ control, name: 'channel' }}
        />
        <SwitchFieldForm
          control={{ label: 'Turn on', description: 'Enable something' }}
          controller={{
            control,
            name: 'danger',
          }}
        />
      </SimpleGrid>
    ),
    onSubmit: handleSubmit(async (e) => {
      const data = await onSubmit(
        JSON.stringify({
          channel: e.channel,
        })
      );

      reset(data);
    }),
    canSave: formState.isDirty,
    reset: () => reset(control._defaultValues),
  };
};

Backend Server Implementation

Note: This code is only the "listening" to a certain route and I have the backend server working. It is using express.js and is running alongside with my actual bot.

module.exports = (client, server, utils) => {
  server.get("/guilds/:id/features/fruitStocks", async (req, res) => {    
    try {
      console.log("trying to get")
      const guild = client.guilds.cache.get(req.params.id);
      const schema = await client.mongoose.schemas.guilds.findOne({ guildId: guild.id })

      if (!schema) {
        return res.status(404).json({ error: "Guild schema not found" });
      }

      const fruitStocks = schema.modules.fruitStocks;

      console.log("Im here")
      return { channel: "1180089709196738561" }
    } catch (error) {
      console.error(error);
      return res.status(500).json({ error: `Internal server error. ${error}` })
    }
  })
  
  server.post("/guilds/:id/features/fruitStocks", async (req, res) => {
    try {
      console.log("trying to post")
      await utils.checkPermission(req.session, req.params.id);

      const guild = client.guilds.cache.get(req.params.id);
      const schema = await client.mongoose.schemas.guilds.findOne({ guildId: guild.id })

      if (!schema) {
        return res.status(404).json({ error: "Guild schema not found" });
      }

      schema.modules.fruitStocks.enabled = true
      await schema.save()
      return "Success"
    } catch (error) {
      console.error(error);
      return res.status(500).json({ error: `Internal server error. ${error}` })
    }
  })

  server.delete("/guilds/:id/features/fruitStocks", async (req, res) => {
    try {
      console.log("trying to delete")
      await utils.checkPermission(req.session, req.params.id);

      const guild = client.guilds.cache.get(req.params.id);
      const schema = await client.mongoose.schemas.guilds.findOne({ guildId: guild.id })

      if (!schema) {
        return res.status(404).json({ error: "Guild schema not found" });
      }

      schema.modules.fruitStocks.enabled = false
      await schema.save()
      return "Success"
    } catch (error) {
      console.error(error);
      return res.status(500).json({ error: `Internal server error. ${error}` })
    }
  })

  server.patch("/guilds/:id/features/fruitStocks", async (req, res) => {
    try {
      console.log("trying to patch")
      await utils.checkPermission(req.session, req.params.id);

      const guild = client.guilds.cache.get(req.params.id);
      const schema = await client.mongoose.schemas.guilds.findOne({ guildId: guild.id })

      if (!schema) {
        return res.status(404).json({ error: "Guild schema not found" });
      }
    } catch (error) {
      console.error(error);
      return res.status(500).json({ error: `Internal server error. ${error}` })
    }
  })
}

Any Help Appreciated:

I would appreciate any guidance or assistance in resolving this issue. If more code files or information are needed, please let me know.

Thank you for your help!

Error while Authenticating

Describe the bug
A clear and concise description of what the bug is.
i setup backend exactly as the example one
but when i try to authenticate it shows me this Error

Screenshots
image

and here is console output
image

backend output :
image

Device:

  • OS: Windows 10 pro
  • Browser Edge
  • Version latest

Unsure how to start this

I've been working on this for 2-3 hours at least and i can not get it working for the life of me, If there is any tutorial or anything i can follow that will be very nice

Multi Channel Select

It would be nice to have a MultiSelectChannel Form like the SelectChannel Form but make it possible to select multiple Channels

Return error

When i try to invite the bot in the server it return me that error

 33 |     return (await response.json()) as AccessToken;
  34 |   } else {
35 |     throw new Error('Failed to exchange token');
     |          ^
  36 |   }
  37 | }
  38 |

Credit issue

Hello, can I use this dashboard with my custom additions and with MySQL? However, is it possible to use it without giving credit?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.