How to get rid of "undefined" in Discord embeds - discord.js

I'm trying to make it so that the output of this Discord embed won't be "undefined" for the Bot, Mute, and Deafen part of the embed.
I tried to change some var to "let" or "const"
I've tampered with the aboutuser portion to change it to something different.
I've messed with the if portion of the code.
Here's the code.
async run(message, args){
if (message.channel instanceof discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
var serv = message.guild
if (serv.explicitContentFilter == 0) {
var eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
var eFC = "Scan for users without a role.";
}
if (serv.explicitContentFilter == 2) {
var eFC = "Scan every message";
}
///////////////////////////////////////////////////////////////////////////////////////////////////
if (serv.verificationLevel == 4) {
var verL = "Intense (Verified Account & Verified Phone linked)";
}
if (serv.verificationLevel == 3) {
var verL = "Secure (Verified Account & Guild member for 10+ minutes)";
}
if (serv.verificationLevel == 2) {
var verL = "Medium (Verified Account for 5 minutes+)";
}
if (serv.verificationLevel == 1) {
var verL = "Low (Verified Account)";
}
if (serv.verificationLevel == 0) {
var verL = "None (No Restriction)";
}
//////////////
if (serv.region == `brazil`) {
var regio = "Brazil";
}
if (serv.region == `eu-central`) {
var regio = "Central Europe";
}
if (serv.region == `hongkong`) {
var regio = "Hong Kong";
}
if (serv.region == `japan`) {
var regio = "Japan";
}
if (serv.region == `russia`) {
var regio = "Russia";
}
if (serv.region == `singapore`) {
var regio = "Singapore";
}
if (serv.region == `southafrica`) {
var regio = "South Africa";
}
if (serv.region == `sydney`) {
var regio = "Sydney";
}
if (serv.region == `us-central`) {
var regio = "Central US";
}
if (serv.region == `us-east`) {
var regio = "East US";
}
if (serv.region == `us-south`) {
var regio = "South US";
}
if (serv.region == `us-west`) {
var regio = "West US";
}
if (serv.region == `eu-west`) {
var regio = "West Europe";
}
//
if (serv.defaultMessageNotifications == `ALL`) {
var defn = "Send all Messages";
}
if (serv.defaultMessageNotifications == `MENTIONS`) {
var defn = "Only #everyone";
}
var myInfo = new discord.RichEmbed()
.setAuthor(`${serv.name}'s guild info`,`${message.guild.iconURL}`)
.addField(`AFK Channel`,`${serv.afkChannel}`,true)
.addField(`AFK Timeout`,`${serv.afkTimeout}s`,true)
.addField(`Channels`,`${serv.channels.size}`,true)
.addField(`Creation of Guild`,`${serv.createdAt}`,true)
.addField(`Default Notification`, defn,true)
.addField(`Explicit Content Filter Level`, eFC,true)
.addField(`Guild ID`,`${serv.id}`,true)
.addField(`How much members`,`${serv.memberCount}`,true)
.addField(`Owner`,`${serv.owner}`,true)
.addField(`Region`, regio,true)
.addField('Roles', `Please do s!roles to find server roles!`, true)
/* serv.roles.map(r => `${r}`).join(' | ') */
.addField(`Verification Level`, verL,true)
.setColor(0x511fdd)
.setFooter('Aboutserver command')
.setThumbnail(`${message.guild.iconURL}`)
message.channel.sendEmbed(myInfo);
}
}
expected result : The bot will say Yes or No instead of undefined, or true or false.
actual result : The bot's output is just undefined.

There are a couple of things happening here, but let's focus on the main issue; how you have declared your variables.
To put it simply, variables can only be accessed within the scope in which they are declared in (The scope is all the code between the {}).
I'll explain it with a short example based on your code. In your if statements you declare your variables, meaning they can be used within that if statements' scope. You later want to use those same variables outside of the if statement and in your embed. Because those variables don't exist in that scope, they are undefined.
...
// At this point there is no variable 'eFC' available.
if (serv.explicitContentFilter == 0) {
// Here you create the variable 'eFC' but it can only be used inside this scope, meaning it cannot be accessed outside the 'if' statement.
var eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
// Here you create another variable with the same name, but it would end up being a different variable.
var eFC = "Scan for users without a role.";
}
// Here there is still no variable 'eFC' available to us.
...
The simple solution is: declare your variables in another scope and assign the values later. Below you can see an example:
...
// Here we create a new variable called 'eFC' which can be used within this scope
var eFC;
if (serv.explicitContentFilter == 0) {
// Here we assign a value to the previously defined variable
eFC = "Don't Scan Any messages";
}
if (serv.explicitContentFilter == 1) {
// Here we assign a value to the previously defined variable
eFC = "Scan for users without a role.";
}
// Here we can use the variable 'eFC' which will have a value
console.log(eFC);
...
If you do this for all the variables which you use, the code should work fine.
Lastly I want to leave you with some extra help. I see you have created many, many, many if statements to check for e.g. the server region or the server verification level. Javascript (among many other programming languages) has a think called a switch case which basically does the same thing you have with all those if statements, but in a more neater way. Check out the link, I think it will help you make your code look a bit more readable

Related

Problem when an array element i'm trying to filter for does not exist

I have some code that gets a key from firebase, and compares it with a key stored locally in a text file. If there is a match, it checks an additional read/unread parameter, and then marks a variable as "Read" or "Unread".
The code works fine as long as every key I pull from Firebase exists in the text file. However, I get an "Index out of bounds" crash if a key from Firebase does not exist in my local file.
The code in question is as per below:
func readFile(){
let filename = getDocumentsDirectory().appendingPathComponent("output.txt")
do {
let textStringFromFile = try String(contentsOf: filename, encoding: .utf8)
var result: [(messageID: String, readStatus: String)] = []
let rows = textStringFromFile.components(separatedBy: "\n")
for row in rows {
let columns = row.components(separatedBy: ",")
result.append((columns[0], columns[1]))
}
let filteredMessageID = result.filter { $0.messageID == (nominationKeyForReadStatus) }
var messageIDElement = filteredMessageID.map { $0.messageID }
var readStatusElement = filteredMessageID.map { $0.readStatus }
if readStatusElement[0] == "1" && nominationKeyForReadStatus == messageIDElement[0] {
readStatusFromFunction = "Read"
}
else {
readStatusFromFunction = "Unread"
}
}
catch{
}
}
The crash seems to happen when filteredMessageID has 0 values. How do I account for this case? Thanks in advance.
You can make a pre check before accessing the index for messageIDElement, readStatusElement and filteredMessageID that it not having count 0.
if filteredMessageID.count != 0 {
if readStatusElement.count != 0 && messageIDElement != 0 {
// Your code
}
}

Unable to access to AngularJS's variables after having set them

I am working in a project and I am having some problems to work with some variables in the controller. This is the controller's code
angular.module('wc-general-informe-notas')
.controller('AnalisisEvaluacionController', ['$scope','$state','urlBasePartials', 'idColegio', 'anio', 'EvaluacionFactory',
function ($scope, $state, urlBasePartials, idColegio, anio, EvaluacionFactory) {
//Default ranges that clasifies
$scope.scoreRange = [
{level: "Very low", from: 1, to: 3.9},
{level: "Low", from: 4, to: 4.9},
{level: "High", from: 5, to: 5.9},
{level: "Excellent", from: 6, to: 7},
];
$scope.setRange = function () {
$scope.ranges = $scope.scoreRange;
}
$scope.informe =13;
$scope.levels = [];
$scope.idColegio = idColegio;
$scope.anio = anio;
$scope.nombreCurso = $('#curso option:selected').text();
$scope.casillero = $('#casillero option:selected').text();
$scope.evaluation = null;
$scope.setRange();
$scope.generateReport = function () {
EvaluacionFactory.patch({
idEvaluacion: $scope.filtroCasillero,
idSector: $scope.filtroAsignatura,
idCurso: $scope.filtroCurso,
idEvaluacionCursoSector: $scope.evaluacionCs[$scope.filtroPeriodo],
'expand[]': ['r_evaluacion_nota','nota_detalle','r_nota_alumno','alumno_detalle']
}, function (evaluation) {
$scope.evaluation = evaluation;
$scope.adjustLevels();
})
}
$scope.getRange = function (value) {
for (var i in $scope.ranges)
{
var range = $scope.ranges[i];
if (value == range.from || value == range.to || (value > range.from && value < range.to))
return range.level;
}
}
function init() {
$scope.profesor = null;
$scope.$parent.cursos_lista.forEach(function (curso) {
if(curso.id == $scope.filtroCurso)
{
if(curso.profesor != undefined)
{
var profesor = curso.profesor.usuario_detalle[0];
$scope.profesor = profesor.nombres + " " + profesor.apellido_paterno + " " + profesor.apellido_materno;
$scope.profesor = $scope.profesor.toString().toLowerCase();
}
}
})
if ($scope.ranges == undefined)
$scope.setRange();
if ($scope.filtroCasillero != null)
$scope.generateReport();
}
init();
$scope.adjustLevels = function () {
for(var i in $scope.evaluation.scores)
$scope.levels[$scope.evaluation.scores[i].id] = $scope.getRange($scope.evaluation.scores[i].valor);
}
}]);
What this controller does is get data from a factory which brings all the scores that an evaluation has. I render all the data correctly in the view, the problem is that in the view the user can modify $scope.ranges and then click a button (ng-click) that calls $scope.adjustLevels which should show the new level according to the new $scope.ranges' values.
Every time $scope.adjustLevels is called throws an error which said that
$scope.evaluation is null, even though there is no problem when is called after receiving the data from the factory.
It seems that I can't access all those variables I have set previously.
What can be happening? I hadn't had this sort of problems before.
I have tried adding console.log($scope.levels) and console.log($scope.evaluation) and it shows their content only when the method init() is called but not when I called it from the button I have in the view. When I do that is shows an empty array and null which are the values defined by default at the beginning
You expect that the $scope.generateReport() will set the $scope.evaluation but then you have this condition
if ($scope.filtroCasillero != null)
$scope.generateReport();
The $scope.filtroCasillero is not declared which makes the $scope.generateReport() never to be run and thats why the $scope.evaluation is null

iNotify how to detect move-out

Hi there I am using iNotify to detect changes in a directory. The flags I am using are IN_CLOSE_WRITE | IN_MOVED_FROM | IN_MOVED_TO | IN_CREATE
I am trying to differentiate between a IN_MOVED_FROM when renaming, and the IN_MOVED_FROM when a file is moved out of the folder.
I thought to check if the cookie field is not 0 when user moved the file out. As I thought cookie was only for rename procedure. However even when I move the file out of the directory it still has a cookie.
I also though to check for IN_MODIFY as I was hoping that would be there on rename but not on move, but its not there for either.
Does anyone have any ideas on how to detect if it was just "moved-out" or it is the "renamed-from-oldfilename"?
Thanks
You need to check for the IN_MOVED_FROM event and a following IN_MOVED_TO event. If the cookie is the same, the file has been renamed in the same folder. If you don't receive a IN_MOVED_TO event with the same cookie, the file has been moved outside of the watched folder.
I applied the logic mention by #hek2mgl and its working so big thanks to him. This is js-ctypes code:
while (true) {
let length = ostypes.API('read')(fd, buf, count);
length = parseInt(cutils.jscGetDeepest(length));
if (length == -1) {
throw new Error({
name: 'os-api-error',
message: 'Failed to read during poll',
uniEerrno: ctypes.errno
});
} else if (!length==0) {
// then its > 0 as its not -1
// something happend, read struct
let FSChanges = [];
var i = 0;
var numElementsRead = 0;
length = parseInt(cutils.jscGetDeepest(length));
var _cache_aRenamed_local = {}; // local means per buffer
do {
let iHoisted = i;
numElementsRead++;
var casted = ctypes.cast(buf.addressOfElement(iHoisted), ostypes.TYPE.inotify_event.ptr).contents;
var fileName = casted.addressOfField('name').contents.readString();
var mask = casted.addressOfField('mask').contents;
var len = casted.addressOfField('len').contents;
var cookie = cutils.jscGetDeepest(casted.addressOfField('cookie').contents)
var wd = casted.addressOfField('wd').contents;
var aEvent = convertFlagsToAEventStr(mask);
if (aEvent == 'renamed-to') {
if (cookie in _cache_aRenamed_local) { // assuming that renamed-from must happen before rename-to otherwise its a added
if (_cache_aRenamed_local[cookie].aExtra.aOSPath_parentDir_identifier == wd) { // aOSPath_parentDir_identifier is a wd if its different then the current wd then it was added/removed from that watched dir
var rezObj = {
aFileName: fileName,
aEvent: 'renamed',
aExtra: {
nixInotifyFlags: mask, // i should pass this, as if user did modify the flags, they might want to figure out what exactly changed
aOSPath_parentDir_identifier: wd,
aOld: {
aFileName: _cache_aRenamed_local[cookie].aFileName,
aExtra: {
nixInotifyFlags: _cache_aRenamed_local[cookie].aExtra.nixInotifyFlags
}
}
}
}
FSChanges.push(rezObj);
} else {
// the one in cache was removed from its parent folder, this one here was added to parent folder. so this is detect as file moved from one watched dir to another watched dir
if (_cache_aRenamed_local[cookie].aFileName != fileName) {
console.error('whaaaaa wd\'s are differnt and got renamed-to so names should be same');
_cache_aRenamed_local[cookie].aEvent = 'haaa names are different?? im just going to say REMOVED as a guess i have never encoutnered this situation yet and i dont think we ever should';
FSChanges.push(_cache_aRenamed_local[cookie]);
} else {
_cache_aRenamed_local[cookie].aEvent = 'removed';
FSChanges.push(_cache_aRenamed_local[cookie]);
}
}
delete _cache_aRenamed_local[cookie];
} else {
var rezObj = {
aFileName: fileName,
aEvent: 'added',
aExtra: {
aOSPath_parentDir_identifier: wd
}
}
FSChanges.push(rezObj);
}
} else if (aEvent == 'renamed-from') {
var rezObj = {
aFileName: fileName,
aEvent: aEvent,
aExtra: {
aOSPath_parentDir_identifier: wd
}
}
_cache_aRenamed_local[cookie] = rezObj;
} else {
var rezObj = {
aFileName: fileName,
aEvent: aEvent,
aExtra: {
aOSPath_parentDir_identifier: wd
}
}
FSChanges.push(rezObj);
}
if (len == 0) {
break;
};
i += nixStuff.sizeField0 + nixStuff.sizeField1 + nixStuff.sizeField2 + nixStuff.sizeField3 + parseInt(len);
} while (i < length);
for (var cookieLeft in _cache_aRenamed_local) {
// whatever is left in _cache_aRenamed_local is `removed` things
_cache_aRenamed_local[cookieLeft].aEvent = 'removed';
FSChanges.push(rezObj);
}
console.error('loop ended:', 'numElementsRead:', numElementsRead);
if (FSChanges.length > 0) {
return FSChanges;
} // else dont return and continue loop
}
}
I use this function to convert the flags to a string of like renamed-from or renamed-to
function convertFlagsToAEventStr(flags) {
var default_flags = {
IN_CLOSE_WRITE: 'contents-modified',
IN_MOVED_TO: 'renamed-to', // can also be a added
IN_DELETE: 'removed',
IN_MOVED_FROM: 'renamed-from', // can also be a removed
IN_CREATE: 'added'
};
for (var f in default_flags) {
if (flags & ostypes.CONST[f]) {
return default_flags[f];
}
}
return 'UNKNOWN FLAG';
}

Automatic be bold character string?

On html:
I get a character :
“The Theory of Everything,” may have a few more magic tricks up his sleeve. Sources tell Variety that Redmayne is the favorite to play Newt Scamander in Warner Bros.’ hotly-anticipated “Harry Potter” spin-off, “...
When I will process it by html agility pack(using LINQ) then It be show off:
“The Theory of Everything,” may have a few more magic tricks up his sleeve. Sources tell Variety that Redmayne is the favorite to play Newt Scamander in Warner Bros.’ hotly-anticipated “Harry Potter” spin-off, “...
I want these bold character on html when take down on my app then still keep bold character(or color). Can it be do that?
foreach(var pos in pos_block)
{
//get header, pronunciton
var pronuncationuk=pos.Descendants("span").FirstOrDefault(x => x.GetAttributeValue("class", "") == "sound audio_play_button pron-icon uk");
var pronuncationus=pos.Descendants("span").FirstOrDefault(x => x.GetAttributeValue("class", "") == "sound audio_play_button pron-icon us");
var pos_head = pos.Descendants("span").FirstOrDefault(x => x.GetAttributeValue("class", "") == "pos-head");
////
////
////
var id = pos.Descendants("div").Where(x => x.GetAttributeValue("class", "") == "sense-block");
if(id!=null)
{
foreach(var node in id)
{
result = new ResultToSearch();
var span_h2 = node.Descendants("h2").FirstOrDefault(x => x.GetAttributeValue("class", "") == "");
var sense_body = node.Descendants("div").FirstOrDefault(x => x.GetAttributeValue("class", "") == "sense-body");
if(j==1)
{
if(section_title!=null)
{
result.vocabulary = section_title.InnerText.Trim();
}
if(pronuncationuk!=null)
{
result.pronunciationuk = pronuncationuk.GetAttributeValue("class","");
result.iconuk = "/Photos/uk.png";
}
if(pronuncationus!=null)
{
result.pronunciationus = pronuncationuk.GetAttributeValue("class", "");
result.iconus = "/Photos/us.png";
}
if(pos_head!=null)
{
result.poshead = pos_head.InnerText.Trim();
}
}
if(span_h2!=null)
{
result.senseblockh2 = span_h2.InnerText.Trim();
}
if(sense_body!=null)
{
result.sensebody = sense_body.InnerText.Trim();
}
arrays.Add(result);
j++;
}
//
}
//
j=1;
Try property InnerHtml instead of InnerText.
InnerHtml gets the HTML between the start and end tags of the object.
Whereas InnerText strips all HTML tags and returns the pure text content.

Registrer in array and new variable

I am trying to make a program where you can register expenses on someone.
i have 2 TextInputs, named "txt1" and "txt2"
I want to make an eventlistener where
If you put in a new name in “txt1”, it will be registered in an array, and a new variable will be created, and the number in “txt2” will be added to that variable.
If you put in a name that’s already in the array, the number in “txt2” will be added the variable which was created when you typed in the name the first time.
Here's what i got so far
var names:Array = new Array();
stage.addEventListener(KeyboardEvent.KEY_DOWN, regi)
function regi(evt)
{
if (evt.keyCode == 13)
{
var k:String = txt1.text
if (names.indexOf(k) != -1)
{
txt1.text+txt2.text
}
else
{
names[names.length] = k
var txt1.text = txt2.text
}
}
}
you can use Dictionary to do that ex:
var names:Dictionary = new Dictionary();
stage.addEventListener(KeyboardEvent.KEY_DOWN, regi);
function regi( evt:KeyboardEvent ):void
{
if (evt.keyCode == 13)
{
if( names[txt1.text] ) names[txt1.text] += txt2.text;
else names[txt1.text] = txt2.text;
}
}

Resources