PAdventures
PAdventures
Explore posts from servers
DIAdiscord.js - Imagine a bot
Created by PAdventures on 1/7/2024 in #djs-questions
AutoModerationRuleUpdate -> OldRule is null on rule actions update
the old rule is null when I update the rule's actions (timeout, alert message). Is this normal behaviour? Yes, i am aware that the old rule can be null
3 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 12/27/2023 in #djs-questions
Event Emitter emits custom event twice
client.emit("loggerAdd", loggerData)
console.log("emitted")
client.emit("loggerAdd", loggerData)
console.log("emitted")
client.on("loggerAdd", () => {
console.log("received")
})
client.on("loggerAdd", () => {
console.log("received")
})
console
emitted
received
received
emitted
received
received
my code doesn't look exactly like this by similar
4 replies
DTDrizzle Team
Created by PAdventures on 12/19/2023 in #help
Dizzle Kit: Push altering unchanged column
CREATE TABLE `economy_profiles` (
`member_id` bigint unsigned NOT NULL,
`guild_id` bigint unsigned NOT NULL,
`wallet` int unsigned NOT NULL,
`bank` int unsigned NOT NULL,
`safe` int unsigned NOT NULL,
- `bank_level` tinyint unsigned NOT NULL DEFAULT '0',
- `safe_level` tinyint unsigned NOT NULL DEFAULT '0',
+ `bank_level` tinyint unsigned NOT NULL,
+ `safe_level` tinyint unsigned NOT NULL,
`created_at` date NOT NULL,
`updated_at` date NOT NULL,
PRIMARY KEY (`member_id`, `guild_id`),
UNIQUE KEY `economy_profiles_member_id_guild_id_unique` (`member_id`, `guild_id`),
UNIQUE KEY `member_id_guild_id_idx` (`member_id`, `guild_id`)
) ENGINE InnoDB,
CHARSET utf8mb4,
COLLATE utf8mb4_0900_ai_ci;
CREATE TABLE `economy_profiles` (
`member_id` bigint unsigned NOT NULL,
`guild_id` bigint unsigned NOT NULL,
`wallet` int unsigned NOT NULL,
`bank` int unsigned NOT NULL,
`safe` int unsigned NOT NULL,
- `bank_level` tinyint unsigned NOT NULL DEFAULT '0',
- `safe_level` tinyint unsigned NOT NULL DEFAULT '0',
+ `bank_level` tinyint unsigned NOT NULL,
+ `safe_level` tinyint unsigned NOT NULL,
`created_at` date NOT NULL,
`updated_at` date NOT NULL,
PRIMARY KEY (`member_id`, `guild_id`),
UNIQUE KEY `economy_profiles_member_id_guild_id_unique` (`member_id`, `guild_id`),
UNIQUE KEY `member_id_guild_id_idx` (`member_id`, `guild_id`)
) ENGINE InnoDB,
CHARSET utf8mb4,
COLLATE utf8mb4_0900_ai_ci;
I will push this to planetscale. I run the push again without doing anything and this happens:
CREATE TABLE `economy_profiles` (
`member_id` bigint unsigned NOT NULL,
`guild_id` bigint unsigned NOT NULL,
`wallet` int unsigned NOT NULL,
`bank` int unsigned NOT NULL,
`safe` int unsigned NOT NULL,
- `bank_level` tinyint unsigned NOT NULL,
- `safe_level` tinyint unsigned NOT NULL,
+ `bank_level` tinyint unsigned NOT NULL DEFAULT '0',
+ `safe_level` tinyint unsigned NOT NULL DEFAULT '0',
`created_at` date NOT NULL,
`updated_at` date NOT NULL,
PRIMARY KEY (`member_id`, `guild_id`),
UNIQUE KEY `economy_profiles_member_id_guild_id_unique` (`member_id`, `guild_id`),
UNIQUE KEY `member_id_guild_id_idx` (`member_id`, `guild_id`)
) ENGINE InnoDB,
CHARSET utf8mb4,
COLLATE utf8mb4_0900_ai_ci;
CREATE TABLE `economy_profiles` (
`member_id` bigint unsigned NOT NULL,
`guild_id` bigint unsigned NOT NULL,
`wallet` int unsigned NOT NULL,
`bank` int unsigned NOT NULL,
`safe` int unsigned NOT NULL,
- `bank_level` tinyint unsigned NOT NULL,
- `safe_level` tinyint unsigned NOT NULL,
+ `bank_level` tinyint unsigned NOT NULL DEFAULT '0',
+ `safe_level` tinyint unsigned NOT NULL DEFAULT '0',
`created_at` date NOT NULL,
`updated_at` date NOT NULL,
PRIMARY KEY (`member_id`, `guild_id`),
UNIQUE KEY `economy_profiles_member_id_guild_id_unique` (`member_id`, `guild_id`),
UNIQUE KEY `member_id_guild_id_idx` (`member_id`, `guild_id`)
) ENGINE InnoDB,
CHARSET utf8mb4,
COLLATE utf8mb4_0900_ai_ci;
15 replies
DTDrizzle Team
Created by PAdventures on 12/10/2023 in #help
ExecutedQuery data question
what do these attributes mean when it comes to planetscale? it's quite confusing
headers: string[];
types: Types;
rows: Row[];
fields: Field[];
size: number;
statement: string;
insertId: string;
rowsAffected: number;
time: number;
headers: string[];
types: Types;
rows: Row[];
fields: Field[];
size: number;
statement: string;
insertId: string;
rowsAffected: number;
time: number;
I assume time is how long the query took rowsAffected is that row read/row returned? rows I assume are the rows that were returned fields is assume are the table fields statment i assume is the raw SQL statement the others I have no clue
2 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 12/6/2023 in #djs-questions
ActionRowBuilder type error with EditReply
public paginationButtons(): ButtonBuilder[] {
return [
new ButtonBuilder().setCustomId('pg-prev').setLabel('Previous').setStyle(ButtonStyle.Primary).setEmoji('⬅️'),
new ButtonBuilder().setCustomId('pg-home').setLabel('Home').setStyle(ButtonStyle.Secondary).setEmoji('🏡'),
new ButtonBuilder().setCustomId('pg-next').setLabel('Next').setStyle(ButtonStyle.Primary).setEmoji('➡️'),
];
}

public async ChatInputEmbedPagination(interaction: ChatInputCommandInteraction<CacheType>, pages: EmbedBuilder[], time: number = 30 * 1000, ephemeral?: boolean): Promise<Message<boolean>> {
if (interaction.deferred || interaction.replied) {
throw new Error("Interaction already deferred or replied");
}

await interaction.deferReply({ ephemeral, fetchReply: true });

if (pages.length === 1) {
return await interaction.editReply({
embeds: pages,
components: [],
});
}

const prev = this.paginationButtons()[0].setDisabled(true);
const home = this.paginationButtons()[1].setDisabled(true);
const next = this.paginationButtons()[2].setDisabled(true);

const buttons = new ActionRowBuilder().addComponents([prev, home, next]);

let page = 0;

const msg = await interaction.editReply({
embeds: [pages[page]],
components: [buttons]
})
}
public paginationButtons(): ButtonBuilder[] {
return [
new ButtonBuilder().setCustomId('pg-prev').setLabel('Previous').setStyle(ButtonStyle.Primary).setEmoji('⬅️'),
new ButtonBuilder().setCustomId('pg-home').setLabel('Home').setStyle(ButtonStyle.Secondary).setEmoji('🏡'),
new ButtonBuilder().setCustomId('pg-next').setLabel('Next').setStyle(ButtonStyle.Primary).setEmoji('➡️'),
];
}

public async ChatInputEmbedPagination(interaction: ChatInputCommandInteraction<CacheType>, pages: EmbedBuilder[], time: number = 30 * 1000, ephemeral?: boolean): Promise<Message<boolean>> {
if (interaction.deferred || interaction.replied) {
throw new Error("Interaction already deferred or replied");
}

await interaction.deferReply({ ephemeral, fetchReply: true });

if (pages.length === 1) {
return await interaction.editReply({
embeds: pages,
components: [],
});
}

const prev = this.paginationButtons()[0].setDisabled(true);
const home = this.paginationButtons()[1].setDisabled(true);
const next = this.paginationButtons()[2].setDisabled(true);

const buttons = new ActionRowBuilder().addComponents([prev, home, next]);

let page = 0;

const msg = await interaction.editReply({
embeds: [pages[page]],
components: [buttons]
})
}
error
Type 'ActionRowBuilder<AnyComponentBuilder>' is not assignable to type 'APIActionRowComponent<APIMessageActionRowComponent> | JSONEncodable<APIActionRowComponent<APIMessageActionRowComponent>> | ActionRowData<...>'.
Property 'type' is missing in type 'ActionRowBuilder<AnyComponentBuilder>' but required in type 'ActionRowData<MessageActionRowComponentData | MessageActionRowComponentBuilder>'.ts(2322)
Type 'ActionRowBuilder<AnyComponentBuilder>' is not assignable to type 'APIActionRowComponent<APIMessageActionRowComponent> | JSONEncodable<APIActionRowComponent<APIMessageActionRowComponent>> | ActionRowData<...>'.
Property 'type' is missing in type 'ActionRowBuilder<AnyComponentBuilder>' but required in type 'ActionRowData<MessageActionRowComponentData | MessageActionRowComponentBuilder>'.ts(2322)
The package manager i use reciple has the same discord.js version as mine
8 replies
DTDrizzle Team
Created by PAdventures on 11/28/2023 in #help
Migration Confirmation/Help with PlanetScale
I know I can test this myself but I want to reduce the connections to my PlanetScale database. So, I have my main branch which has a password to it, and a development branch off of the main branch with it's own password. If I use the dev url in the migration config file and main url for the drizzle connection will this cause any issues. Here is what I have done:
//drizzle.config.ts
import * as dotenv from 'dotenv';
import type { Config } from 'drizzle-kit';

dotenv.config();

export default {
schema: './db/schema/*',
driver: 'mysql2',
out: './drizzle',
dbCredentials: {
uri: process.env.DATABASE_DEV_URL ?? ''
}
} satisfies Config;
//drizzle.config.ts
import * as dotenv from 'dotenv';
import type { Config } from 'drizzle-kit';

dotenv.config();

export default {
schema: './db/schema/*',
driver: 'mysql2',
out: './drizzle',
dbCredentials: {
uri: process.env.DATABASE_DEV_URL ?? ''
}
} satisfies Config;
//drizzle connection
export class BaseUtility extends BaseModule {
// cool stuff up here

private planetScaleClient: Client = new Client({ url: process.env.DATABASE_MAIN_URL, fetch: undiciFetch });
private planetScaleAdapter: PrismaPlanetScale = new PrismaPlanetScale(this.planetScaleClient);
public prisma: PrismaClient = new PrismaClient({ adapter: this.planetScaleAdapter });
// more cool stuff down here
}
//drizzle connection
export class BaseUtility extends BaseModule {
// cool stuff up here

private planetScaleClient: Client = new Client({ url: process.env.DATABASE_MAIN_URL, fetch: undiciFetch });
private planetScaleAdapter: PrismaPlanetScale = new PrismaPlanetScale(this.planetScaleClient);
public prisma: PrismaClient = new PrismaClient({ adapter: this.planetScaleAdapter });
// more cool stuff down here
}
1 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 10/23/2023 in #djs-questions
@discordjs/opus not installing for macOS
Ive literally tried everything
8 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 9/23/2023 in #djs-questions
Buttons will not re-enable
I have a pagination system that should disable and enable buttons depending on what page the user is on. The buttons will always stay on their default disabled state and won't change whenever I editReply the message Collector
collector.on('collect', async (button) => {
await button.deferUpdate();
if (button.customId === 'help-v2-previous-page') {
if (pageNumber > -1) {
pageNumber--;
}
}
else if (button.customId === 'help-v2-home') {
pageNumber = -1;
}
else if (button.customId === 'help-v2-next-page') {
if (pageNumber < pages.length - 1) {
pageNumber++;
}
}

// Only doing this because I'm trying to solve the issue
let button1;
let button2;
let button3;
if (pageNumber === -1) {
button1 = true;
button2 = true;
}
else {
button1 = false;
button2 = false;
}

if (pageNumber < pages.length - 1) {
button3 = false;
}
else {
button3 = true;
}

await interaction.editReply({
embeds: [getPageCommandEmbed(pageNumber)],
compontents: [buttonRow(button1, button2, button3)],
});

collector.resetTimer();
});
collector.on('collect', async (button) => {
await button.deferUpdate();
if (button.customId === 'help-v2-previous-page') {
if (pageNumber > -1) {
pageNumber--;
}
}
else if (button.customId === 'help-v2-home') {
pageNumber = -1;
}
else if (button.customId === 'help-v2-next-page') {
if (pageNumber < pages.length - 1) {
pageNumber++;
}
}

// Only doing this because I'm trying to solve the issue
let button1;
let button2;
let button3;
if (pageNumber === -1) {
button1 = true;
button2 = true;
}
else {
button1 = false;
button2 = false;
}

if (pageNumber < pages.length - 1) {
button3 = false;
}
else {
button3 = true;
}

await interaction.editReply({
embeds: [getPageCommandEmbed(pageNumber)],
compontents: [buttonRow(button1, button2, button3)],
});

collector.resetTimer();
});
buttonRow()
const buttonRow = (st1, st2, st3) => {
return new ActionRowBuilder()
.setComponents(prevPage(st1), home(st2), nextPage(st3));
};
const buttonRow = (st1, st2, st3) => {
return new ActionRowBuilder()
.setComponents(prevPage(st1), home(st2), nextPage(st3));
};
button example: prevPage()
const prevPage = (state) => {
return new ButtonBuilder()
.setCustomId('help-v2-previous-page')
.setLabel('Previous Page')
.setEmoji('⬅️')
.setStyle(ButtonStyle.Primary)
.setDisabled(state);
};
const prevPage = (state) => {
return new ButtonBuilder()
.setCustomId('help-v2-previous-page')
.setLabel('Previous Page')
.setEmoji('⬅️')
.setStyle(ButtonStyle.Primary)
.setDisabled(state);
};
4 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 9/4/2023 in #djs-questions
Message Collector Filter not working
The filter is not working for some reason
console.log(codeValue);

const filterDelete = msg => msg.author.id === user.id && msg.content.toLowerCase() === `delete ${codeValue}`;

const collector = interaction.channel.createMessageCollector({ filter: filterDelete, time: 10_000 });
console.log(codeValue);

const filterDelete = msg => msg.author.id === user.id && msg.content.toLowerCase() === `delete ${codeValue}`;

const collector = interaction.channel.createMessageCollector({ filter: filterDelete, time: 10_000 });
Logs
cbz5yhifqx
cbz5yhifqx
what i type in the channel delete cbz5yhifqx collector
collector.on('collect', async (msg) => {
await msg.delete();
await Code.deleteOne({ _id: code._id });
interaction.editReply({ embeds: [success ] });
});
collector.on('collect', async (msg) => {
await msg.delete();
await Code.deleteOne({ _id: code._id });
interaction.editReply({ embeds: [success ] });
});
collector doesnt do anything
11 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 7/19/2023 in #djs-questions
Custom Emoji formatting issue
I am trying to use custom emojis from a server I own for my bot. The bot is in this server and has admin perms in a different server plus there are no custom emoji restrictions in the channel where the bot is trying to use the emojis. I have tried many methods to use the emojis. For example:
'<:EMOJI_NAME_HERE:EMOJI_ID_HERE>'
'<:EMOJI_NAME_HERE:EMOJI_ID_HERE>'
Plus
interaction.client.emojis.cache.get("EMOJI_ID_HERE").toString()
interaction.client.emojis.cache.get("EMOJI_ID_HERE").toString()
And
formatEmoji("EMOJI_ID_HERE", false).replace("_", "EMOJI_NAME_HERE")
formatEmoji("EMOJI_ID_HERE", false).replace("_", "EMOJI_NAME_HERE")
Each just ends up in the bot sending the emoji name wrapped around colons. I have triple-checked that the emoji names are correct as well as their ids. Any idea on how to solve this?
10 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 7/6/2023 in #djs-questions
Fetching Guild Commands returns nothing
I am using the ApplicationCommandPermissionsUpdate event. I am trying to fetch the command using the guild.commands.fetch() method. This always returns empty and i'm not sure why. Here is my some code for the ApplicationCommandPermissionsUpdate file:
module.exports = {
name: Events.ApplicationCommandPermissionsUpdate,
on: true,
/** @param {ApplicationCommand} data @param {Client} client */
async execute(data, client) {
//STUFF HAPPENS HERE
let command;

try {
command = await guild.commands.fetch({ force: true });
console.log(command);
console.log(command.map(c => c.name));
} catch (error) {
return console.log(error);
};

//STUFF HAPPENS AFTER HERE
},
};
module.exports = {
name: Events.ApplicationCommandPermissionsUpdate,
on: true,
/** @param {ApplicationCommand} data @param {Client} client */
async execute(data, client) {
//STUFF HAPPENS HERE
let command;

try {
command = await guild.commands.fetch({ force: true });
console.log(command);
console.log(command.map(c => c.name));
} catch (error) {
return console.log(error);
};

//STUFF HAPPENS AFTER HERE
},
};
Output for the logged collection, array and error
Collection(0) [Map] {}
[]
//No error
Collection(0) [Map] {}
[]
//No error
Please note that there are application commands in the server
12 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 5/23/2023 in #djs-questions
How to detect if a string is a snowflake and check what type of snowflake it is?
I've been doing this but i want to know if there is an easier way
const snowflake = options.getString("snowflake");
const guildSearch = client.guilds.cache.find(server => server.id === snowflake);
const userSearch = guild.members.cache.find(member => member.id === snowflake);
const channelSearch = guild.channels.cache.find(channel => channel.id === snowflake);
const roleSearch = guild.roles.cache.find(role => role.id === snowflake);
const commandSearch = guild.commands.cache.find(command => command.id === snowflake);
const emojiSearch = guild.emojis.cache.find(emoji => emoji.id === snowflake);
const stickerSearch = guild.stickers.cache.find(sticker => sticker.id === snowflake);
const snowflake = options.getString("snowflake");
const guildSearch = client.guilds.cache.find(server => server.id === snowflake);
const userSearch = guild.members.cache.find(member => member.id === snowflake);
const channelSearch = guild.channels.cache.find(channel => channel.id === snowflake);
const roleSearch = guild.roles.cache.find(role => role.id === snowflake);
const commandSearch = guild.commands.cache.find(command => command.id === snowflake);
const emojiSearch = guild.emojis.cache.find(emoji => emoji.id === snowflake);
const stickerSearch = guild.stickers.cache.find(sticker => sticker.id === snowflake);
10 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 5/8/2023 in #djs-questions
Channel Update Event
Is there any way, to find out which user moved a channel from one category to another?
9 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 4/22/2023 in #djs-questions
Autocomplete Question
I don't understand what autocomplete does and I can't seem to find any information on this that goes in-depth. What does autocomplete actually do?
5 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 4/13/2023 in #djs-questions
Audit Log Channel Update Event
With the code below, when I update a channel's parent, auditLog is undefined. Why?
module.exports = {
name: Events.ChannelUpdate,
on: true,
async execute(oldChannel, newChannel, client){
const guild = client.guilds.cache.get(newChannel.guildId)
if (!guild) return;
if (newChannel.type == ChannelType.DM || newChannel.type == ChannelType.GroupDM) return;
const auditLogs = await guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.ChannelUpdate
});
--> const auditLog = auditLogs.entries.first()
module.exports = {
name: Events.ChannelUpdate,
on: true,
async execute(oldChannel, newChannel, client){
const guild = client.guilds.cache.get(newChannel.guildId)
if (!guild) return;
if (newChannel.type == ChannelType.DM || newChannel.type == ChannelType.GroupDM) return;
const auditLogs = await guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.ChannelUpdate
});
--> const auditLog = auditLogs.entries.first()
2 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 4/12/2023 in #djs-questions
Client Question
Why does the following sometimes work when the client / code starts / runs and other times doesn't? client.application.commands.cache.size Normally returns 28 Other times returns 0
4 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 4/10/2023 in #djs-questions
Mention Spam Protection Activation / Deactivation Detection
Can you get the user who deleted / edited an auto mod rule?
19 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 4/8/2023 in #djs-questions
Auto Mod Create Event not working
here is the event code. the output is nothing
const { EmbedBuilder, Events } = require('discord.js');
require('dotenv').config();
const logsSchema = require('../../Models/Logs');

module.exports = {
name: Events.AutoModerationRuleCreate,
on: true,
async execute(rule, client){
console.log("abc");
const guild = client.guilds.cache.get(rule.guild.id)
if (!guild) return;
console.log(guild.id);
const logChannelFind = await logsSchema.findOne({
GuildID: rule.guild.id
});
if (!logChannelFind) return;
console.log(logChannelFind);
const logChannel = client.channels.cache.get(logChannelFind.ChannelID);
const embed = new EmbedBuilder()
.setColor("Green")
.setTitle("Auto Moderation Rule Created")
try {
logChannel.send({ embeds: [embed] })
} catch (error) {
console.log(error);
};
}
}
const { EmbedBuilder, Events } = require('discord.js');
require('dotenv').config();
const logsSchema = require('../../Models/Logs');

module.exports = {
name: Events.AutoModerationRuleCreate,
on: true,
async execute(rule, client){
console.log("abc");
const guild = client.guilds.cache.get(rule.guild.id)
if (!guild) return;
console.log(guild.id);
const logChannelFind = await logsSchema.findOne({
GuildID: rule.guild.id
});
if (!logChannelFind) return;
console.log(logChannelFind);
const logChannel = client.channels.cache.get(logChannelFind.ChannelID);
const embed = new EmbedBuilder()
.setColor("Green")
.setTitle("Auto Moderation Rule Created")
try {
logChannel.send({ embeds: [embed] })
} catch (error) {
console.log(error);
};
}
}
7 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 4/8/2023 in #djs-questions
How to I turn Permission numbers into a string / array?
const directories = [
...new Set(interaction.client.commands.map((cmd) => cmd.folder)),
];

const formatString = (str) =>
`${str[0].toUpperCase()}${str.slice(1).toLowerCase()}`;

const categories = directories.map((dir) => {
const getCommands = interaction.client.commands
.filter((cmd) => cmd.folder === dir)
.map((cmd) => {
return {
name: cmd.data.name,
description:
cmd.data.description ||
"There is no description for this command.",
--> defaultMemberPermissions: cmd.data.default_member_permissions// || "There are no defualt member permissions for this command"
};
const directories = [
...new Set(interaction.client.commands.map((cmd) => cmd.folder)),
];

const formatString = (str) =>
`${str[0].toUpperCase()}${str.slice(1).toLowerCase()}`;

const categories = directories.map((dir) => {
const getCommands = interaction.client.commands
.filter((cmd) => cmd.folder === dir)
.map((cmd) => {
return {
name: cmd.data.name,
description:
cmd.data.description ||
"There is no description for this command.",
--> defaultMemberPermissions: cmd.data.default_member_permissions// || "There are no defualt member permissions for this command"
};
defaultMemberPermissions returns with a number. How do i make this a string, such as administrator?
7 replies
DIAdiscord.js - Imagine a bot
Created by PAdventures on 4/7/2023 in #djs-questions
Application Command Permission Update Event
I am trying to get the type of permission in the data of the event. Example: data.permissions.type This is returning as undefined when I update a app command's user/roles/channel permissions If you are confused, look at the type / ApplicationCommandPermissionType in the link below https://old.discordjs.dev/#/docs/discord.js/main/typedef/ApplicationCommandPermissions
10 replies