Проблемы с `setruleschannel` и` setpublicupdateschannel` не обновлять объект гильдии в библиотеке Discord Im созданиеJavascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Проблемы с `setruleschannel` и` setpublicupdateschannel` не обновлять объект гильдии в библиотеке Discord Im создание

Сообщение Anonymous »

Я разрабатываю пользовательскую библиотеку Javascript Discord, и я сталкиваюсь с проблемой при попытке обновить поля GuildChanneD и publicupdateschannelid и SetPublicupdateschannel . Эти методы, похоже, выполняются без ошибок, но после обновления объект гильдии остается неизменным, как если бы значения не были обновлены вообще.'use strict';

const GuildMemberManager = require("../Managers/GuildMemberManager");
const GuildChannelManager = require("../Managers/GuildChannelManager");
const RoleManager = require("../Managers/RoleManager");
const PresenceManager = require("../Managers/PresenceManager");
const VoiceStateManager = require("../Managers/VoiceStateManager");
const StageInstanceManager = require("../Managers/StageInstanceManager");
const GuildInviteManager = require("../Managers/GuildInviteManager");
const GuildScheduledEventManager = require("../Managers/GuildScheduledEventManager");
const AutoModerationRuleManager = require("../Managers/AutoModerationRuleManager");
const GuildEmojiManager = require("../Managers/GuildEmojiManager");
const GuildStickerManager = require("../Managers/GuildStickerManager");
const Rest = require("../Rest");
const fetch = require("node-fetch")

class Guild {
constructor(data, client) {
Object.defineProperty(this, 'client', {
value: client,
enumerable: false,
writable: false,
});
this.id = data.id;
this.name = data.name;
this.icon = data.icon ?? null;
this.features = data.features ?? [];
// put GuildApplicationCommandManager heres
this.members = new GuildMemberManager(this, data.members ?? []);
this.channels = new GuildChannelManager(this, data.channels ?? []);
// put GuildBanManager here
this.roles = new RoleManager(this, this.client);
this.presences = new PresenceManager(this, data.presences ?? []);
this.voiceStates = new VoiceStateManager(this, data.voice_states ?? []);
this.stageInstances = new StageInstanceManager(this, data.stage_instances ?? []);
this.invites = new GuildInviteManager(this, data.invites ?? []);
this.scheduledEvents = new GuildScheduledEventManager(this, data.scheduled_events ?? []);
this.autoModerationRules = new AutoModerationRuleManager(this, data.auto_moderation_rules ?? []);
// put vailable: here
// put shardId: here
this.splash = data.splash ?? null;
this.banner = data.banner ?? null;
this.description = data.description ?? null;
this.verificationLevel = data.verification_level ?? 0;
this.vanityURLCode = data.vanity_url_code ?? null;
// put nsfw level here
this.premiumSubscriptionCount = data.premium_subscription_count ?? 0;
// put discovery splash here
this.memberCount = data.memberCount ?? 0;
// put larger here
// put premium progress bar here
this.afkTimeout = data.afk_timeout ?? 0;
this.afkChannelId = data.afk_channel_id ?? null;
this.systemChannelId = data.system_channel_id ?? null;
this.premiumTier = data.premium_tier ?? 0;
this.widgetEnabled = data.widget_enabled ?? false;
this.widgetChannelId = data.widget_channel_id ?? null;
this.explicitContentFilter = data.explicit_content_filter ?? 0;
this.mfaLevel = data.mfa_level ?? 0;
this.joinedTimestamp = data.joined_timestamp ?? null;
this.defaultMessageNotifications = data.default_message_notifications ?? 0;
// put SystemChannelFlagsBitField here
this.maximumMembers = data.maximum_members ?? 500000;
this.maximumPresences = data.maximum_presences ?? null;
this.maxVideoChannelUsers = data.max_video_channel_users ?? 0;
this.maxStageVideoChannelUsers = data.max_stage_video_channel_users ?? 0;
this.approximateMemberCount = data.approximate_member_count ?? 0;
this.approximatePresenceCount = data.approximate_presence_count ?? 0;
this.vanityURLUses = data.vanity_url_uses ?? 0;
this.rulesChannelId = data.rules_channel_id ?? null;
this.publicUpdatesChannelId = data.public_updates_channel_id ?? null;
this.preferredLocale = data.preferred_locale ?? 'en-US';
// put safetyAlertsChannelId here
this.ownerId = data.owner_id ?? null;
this.emojis = new GuildEmojiManager(this, data.emojis ?? []);
this.stickers = new GuildStickerManager(this, data.stickers ?? []);
}

/**
* Edits the guild using PATCH.
*
* Available options to update:
* - `name` *(string)*: The new name of the guild.
* - `afkChannelId` *(string|null)*: The ID of the voice channel where AFK users are moved.
* - `afkTimeout` *(number)*: The AFK timeout in seconds.
* - `systemChannelId` *(string|null)*: The ID of the system channel.
* - `systemChannelFlags` *(number)*: System channel flags (bitfield).
* - `verificationLevel` *(number)*: The verification level (0–4).
* - `explicitContentFilter` *(number)*: The explicit content filter level (0–2).
* - `defaultMessageNotifications` *(number)*: Default message notification level (0–1).
* - `icon` *(string|null)*: A data URI or base64 string of the guild icon. `null` to remove.
* - `splash` *(string|null)*: A data URI or base64 string of the guild splash image. `null` to remove.
* - `discoverySplash` *(string|null)*: A data URI or base64 string for the guild’s discovery splash. `null` to remove.
* - `banner` *(string|null)*: A data URI or base64 string of the guild banner. `null` to remove.
* - `rulesChannelId` *(string|null)*: The ID of the rules channel.
* - `publicUpdatesChannelId` *(string|null)*: The ID of the public updates channel.
* - `preferredLocale` *(string)*: The preferred locale (e.g., "en-US").
* - `description` *(string|null)*: The description for the guild (shown in server discovery).
*
* @param {Object} options - The guild settings to update.
* @param {string} [options.name]
* @param {string|null} [options.afkChannelId]
* @param {number} [options.afkTimeout]
* @param {string|null} [options.systemChannelId]
* @param {number} [options.systemChannelFlags]
* @param {number} [options.verificationLevel]
* @param {number} [options.explicitContentFilter]
* @param {number} [options.defaultMessageNotifications]
* @param {string|null} [options.icon]
* @param {string|null} [options.splash]
* @param {string|null} [options.discoverySplash]
* @param {string|null} [options.banner]
* @param {string|null} [options.rulesChannelId]
* @param {string|null} [options.publicUpdatesChannelId]
* @param {string} [options.preferredLocale]
* @param {string|null} [options.description]
*
* @returns {Promise} The updated Guild instance.
*/

async edit(options) {
const validProperties = [
'name',
'afkChannelId',
'afkTimeout',
'systemChannelId',
'systemChannelFlags',
'verificationLevel',
'explicitContentFilter',
'defaultMessageNotifications',
'icon',
'splash',
'discoverySplash',
'banner',
'rulesChannelId',
'publicUpdatesChannelId',
'preferredLocale',
'description'
];

for (const key in options) {
if (!validProperties.includes(key)) {
throw new Error(`Invalid property: ${key}`);
}
}

const requestData = {
name: 'name' in options ? options.name : this.name,
afk_channel_id: 'afkChannelId' in options ? options.afkChannelId : this.afkChannelId,
afk_timeout: 'afkTimeout' in options ? options.afkTimeout : this.afkTimeout,
system_channel_id: 'systemChannelId' in options ? options.systemChannelId : this.systemChannelId,
system_channel_flags: 'systemChannelFlags' in options ? options.systemChannelFlags : this.systemChannelFlags,
verification_level: 'verificationLevel' in options ? options.verificationLevel : this.verificationLevel,
explicit_content_filter: 'explicitContentFilter' in options ? options.explicitContentFilter : this.explicitContentFilter,
default_message_notifications: 'defaultMessageNotifications' in options ? options.defaultMessageNotifications : this.defaultMessageNotifications,
icon: 'icon' in options ? options.icon : this.icon,
splash: 'splash' in options ? options.splash : this.splash,
discovery_splash: 'discoverySplash' in options ? options.discoverySplash : this.discoverySplash,
banner: 'banner' in options ? options.banner : this.banner,
rules_channel_id: 'rulesChannelId' in options ? options.rulesChannelId : this.rulesChannelId,
public_updates_channel_id: 'publicUpdatesChannelId' in options ? options.publicUpdatesChannelId : this.publicUpdatesChannelId,
preferred_locale: 'preferredLocale' in options ? options.preferredLocale : this.preferredLocale,
description: 'description' in options ? options.description : this.description
};

const updatedData = await Rest.patch(this.client.token, `/guilds/${this.id}`, requestData);

Object.assign(this, {
name: updatedData.name,
afkChannelId: updatedData.afk_channel_id,
afkTimeout: updatedData.afk_timeout,
systemChannelId: updatedData.system_channel_id,
systemChannelFlags: updatedData.system_channel_flags,
verificationLevel: updatedData.verification_level,
explicitContentFilter: updatedData.explicit_content_filter,
defaultMessageNotifications: updatedData.default_message_notifications,
icon: updatedData.icon,
splash: updatedData.splash,
discoverySplash: updatedData.discovery_splash,
banner: updatedData.banner,
rulesChannelId: updatedData.rules_channel_id,
publicUpdatesChannelId: updatedData.public_updates_channel_id,
preferredLocale: updatedData.preferred_locale,
description: updatedData.description
});

return this;
}

async setName(name) {
if (typeof name !== 'string' || name.length < 1 || name.length > 100) {
throw new Error("Name must be a string between 1 and 100 characters.");
}

return await this.edit({ name });
}

async setAFKChannel(channel) {
const channelId = typeof channel === 'string' ? channel : channel?.id;

if (!channelId || typeof channelId !== 'string') {
throw new Error("[Vunsh]");
}

const fullChannel = await this.channels.fetch(channelId);

if (!fullChannel || fullChannel.type !== 2) {
throw new Error("AFK channel must be a voice channel.");
}

return await this.edit({ afkChannelId: channelId });
}

async setAFKTimeout(timeout) {
const validTimeouts = [60, 300, 900, 1800, 3600];
if (!validTimeouts.includes(timeout)) {
throw new Error("Timeout must be one of the following values in seconds: 60, 300, 900, 1800, or 3600.");
}

const updatedData = await Rest.patch(this.client.token, `/guilds/${this.id}`, {
afk_timeout: timeout
});

Object.assign(this, {
afkTimeout: updatedData.afk_timeout
});

return this;
}

async setIcon(icon) {
if (icon !== null && typeof icon !== 'string') {
throw new Error("Icon must be a string (data URI, URL) or null to remove it.");
}

if (icon === null) {
return await this.edit({ icon: null });
}

if (icon.startsWith('http')) {
try {
const res = await fetch(icon);
if (!res.ok) throw new Error(`Failed to fetch image from URL: ${res.statusText}`);
const contentType = res.headers.get('content-type');
const buffer = await res.buffer();
const base64 = buffer.toString('base64');
icon = `data:${contentType};base64,${base64}`;
} catch (err) {
throw new Error(`Failed to process image URL: ${err.message}`);
}
}

return await this.edit({ icon });
}

async setBanner(banner) {
if (banner !== null && typeof banner !== 'string') {
throw new Error("Banner must be a string (data URI, URL) or null to remove it.");
}

if (banner === null) {
return await this.edit({ banner: null });
}

if (banner.startsWith('http')) {
try {
const res = await fetch(banner);
if (!res.ok) throw new Error(`Failed to fetch image from URL: ${res.statusText}`);
const contentType = res.headers.get('content-type');
const buffer = await res.buffer();
const base64 = buffer.toString('base64');
banner = `data:${contentType};base64,${base64}`;
} catch (err) {
throw new Error(`Failed to process banner image URL: ${err.message}`);
}
}

return await this.edit({ banner });
}

async setSplash(splash) {
if (splash !== null && typeof splash !== 'string') {
throw new Error("Splash must be a string (data URI, URL) or null to remove it.");
}

if (splash === null) {
return await this.edit({ splash: null });
}

if (splash.startsWith('http')) {
try {
const res = await fetch(splash);
if (!res.ok) throw new Error(`Failed to fetch splash image from URL: ${res.statusText}`);
const contentType = res.headers.get('content-type');
const buffer = await res.buffer();
const base64 = buffer.toString('base64');
splash = `data:${contentType};base64,${base64}`;
} catch (err) {
throw new Error(`Failed to process splash image URL: ${err.message}`);
}
}

return await this.edit({ splash });
}

async setDiscoverySplash(splash) {
if (splash !== null && typeof splash !== 'string') {
throw new Error("Discovery splash must be a string (data URI, URL) or null to remove it.");
}

if (splash === null) {
return await this.edit({ discovery_splash: null });
}

if (splash.startsWith('http')) {
try {
const res = await fetch(splash);
if (!res.ok) throw new Error(`Failed to fetch discovery splash image from URL: ${res.statusText}`);
const contentType = res.headers.get('content-type');
const buffer = await res.buffer();
const base64 = buffer.toString('base64');
splash = `data:${contentType};base64,${base64}`;
} catch (err) {
throw new Error(`Failed to process discovery splash image URL: ${err.message}`);
}
}

return await this.edit({ discovery_splash: splash });
}

async setSystemChannel(channel) {
let channelId = null;

if (typeof channel === 'string') {
channelId = channel;
} else if (typeof channel === 'object' && channel !== null && 'id' in channel) {
channelId = channel.id;
} else if (channel !== null) {
throw new Error("Channel must be a string (channel ID), an object with an 'id' property, or null.");
}

return await this.edit({ systemChannelId: channelId });
}

async setSystemChannelFlags(flags) {
if (typeof flags !== 'number') {
throw new Error("Flags must be a number representing a bitfield.");
}

return await this.edit({ systemChannelFlags: flags });
}

async setPublicUpdatesChannel(channel) {
const channelId = typeof channel === 'string' ? channel : channel?.id;

if (!channelId || typeof channelId !== 'string') {
throw new Error("Invalid channel provided. Must be a string ID or a channel object with an ID.");
}

const fullChannel = await this.channels.fetch(channelId);
if (!fullChannel) {
throw new Error("Channel not found in this guild.");
}

return await this.edit({ publicUpdatesChannelId: channelId });
}

async setRulesChannel(channel) {
const channelId = typeof channel === 'string' ? channel : channel?.id;

if (!channelId || typeof channelId !== 'string') {
throw new Error("Invalid channel ID.");
}

const fullChannel = await this.channels.fetch(channelId);

if (!fullChannel || ![0, 5].includes(fullChannel.type)) {
throw new Error("Rules channel must be a text or announcement channel.");
}

return await this.edit({ rulesChannelId: channelId });
}
}

module.exports = Guild;
< /code>
Это мой файл rest.js < /p>
/**
* A utility class for making HTTP requests to the Discord API.
*/
module.exports = class Rest {
/**
* Makes a GET request to the Discord API.
*
* @param {string} authorization - The bot token.
* @param {string} endpoint - The API endpoint to send the GET request to (e.g., `/guilds/{guildId}`).
* @returns {Promise} A promise that resolves to the parsed JSON response from the API.
* @throws {Error} Throws an error if the API request fails or returns an invalid response.
* @private
*/
static async get(authorization, endpoint) {
const response = await fetch(`https://discord.com/api/v10${endpoint}`, {
method: 'GET',
headers: {
'Authorization': `Bot ${authorization}`,
'Content-Type': 'application/json'
}
});

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

return await response.json();
}

/**
* Makes a PATCH request to the Discord API.
*
* @param {string} authorization - The bot token.
* @param {string} endpoint - The API endpoint to send the PATCH request to (e.g., `/guilds/{guildId}`).
* @param {Object} data - The JSON body data to send with the PATCH request.
* @returns {Promise} A promise that resolves to the parsed JSON response from the API.
* @throws {Error} Throws an error if the API request fails or returns an invalid response.
* @private
*/
static async patch(authorization, endpoint, data) {
const response = await fetch(`https://discord.com/api/v10${endpoint}`, {
method: 'PATCH',
headers: {
'Authorization': `Bot ${authorization}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

return await response.json();
}
};


Подробнее здесь: https://stackoverflow.com/questions/795 ... ng-guild-o
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Javascript»