Giter VIP home page Giter VIP logo

pioucord's Introduction

Pioucord

npm download github version

Don't except too much from this package for now, if you want something easier to use , then use discord.js.

pioucord is an ES package that allows you to create a discord bot with ease. It helps in different point, such as:

  • Connection to the gateway with a WebSocket (including shards)
  • Requests to the API
  • Rate limits

Installation

npm install pioucord

A simple bot

To know more about intents, check here.

To know more about presence, check here.

import {Client, ActivityType, Routes} from 'pioucord';

const client = new Client({
    intents: ['Guilds', 'GuildMessages', 'MessageContent'],
    presence: {
        status: 'dnd',
        activities: [
            {
                name: '!ping',
                type: ActivityType.Playing
            }
        ]
    }
});

client.ws.on('READY', (data) => {
    console.log(`Logged in as ${client.user.username}#${client.user.discriminator} (${client.user.id})`);
});

client.ws.on('MESSAGE_CREATE', message => {
    if (message.content == "!ping") {
        client.rest.post(Routes.channelMessages(message.channel_id), {
            content: 'Pong!'
        });
    }
});

client.login('Some secret token goes here');

Here, when the bot will see a message with !ping as content, it will send Pong! in the same channel.

Since there's no classes for now, to reply to a message, you need to add the field message_reference in the message payload, check here for more infos.

It will look like:

client.rest.post(Routes.channelMessages(message.channel_id), {
    content: 'Pong!',
    message_reference: {
        message_id: message.id
    }
});

You may have noticed two points:

  • We should use client.ws.on instead of client.on to listen to events. (client.on is not implemented yet, and will be used for constructed objects)
  • We can use client.user as soon as the READY event is thrown.
  • Events are in screaming case, and the provided parameters are raw data from the gateway, check event list here.

Sharding

To know more about shards, check here.

You can use specific shards to start your bot with:

import {Client} from 'pioucord';

const client = new Client({
    intents: 'some intents, check above',
    shards: [0, 2],
    shardsCount: 3
});

If you don't put any, it will identify to the gateway without providing shards.

Uploading files

To know how files upload works, check here.

To upload files, you just need to use the files field in the payload, and put an array of files.

// ...
client.ws.on('MESSAGE_CREATE', message => {
    if (message.content == "!image") {
        client.rest.post(Routes.channelMessages(message.channel_id), {
            content: 'Beautiful image!',
            message_reference: {
                message_id: message.id
            },
            files: [{
              name: 'image.png',
              description: 'Image',
              file: "A buffer goes here"
            }]
        });
    }
});
// ...

Handler

It isn't supported by the package itself, it's much better to let the user create it himself.

A little handler example

If you want, you can create a commands' handler, which will make your bot easier to manage.

You can create an events one if you want, but I will not show it here.

import {readdir} from 'node:fs/promises'; // Used to read dirs, need an absolute path
import {Client} from 'pioucord';

// Simple client creation
const client = new Client({
    intents: ['GuildMessages', 'MessageContent']
});

// Reading the commands folder
client.commands = new Map();
const path = 'absolute path goes here';
for (const file of await readdir(path)) {
    const command = (await import('file://' + path + file)).default;
    client.commands.set(command.name, command);
}
;

// Listening messages
const prefix = '!';
client.ws.on('MESSAGE_CREATE', message => {
    if (message.author.bot || !message.content.startsWith(prefix)) return;

    const args = message.content.split(/ +/);
    const command = client.commands.get(args.shift().slice(prefix.length));

    if (!command) return;

    command.execute(message, args);
});

client.login('token goes here as always');

And then, put some files in the commands folder which looks like:

import {Routes} from 'pioucord';

export default {
    name: 'ping',
    execute: (message, args) => {
        // The client is in each events objects
        message.client.rest.post(Routes.channelMessages(message.channel_id), {
            content: 'Pong!',
            message_reference: {
                message_id: message.id
            }
        });
    }
};

You can access the client from every event.

Call it as you want, it won't change anything, but try to make something understandable.

Upgrade the handler

You may be tired because of all these client.rest, because the package still don't have classes (it should be out for the V2).

If you don't want to wait (and you are right), you are free to add some functions to your handler, here is a little example:

client.on('MESSAGE_CREATE', message => {
    if (message.author.bot || !message.content.startsWith(prefix)) return;

    const args = message.content.split(/ +/);
    const command = client.commands.get(args.shift().slice(prefix.length));

    if (!command) return;

    // Here, modifications
    const functions = {
        channelSend: (data) => {
            return client.rest.post(Routes.channelMessages(message.channel_id), data);
        },
        messageReply: (data) => {
            return client.rest.post(Routes.channelMessages(message.channel_id), Object.assign(data,
                {
                    message_reference: {
                        message_id: message.id
                    }
                }
            ));
        }
    };

    // Don't forget to send them
    command.execute(message, args, functions);
});

And then, the ping command file:

export default {
    name: 'ping',
    execute: (message, args, functions) => {
        functions.messageReply({content: 'Pong!'});
    }
};

See? Much clearer!

Debug

That's not something very important, but you can use the debug event on the ws, like:

client.ws.on('debug', (shardId, text) => {
    console.log(`Shard ${shardId ?? 'MAIN'} | ${text}`);
});

pioucord's People

Contributors

nanapiou avatar 10hecone avatar

Stargazers

Foxys_ avatar  avatar  avatar

Watchers

 avatar

Forkers

10hecone

pioucord's Issues

Ajouter des informations dans la class Client

Bonjour, est-ce possible d'ajouter des informations en plus pour le client ? Par exemple avoir directement les infos dès guilds, et tout. Des infos utiles pour eviter qu'on fasse des requetes à repetition.

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.