Set channel id for DiscordBot for multiple servers

丶灬走出姿态 提交于 2021-02-20 04:56:51

问题


Could someone help me set command to set channel for specific server so that it does not interfere with each other? Actually I have this:

var testChannel = bot.channels.find(channel => channel.id === "hereMyChannelID");

I want to set command which Owner can use to set channel id for his server.


回答1:


You can accomplish this task by creating a JSON file to hold the specified channels of each guild. Then, in your command, simply define the channel in the JSON. After that, anywhere else in your code, you can then find the channel specified by a guild owner and interact with it.

Keep in mind, a database would be a better choice due to the speed comparison and much lower risk of corruption. Find the right one for you and your code, and replace this JSON setup with the database.

guilds.json setup:

{
  "guildID": {
    "channel": "channelID"
  }
}

Command code:

// -- Define these variables outside of the command. --
const guilds = require('./guilds.json');
const fs = require('fs');
// ----------------------------------------------------

const args = message.content.trim().split(/ +/g); // Probably already declared.

try {
  if (message.author.id !== message.guild.ownerID) return await message.channel.send('Access denied.');

  if (!message.mentions.channels.first()) return await message.channel.send('Invalid channel.'); 

  guilds[message.guild.id].channel = message.mentions.channels.first().id;
  fs.writeFileSync('./guilds.json', JSON.stringify(guilds));
  await message.channel.send('Successfully changed channel.');
} catch(err) {
  console.error(err);
}

Somewhere else:

const guilds = require('./guilds.json');

const channel = client.channels.get(guilds[message.guild.id].channel);

if (channel) {
  channel.send('Found the right one!')
    .catch(console.error);
} else console.error('Invalid or undefined channel.');


来源:https://stackoverflow.com/questions/56262813/set-channel-id-for-discordbot-for-multiple-servers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!