Discord.JS code wont work? - discord.js

So im making a myth hunters bot for roblox, and I want to copy all users with a certain rank, but thatch not what I want to do, Im just wondering why this will not work. No errors and no reply
var args = message.content.substring(prefix.length).split(" ");
switch (args[0].toLowerCase()) {
case "info":
let mythUser = message.content.replace("mh>info ", "");
if (mythUser === "fodloca") {
var fodLoceEmb = new discord.RichEmbed()
.setTitle("User: Fodloca")
.addField("ID: 663751421", "Description: Hey, I'm Fodloca..")
.setThumbnail("https://www.roblox.com/outfit-thumbnail/image?userOutfitId=663751421&width=420&height=420&format=png")
message.channel.send(forLoceEmb);
}
break;
}

Use == not ===
var args = message.content.substring(prefix.length).split(" ");
switch (args[0].toLowerCase()) {
case "info":
let mythUser = message.content.replace("mh>info ", "");
if (mythUser == "fodloca") {
var fodLoceEmb = new discord.RichEmbed()
.setTitle("User: Fodloca")
.addField("ID: 663751421", "Description: Hey, I'm Fodloca..")
.setThumbnail("https://www.roblox.com/outfit-thumbnail/image?userOutfitId=663751421&width=420&height=420&format=png")
message.channel.send(forLoceEmb);
}
break;
}

Related

My discord.js has an error and I don't know how to fix it

My Problem is that my bot tells me when i hit the reaction of the embed message that name is undefied. I don´t know how to fix this or how i should define name. I also dont know if this code, the reactionMemberAdd part works for many roles. It would be very great if one can help me
const Discord = require("discord.js")
const fs = require("fs")
const generalrolesConfig = JSON.parse(fs.readFileSync('./configs/generalroles.json', 'utf-8'))
module.exports = client => {
//Allgemein
//Chat Nachricht um Embed aufzurufen: general :space_invader: 813828905081110568 :computer: 815181805350682655 :frame_photo: 815181807234449428
//id von member:813828905081110568 👾
//id von programmierer: 815181805350682655 💻
//id von grafiker/desginer: 815181807234449428 🖼
client.on('message', async (msg) => {
if(msg.author.bot || !msg.guild) return;
if(msg.content.startsWith('!general')) {
var args = msg.content.split(' ')
if(args.length == 7) {
var emoji1 = args[1]
var roleid1 = args[2]
var emoji2 = args[3]
var roleid2 = args[4]
var emoji3 = args[5]
var roleid3 = args[6]
var role = msg.guild.roles.cache.get((roleid1 || roleid2 || roleid3))
if(!role) {
msg.reply('Die Rolle gibt es nicht'); return
}
var generalembed = new Discord.MessageEmbed()
.setTitle("Allgemein")
.setColor("RED")
.setDescription('TEST')
var sendedMessage = await msg.channel.send(generalembed)
sendedMessage.react(emoji1).then(sendedMessage.react(emoji2)).then(sendedMessage.react(emoji3))
var toSave = {message: sendedMessage.id, emoji1: emoji1, roleid1: roleid1, emoji2: emoji2, roleid2: roleid2, emoji3: emoji3, roleid3: roleid3}
generalrolesConfig.reactions.push(toSave)
fs.writeFileSync('./configs/generalroles.json', JSON.stringify(generalrolesConfig))
} else {
msg.reply('etwas ist falsch gelaufen')
}
}
})
client.on('messageReactionAdd', (reaction, user) => {
if(reaction.message.partial) reaction.fetch()
if(reaction.partial) reaction.fetch()
if(user.bot || !reaction.message.guild) return
for (let index = 0; index < generalrolesConfig.reactions.length; index++) {
let reactionRole = generalrolesConfig.reactions[index]
if(reaction.message.id == reactionRole.message && reaction.emoji1.name == reactionRole.emoji1 && !reaction.message.guild.members.cache.get(user.id).roles.cache.has(reactionRole.roleid)) {
reaction.message.guild.members.cache.get(user.id).roles.add(reactionRole.role)
}
}
})
}

TypeError: connection.playStream is not a function discord bot

switch(args[0]){
case 'ping':
message.reply('pong!');
break;
case 'play':
if (message.member.voice.channel) {
if(args[1]){
const connection = message.member.voice.channel.join();
const dispatcher = connection.playStream(ytdl(args[1]));
}else{
message.reply('Tio, el link joder');
}
} else {
message.reply('Pero tio, únete al canal de voz');
}
break;
case 'info':
message.reply('No soy el FBI,hippie');
break;
case 'clear':
if(!args[1]) return message.reply('Hippie,que te falta un argumento')
message.channel.bulkDelete(args[1]);
break;
}
});
I tried to seek in other questions the solutions but none of this are what i need or doesnt work,here is the error TypeError: connection.playStream is not a function
In the new v12 update, playStream has been defunct.
the new proper code is
server.dispatcher = connection.play(ytdl(server.queue[0], {filter: "audioonly"}));
instead of playStream it is just play.
ive been troubleshooting the same code your running, here is the full play,stop and skip commands. I cant figure out the queue though but this should fix your errors with it not running.
case 'play':
if(usedCommandRecently4.has(message.author.id)){
message.reply("Your using this command to fast!");
} else{
function play(connection, message){
var server = servers[message.guild.id];
server.dispatcher = connection.play(ytdl(server.queue[0], {filter: "audioonly"}));
server.queue.shift();
message.channel.send("``Music Bot v1.2`` \n Adding song to queue!");
server.dispatcher.on("end", function(){
if(server.queue[0]){
play(connection, message);
}else {
connection.disconnect();
}
})
}
if(!args[1]){
message.channel.send("``Music Bot v1.2`` \n you need to provide a link!!");
return;
}
if(!message.member.voice.channel){
message.channel.send("``Music Bot v1.2`` \n You must be in a voice channel to play music!");
return;
}
if(!servers[message.guild.id]) servers[message.guild.id] = {
queue: []
}
var server = servers[message.guild.id];
server.queue.push(args[1]);
if(!message.guild.voiceConnection)message.member.voice.channel.join().then(function(connection){
server.dispatcher = connection.play(ytdl(server.queue[0], {filter: "audioonly"}));
play(connection, message);
})
usedCommandRecently4.add(message.author.id);
setTimeout(() => {
usedCommandRecently4.delete(message.author.id)
}, 10000);
}
break;
case 'skip':
if(usedCommandRecently3.has(message.author.id)){
message.reply("Your using this command to fast!");
} else{
var server = servers[message.guild.id];
if(server.dispatcher) server.dispatcher.end();
message.channel.send("``Music Bot v1.2`` \n Skipping the current song!")
usedCommandRecently3.add(message.author.id);
setTimeout(() => {
usedCommandRecently3.delete(message.author.id)
}, 3000);
}
break;
case 'stop':
var server = servers[message.guild.id];
if(message.guild.voice.connection){
for(var i = server.queue.length -1; i >=0; i--){
server.queue.splice(i, 1);
}
server.dispatcher.end();
message.channel.send("``Music Bot v1.2`` \n Ending the queue and Leaving the voice channel! \n This bot is in early development! \n if you have any problems with it dm Justice#6770!")
console.log('stopped the queue')
}
}
if(message.guild.connection) message.guild.voiceConnection.disconnect();

Arguments for Discord.js

how do I read args in discord.js? I am trying to create a support bot and I want to have an !help {topic} command. how do I do that?
my current code is very basic
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = ("!")
const token = ("removed")
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
}
if (msg.content === 'help') {
msg.reply('type -new to create a support ticket');
}
});
client.login(token);
You can make use of a prefix and arguments like so...
const prefix = '!'; // just an example, change to whatever you want
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.trim().split(/ +/g);
const cmd = args[0].slice(prefix.length).toLowerCase(); // case INsensitive, without prefix
if (cmd === 'ping') message.reply('pong');
if (cmd === 'help') {
if (!args[1]) return message.reply('Please specify a topic.');
if (args[2]) return message.reply('Too many arguments.');
// command code
}
});
you can use Switch statement instead of
if (command == 'help') {} else if (command == 'ping') {}
client.on ('message', async message => {
var prefix = "!";
var command = message.content.slice (prefix.length).split (" ")[0],
topic = message.content.split (" ")[1];
switch (command) {
case "help":
if (!topic) return message.channel.send ('no topic bro');
break;
case "ping":
message.channel.send ('pong!');
break;
}
});
let args = msg.content.split(' ');
let command = args.shift().toLowerCase();
this is the simplified answer from #slothiful.
usage
if(command == 'example'){
if(args[0] == '1'){
console.log('1');
} else {
console.log('2');
You can create a simple command/arguments thing (I don't know how to word it correctly)
client.on("message", message => {
let msgArray = message.content.split(" "); // Splits the message content with space as a delimiter
let prefix = "your prefix here";
let command = msgArray[0].replace(prefix, ""); // Gets the first element of msgArray and removes the prefix
let args = msgArray.slice(1); // Remove the first element of msgArray/command and this basically returns the arguments
// Now here is where you can create your commands
if(command === "help") {
if(!args[0]) return message.channel.send("Please specify a topic.");
if(args[1]) return message.channel.send("Too many arguments.");
// do your other help command stuff...
}
});
You can do
const args =
message.content.slice(prefix.length).trim().split(' ');
const cmd = args.shift().toLocaleLowerCase();
Word of advice, use a command handler and slash commands - this will solve both the need for a help command and reading arguments. Also helps with readability.
Anyways...
message.content.split(' '): This will split your string into an array of sub-strings, then return a new array.
.shift(): This will remove the first index in the array.
Combining this will get you your arguments: const args = message.content.split(' ').shift()

Save UIImage as jpg File in Photo Library Directory in Xamarin.iOS

As I know this is Simple Approch to save it in a Photo Library. But It can save with custom filename.
var someImage = UIImage.FromFile("someImage.jpg");
someImage.SaveToPhotosAlbum((image, error) => {
var o = image as UIImage;
Console.WriteLine("error:" + error);
})
But I want to save it with filename.jpg in the Photo Library.
I try so much code but nothing is getting help to me.
Code 1 :
var imageName = "/" + dicomId.ToString() + ".jpg";
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, imageName); // hardcoded filename, overwritten each time
NSData imgData = dicomImage.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
This code part goes to if condition but it can not save the Image.
Code 2 :
If using this part of Code
var documentsDirectoryPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true)[0];
It give you don't have permission to save image.
I try lots of thing on google and SO but nothing could help to me.
Edit :
info.plist
Any Help would be Appreciated.
How about using UIImage.SaveToPhotosAlbum()?
Usage is something like:
image.SaveToPhotosAlbum((uiImage, nsError) =>
{
if (nsError != null)
// do something about the error..
else
// image should be saved
});
Make sure that you have requested permissions before you try to save.
PHPhotoLibrary.RequestAuthorization(status =>
{
switch (status)
{
case PHAuthorizationStatus.Restricted:
case PHAuthorizationStatus.Denied:
// nope you don't have permission
break;
case PHAuthorizationStatus.Authorized:
// yep it is ok to save
break;
}
});
Edit: if you want more control, you need to use PHPhotosLibrary, which is an awful API...
var library = PHPhotoLibrary.SharedPhotoLibrary;
var albumName = "MyPhotos";
var fetchOptions = new PHFetchOptions();
fetchOptions.Predicate = NSPredicate.FromFormat($"title = {albumName}");
var assetsCollections = PHAssetCollection.FetchAssetCollections(
PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
var collection = assetsCollections.firstObject as PHAssetCollection;
library.PerformChanges(() => {
var options = new PHAssetResourceCreationOptions();
options.OriginalFilename = "filename.jpg";
var createRequest = PHAssetCreationRequest.CreationRequestForAsset();
createRequest.AddResource(PHAssetResourceType.FullSizePhoto, image.AsJPEG(1), options);
// if you want to save to specific album... otherwise just remove these three lines
var placeholder = createRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { placeholder });
},
(ok, error) => {
if (error != null)
{
// someone set up us the bomb
}
});

How to instantiate an array in TypeScript which should contain strings?

I am new to TypeScript and working on a server monitoring webApp. I have a method which should save the status of pings and endpoints into an array. Then it should determine the status of the servers depending on the entries in that array. The method should be working correctly I assume, but I think I am not initialising the array in a proper way.
setServersStatus() {
let allStatus: String[] = new Array(); // Here I get a Warning "Instantiation can be simplified"
for (let server of this.servers) {
if (server.restendpoints != null) {
for (let rest of server.restendpoints) {
switch (rest.status) {
case "OK":
allStatus.push("OK");
break;
case "WARNING":
allStatus.push("WARNING");
break;
case "ERROR":
allStatus.push("ERROR");
break;
default:
console.log('status empty');
}
}
}
if (server.ping != null) {
switch (server.ping.status) {
case "OK":
allStatus.push("OK");
break;
case "WARNING":
allStatus.push("WARNING");
break;
case "ERROR":
allStatus.push("ERROR");
break;
default:
console.log('status empty');
}
}
if (allStatus.indexOf('ERROR')) {
server.status = 'ERROR';
}
else if (allStatus.indexOf('WARNING')) {
server.status = 'WARNING';
}
else if (allStatus.indexOf('OK')) {
server.status = 'OK';
}
allStatus.length = 0;
}
}
I also tried to initialize in the following way, but it didn't work:
let allStatus = []; // Here it says "Variable allStatus implicitly has an any[] type"
So how do I initialize an array properly in TypeScript?
You can declare a typed array like this
let allStatus: string[] = [];
or like this
let allStatus: Array<string> = [];

Resources