📜  discord.js 原因 (1)

📅  最后修改于: 2023-12-03 15:00:25.517000             🧑  作者: Mango

Discord.js

Discord.js是一个用于开发Discord机器人的基于Node.js的库。它提供了一系列的方法和事件,方便开发者与Discord API进行交互。

安装

使用npm进行安装:

npm install discord.js
使用
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('ready', () => {
   console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', message => {
   if (message.content === 'ping') {
      message.reply('pong');
   }
});

client.login('your-token-goes-here');

Discord.js文档

提供的方法
  • Client - 与DiscordAPI建立连接
  • Guild - Discord服务器相关
  • User - Discord用户相关
  • Message - Discord消息相关
  • Channel - Discord频道相关
  • Role - Discord角色相关
  • Voice - Discord语音相关
  • Emoji - Discord表情相关
提供的事件
  • ready - bot成功登录到Discord
  • message - 当有新消息发送到频道时触发
  • guildCreate - 当bot加入到一个新的服务器时触发
  • guildDelete - 当bot被从一个服务器移除时触发
示例
发送图片
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
  if (message.content === 'ping') {
    message.reply('pong');
  } else if (message.content === 'image') {
    message.channel.send({
      files: [{
        attachment: 'https://i.imgur.com/w3duR07.png',
        name: 'image.png'
      }]
    })
      .then(console.log)
      .catch(console.error);
  }
});

client.login('your-token-goes-here');
播放音乐
const Discord = require('discord.js');
const ytdl = require('ytdl-core');

const client = new Discord.Client();
const queue = new Map();

client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', async message => {
  if (message.content.startsWith('!play')) {
    const args = message.content.split(' ');
    const voiceChannel = message.member.voiceChannel;
    if (!voiceChannel) return message.reply('请先进入语音频道!');
    const permissions = voiceChannel.permissionsFor(message.client.user);
    if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
      return message.reply('我需要加入和讲话的权限!');
    }

    const songInfo = await ytdl.getInfo(args[1]);
    const song = {
      title: songInfo.title,
      url: songInfo.video_url,
    };

    if (!queue.has(message.guild.id)) {
      queue.set(message.guild.id, {
        textChannel: message.channel,
        voiceChannel: voiceChannel,
        connection: null,
        songs: [],
        volume: 5,
        playing: true,
      });

      try {
        const connection = await voiceChannel.join();
        queue.get(message.guild.id).connection = connection;
        play(message.guild, queue.get(message.guild.id).songs[0]);
      } catch (error) {
        console.error(`我无法加入您的语音频道: ${error}`);
        queue.delete(message.guild.id);
        return message.channel.send(`我无法加入您的语音频道: ${error}`);
      }
    } else {
      queue.get(message.guild.id).songs.push(song);
      return message.channel.send(`**${song.title}** 已加入队列!`);
    }
  } else if (message.content.startsWith('!skip')) {
    if (!message.member.voiceChannel) return message.reply('请先进入语音频道!');
    if (!queue.has(message.guild.id)) return message.reply('当前没有播放任何音乐!');
    queue.get(message.guild.id).connection.dispatcher.end();
  }
});

function play(guild, song) {
  const queue = guild.queue;
  const serverQueue = queue.get(guild.id);

  if (!song) {
    serverQueue.textChannel.send('音乐队列已完成播放');
    serverQueue.voiceChannel.leave();
    queue.delete(guild.id);
    return;
  }

  const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
    .on('end', () => {
      console.log('音乐已完成播放');
      serverQueue.songs.shift();
      play(guild, serverQueue.songs[0]);
    })
    .on('error', error => {
      console.error(error);
    });
  dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
}

client.login('your-token-goes-here');
发送消息到指定用户
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', async message => {
  if (message.content === '!dm') {
    const user = client.users.get('user-id-here');
    user.send('晚上好!');
  }
});

client.login('your-token-goes-here');
结论

Discord.js是一个用户友好的库,简化了与Discord API进行交互的过程。在npm的帮助下,它可以很容易地安装和使用。它还提供了很多有用的方法和事件,方便开发人员开发出简单到复杂的机器人。