Discord.Js The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined - discord.js

I was coding a new command on discord which its focusing on OsuApi and now what I did is making a data function that writes the info on the Api.
I tried this code and it seems that I cannot fix it because I'm kinda new to this function and its bugging me
and here's my code
const { member, channel, content, guild } = message
const cache = {}
let data = cache[member.id]
if (!data) {
const e1 = new ME()
.setTitle(`Fetching Data Please Wait`)
.setColor("Random")
.setTimestamp()
.setFooter({ text: client.user.username, iconURL: client.user.displayAvatarURL() })
console.log("Fecting From DataBase")
const msg = await channel.send({ embeds: [e1] })
await shi().then(async mongodb => {
try {
const result = await us.findOne({ _id: member.id })
if (!result) {
const e2 = new ME()
.setTitle("Aweeee~")
.setColor(config.colors.no)
.setDescription("No user found set user using 's!setuser <username or userid>' ")
.setTimestamp()
.setFooter({ text: client.user.username, iconURL: client.user.displayAvatarURL() })
await setTimeout(() => {
msg.edit({ embeds: [e2] })
}, 5000);
return
}
cache[member.id] = data = [result.text]
} catch (err) {
console.log(err)
message.channel.send("Something bad happened sorry")
}
})
api.user
.get(data)
.then(data => {
const dataJSON = JSON.stringify(data)
fs.writeFileSync('user.json', dataJSON)
const dataBuffer = fs.readFileSync('user.json')
const stringJSON = dataBuffer.toString()
const parseDATA = JSON.parse(stringJSON)
console.log(parseDATA.username)
channel.send("testing")
})
}

Related

TypeError: command.execute is not a function

I am aware that this problem has been discussed already, but I don't seem to fit the solutions found into my code. I've created some commands to this bot and they seem to work, although they are only basic slash commands (e.g. /ping). This problem came in when I try to run a moderation command or a play command.
This is the code with the error
const { Interaction } = require("discord.js");
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return
try{
await command.execute(interaction, client);
} catch (error) {
console.log(error);
await interaction.reply({
content: 'A aparut o eroare cu aceasta comanda!',
ephemeral: true
});
}
},
};
None of the fixes that I found seem to fit, at least to my rather unexperienced eye.
The command I try to run is this:
const { SlashCommandBuilder } = require("#discordjs/builders")
const { MessageEmbed } = require("discord.js")
const { QueryType } = require("discord-player")
module.exports = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("Asculta muzica")
.addSubcommand((subcommand)=>
subcommand
.setName("song")
.setDescription("Incarca o singura melodie printr-un url")
.addStringOption((option) => option.setName("url").setDescription("url-ul melodiei").setRequired(true)))
.addSubcommand((subcommand) =>
subcommand
.setName("playlist")
.setDescription("Incarca un playlist printr-un url")
.addStringOption((option) => option.setName("url").setDescription("url-ul playlist-ului").setRequired(true)))
.addSubcommand((subcommand) =>
subcommand
.setName("search")
.setDescription("Cauta o melodie pe baza cuvintelor-cheie")
.addStringOption((option) =>
option.setName("searchterms").setDescription("the search keywords").setRequired(true))),
run: async ({ client, interaction }) => {
if (interaction.member.voice.channel)
return interaction.editReply("Trebuie sa fii pe un voice channel pentru a folosi aceasta comanda!")
const queue = await client.player.createQueue(interaction.guild)
if (!queue.connection) await queue.connect(interaction.member.voice.channel)
let embed = new MessageEmbed()
if (interaction.options.getSubcommand() === "song"){
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_VIDEO
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${song.duration}`})
} else if (interaction.options.getSubcommand() === "playlist"){
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_PLAYLIST
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const playlist = result.tracks
await queue.addTrack(result.tracks)
embed
.setDescription(`**${result.tracks.length} melodii din [${playlist.title}](${playlist.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${playlist.duration}`})
} else if (interaction.options.getSubcommand() === "search"){
let url = interaction.options.getString("seatchterms")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${song.duration}`})
}
if (!queue.playing) await queue.play()
await interaction.editReply({
embeds: [embed]
})
}
}
and the corresponding error:
TypeError: command.execute is not a function
at Object.execute (C:\Users\shelby\Bot\src\events\interactionCreate.js:15:27)
at Client.<anonymous> (C:\Users\shelby\Bot\src\functions\handelEvents.js:8:58)
at Client.emit (node:events:513:28)
at InteractionCreateAction.handle (C:\Users\shelby\Bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
at module.exports [as INTERACTION_CREATE] (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketShard.onPacket (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:489:22)
at WebSocketShard.onMessage (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:328:10)
at callListener (C:\Users\shelby\Bot\node_modules\ws\lib\event-target.js:290:14)
at WebSocket.onMessage (C:\Users\shelby\Bot\node_modules\ws\lib\event-target.js:209:9)
You should be using command.run() instead of command.execute(), as your exported Slash Command uses this property name to store the core function.
const { Interaction } = require("discord.js");
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return
try{
await command.run({ interaction, client });
} catch (error) {
console.log(error);
await interaction.reply({
content: 'A aparut o eroare cu aceasta comanda!',
ephemeral: true
});
}
},
};
Additionally, you have to use an object that contains your interaction and client to run the function instead of using two arguments.

Discord.js Ticket system doesn't send an ephemeral message

I'm trying to make a ticket system with discord.js v13, but the ephemeral method doesn't work and, when my bot turn on, i need to click one time in the button to activate the system.
print
My code:
const { MessageActionRow, MessageButton, MessageEmbed, Permissions } = require('discord.js');
const db = require("quick.db");
exports.run = async (client, interaction) => {
if (!interaction.isButton()) return;
interaction.deferUpdate();
let getContador = await db.get('counter')
if(getContador === null) {
let contador = await db.set("counter", 1)
}
await db.add("counter", 1)
let tcID = "895323735702253569"
let tmID = "895358127950659604"
const filter = i => i.customId === 'OPENTICKET'
const collector = interaction.channel.createMessageComponentCollector({ filter, max: 1 });
collector.on("collect", async i => {
let cTicket = await i.guild.channels.create(`🎫┆Ticket ${getContador}`, {
type: 'GUILD_TEXT',
permissionOverwrites: [
{
id: i.guild.id,
deny: [Permissions.FLAGS.VIEW_CHANNEL],
},
{
id: i.user.id,
allow: [Permissions.FLAGS.VIEW_CHANNEL, Permissions.FLAGS.SEND_MESSAGES],
},
]
})
await interaction.channel.messages.cache.get(tmID).reply({ content: `... ${cTicket.toString()}...`, ephemeral: true })
})
}
You are replying to a normal message. If you would like an ephemeral message, you have to directly reply to the interaction.
interaction.reply({
content: `... ${cTicket.toString()}...`,
ephemeral: true
})

Discord.js v13, #discordjs/voice Play Music Command

This is my code,
The command executes perfectly, The bot joins the voice channel and also sends the name of the song its about to play, but it doesnt play the song in the voice channel.
This is my first time ever asking a question on stackoverflow so dont mind the format and stuff. But I really need help here.
Discord v13 and latest node module.
const ytsearch = require('yt-search');
const Discord = require('discord.js')
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
NoSubscriberBehavior
} = require('#discordjs/voice');
module.exports = {
name: "play",
description: "test command",
async run(client, message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('Please connect to a voice channel!');
if (!args.length) return message.channel.send('Please Provide Something To Play!')
const connection = await joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const videoFinder = async (query) => {
const videoResult = await ytsearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if (video) {
const stream = ytdl(video.url, { filter: 'audioonly' });
const player = createAudioPlayer();
const resource = createAudioResource(stream)
await player.play(resource);
connection.subscribe(player);
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
}
}```
I would suggest you look at the music bot example at #discordjs/voice.
They do a good job of how to extract the stream from ytdl.
I'm currently still learning how this all works but the part that you will want to look at is in the createAudioResource function.
public createAudioResource(): Promise<AudioResource<Track>> {
return new Promise((resolve, reject) => {
const process = ytdl(
this.url,
{
o: '-',
q: '',
f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio',
r: '100K',
},
{ stdio: ['ignore', 'pipe', 'ignore'] },
);
if (!process.stdout) {
reject(new Error('No stdout'));
return;
}
const stream = process.stdout;
const onError = (error: Error) => {
if (!process.killed) process.kill();
stream.resume();
reject(error);
};
process
.once('spawn', () => {
demuxProbe(stream)
.then((probe) => resolve(createAudioResource(probe.stream, { metadata: this, inputType: probe.type })))
.catch(onError);
})
.catch(onError);
});
}

Sending verification email with Firebase and React Native

I am trying to send the validation email upon the account registration, using firebase. The registration is being done successfully but whenever I try to code email verification it gives me an error. Probably because I don't know where to place it. All my firebase methods are on Fire.js, which are the following:
import firebaseKeys from './Config';
import firebase from 'firebase';
require("firebase/firestore");
class Fire {
constructor() {
if (!firebase.apps.length) {
firebase.initializeApp(firebaseKeys);
}
}
addPost = async ({ text, localUri }) => {
const remoteUri = await this.uploadPhotoAsync(localUri, 'photos/${this.uid}/${Date.now()}');
return new Promise((res, rej) => {
this.firestore.collection('posts').add({
text,
uid: this.uid,
timestamp: this.timestamp,
image: remoteUri
})
.then(ref => {
res(ref);
})
.catch(error => {
rej(error);
});
});
}
uploadPhotoAsync = async (uri, filename) => {
return new Promise(async (res, rej) => {
const response = await fetch(uri);
const file = await response.blob();
let upload = firebase
.storage()
.ref(filename)
.put(file);
upload.on(
"state_changed",
snapshot => {},
err => {
rej(err);
},
async () => {
const url = await upload.snapshot.ref.getDownloadURL();
res(url);
}
);
});
}
createUser = async user => {
let remoteUri = null
try {
await firebase.auth().createUserWithEmailAndPassword(user.email, user.password)
//I tried to code it here with user.sendEmailVerification();
let db = this.firestore.collection("users").doc(this.uid)
db.set({
name: user.name,
email: user.email,
avatar: null
})
if (user.avatar) {
remoteUri = await this.uploadPhotoAsync(user.avatar, 'avatars/${this.uid}')
db.set({avatar: remoteUri}, {merge: true});
}
} catch (error) {
alert("Error: ", error);
}
};
get firestore() {
return firebase.firestore();
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get timestamp() {
return Date.now();
}
}
Fire.shared = new Fire();
export default Fire;
The createUserWithEmailAndPassword() method returns a Promise which resolves with a UserCredential AND (as the the doc indicates) "on successful creation of the user account, this user will also be signed in to your application."
So you can easily get the signed in user by using the user property of the UserCredential, and call the sendEmailVerification() method, as follows:
try {
const userCredential = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
await userCredential.user.sendEmailVerification();
//In the next line, you should most probably use userCredential.user.uid as the ID of the Firestore document (instead of this.uid)
cont db = this.firestore.collection("users").doc(this.uid);
//...
} catch (...)
Note that you may pass an ActionCodeSettings object to the sendEmailVerification() method, see the doc.

How to make Async Await Function in React Native?

I want to create a function that is about uploading photo to Firebase Storage with react-native-fetch-blob. I'm using Redux and you can find action functions below:
My problem is that uploadImage function is not running like asynchronous. Firebase function is running before uploadImage, so application give me an error.
I think i can't make a asynchronous function. How can i fix it ?
uploadImage() function:
const uploadImage = async (imageSource, whereToUpload) => {
let imageURL = '';
const mime = 'image/jpg';
const { Blob } = RNFetchBlob.polyfill;
const { fs } = RNFetchBlob;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
console.log('URI =>', imageSource.uri);
let imgUri = imageSource.uri;
let uploadBlob = null;
const imageRef = firebase.storage().ref(whereToUpload + '/' + imageSource.fileName);
const uploadUri = Platform.OS === 'ios' ? imgUri.replace('file://', '') : imgUri;
await fs.readFile(uploadUri, 'base64')
.then((data) => Blob.build(data, { type: `${mime};BASE64` }))
.then((blob) => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime });
})
.then(() => {
uploadBlob.close();
// eslint-disable-next-line no-return-assign
return imageURL = imageRef.getDownloadURL();
})
.catch((error) => {
console.log(error);
});
return imageURL;
};
and the main action is:
export const addProjectGroup = (
myUser,
groupName,
groupDescription,
groupProfilePic,
) => dispatch => {
const groupProfileFinalPic = async () => {
let finalGroupPicture = { landscape: '' };
if (_.isEmpty(groupProfilePic.src)) {
await uploadImage(groupProfilePic, 'groupPictures').then((imageURL) => {
console.log('İŞLEM TAMAM!');
console.log('SELECTED IMAGE URL =>', imageURL);
finalGroupPicture.landscape = imageURL;
});
} else {
finalGroupPicture.landscape = groupProfilePic.src.landscape;
}
return finalGroupPicture;
};
console.log("final group profile pic =>", groupProfileFinalPic());
// Önce grubu yaratalım..
// eslint-disable-next-line prefer-destructuring
const key = firebase
.database()
.ref()
.child('groups')
.push().key;
firebase
.database()
.ref('/groups/' + key)
.set({
admin: {
email: myUser.email,
name: myUser.name,
uid: myUser.uid,
},
groupName,
groupDescription,
groupProfilePic: groupProfileFinalPic(),
projects: '',
})
.then(() => {
console.log('Groups oluşturuldu.');
})
.catch(e => {
Alert.alert('Hata', 'Beklenmedik bir hata meydana geldi.');
console.log(e.message);
});
dispatch({
type: ADD_PROJECT_GROUP,
});
};
You are not awaiting groupProfileFinalPic(). This should be done before creating the action you want to dispatch.
groupProfileFinalPic().then(groupProfilePic => {
return firebase
.database()
.ref("/groups/" + key)
.set({
admin: {
email: myUser.email,
name: myUser.name,
uid: myUser.uid
},
groupName,
groupDescription,
groupProfilePic,
projects: ""
})
.then(() => {
console.log("Groups oluşturuldu.");
})
.catch(e => {
Alert.alert("Hata", "Beklenmedik bir hata meydana geldi.");
console.log(e.message);
});
});
I have no clue what the last dispatch is for, you might want to do that in one of the callbacks. Your code is to verbose for an SO question, but I hope this helps anyways.
You are using both await and then on the same call. To use await, you can arrange it something like
const uploadImage = async (imageSource, whereToUpload) => {
...
try {
let data = await RNFS.fs.readFile(uploadUri, 'base64')
let uploadBlob = await Blob.build(data, { type: `${mime};BASE64` }))
...etc...
return finalResult
catch (e) {
// handle error
}
}

Resources