Discord bot Error Javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Do anyone know the problem at this javascript bot?
The window (Start.bat) just open and close. Main error is at line 100 - 115!
I use it on my discord server and i need a bot to ban words. The bot is edited to ban words, but now it don't work. (Line 100 - 115)
I hope someone knows the problem.
It is made for a bot named The parrot, and i need a working code.
Code:
const Discord = require('discord.js');
const bot = new Discord.Client();
var fs = require("fs");
var oldAuthor;
// ADD YOUR BOT'S TOKEN HERE
const token = " *censored* ";
bot.on('ready', () => {
});
bot.on('message', message => {
// Makes sure the first word is ~createcommand
var checkMessage = message.content.split(" ");
if(checkMessage[0] == "~lagkommando")
{
// commandText gets grabbed by splitting the string with |
// commandName gets grabbed by splitting the string with spaces
// command Name must have '~' in it just so you can't use any word you
// want
var commandText = message.content.split("|",2);
var commandName = message.content.split(" ");
if(commandName[1].charAt(0) == "~")
{
checkExistingCommand(commandText,commandName);
message.channel.sendMessage("Command " + commandName[1] + " has been created");
} else {
message.channel.sendMessage("Command must contain '~'");
}
}
/*
* Checks the commands.txt file to see if anyone posted the command.
* commands.txt is split with semi-colons. For loop to check every single
* command. If there is a match, then it opens up the txt file associate
* with that command. If there are multiple pictures then the user should
* type $random{} and then type in all the pictures in the brackets
* separated by semi-colons. If there is no $random{} then it just sends the
* message.
*/
fs.readFile('./commands/commands.txt','utf8',function(err,f){
var com = f.toString().split(";");
for(i = 0; i < com.length; i++)
{
if(message.content == com[i])
{
if(com[i] == "~commands")
{
message.channel.sendMessage(com);
break;
}
if(com[i] == "~help")
{
message.channel.sendMessage("Kommandoer: ~help, ~commands, ~database, ~Hei, ~memes og ~problem");
break;
}
var command = "./commands/" + com[i] + ".txt";
fs.readFile(command,'utf8', function(err,f){
try{
var com2 = f.toString().split(";");
var num = Math.random() * ((com2.length - 1) - 0) + 0;
message.channel.sendMessage(com2[Math.floor(num)]);
}
catch(err) {
console.error("",err);
}
});
}
}
});
});
function checkExistingCommand(commandText,commandName)
{
var com = commandName[1];
var desc = commandText[1];
var CE = false;
fs.readFile('./commands/commands.txt','utf8',function(err,f){
var findCommands = f.toString().split(";");
for(i = 0; i < findCommands.length; i++)
{
if(com == findCommands[i])
{
CE = true;
}
}
if(CE == true)
{
createCommand(desc,true,com);
} else if (CE == false)
{
createCommand(desc,false,com);
}
});
}
bot.on('message', message => {
var sender = message.author;
var msg = message.content.toUpperCase();
var prefix = '>'
if (sender.id === ' *Censored* ') {
return;
}
if (msg.includes('noob')) {
message.delete();
message.author.send('The word noob is banned, next time YOU can be banned! ')
}
}
// Appends and/or creates the text files.
function createCommand(desc,b,com)
{
var fileName = "./commands/" + com + ".txt";
if(b == true)
{
fs.writeFile(fileName,desc,function(err){
if(err) {
return console.error(err);
}
});
} else if (b == false){
fs.appendFile('./commands/commands.txt',com+';',(err) =>
{
if(err) throw err;
});
fs.writeFile(fileName,desc,function(err){
if(err) {
return console.error(err);
}
});
}
return;
}
bot.login(token);

I see that you need a better text editor.
On Line 115. (At the eventhandler for message recieved for your Client). You were missing your closing line of );.
Also, just in case you did not knew, I realised that you made your msg string variable to upper-case before you compared it to a lower-cased string for commands. Do note that includes() method is case-sensitive.
I am using Visual Studio Code for my text editor. If somehow it does not show you syntax highlighting and stuff, check the bottom right of the editor, it should display Javascript there.
If it does not, change it to Javascript and it should show the syntax highlighting and stuff correctly.

Related

Google Scripts - getFrom() is not a function error

I had this working before, without an issue, however ever since I put a filter in to remove all threads with more than 1 email it is now coming up with the not a function error. I remove the filter and it still comes up with the error, unsure what has caused this to completely break on me
function extractEmails() {
var htmlBody = getEmailHtml();
var labelName = "auto-reply-incoming";
// get all email threads that match label
var receivedSearchQuery = "label:"+labelName+" -is:sent";
var threads = GmailApp.search(receivedSearchQuery, 0, 500);
threads.forEach ((t, i) => {
let messages = t.getMessages();
let name = messages.getFrom();
let messageCount = t.getMessageCount();
if (messageCount > 1) {
label.removeFromThread(t);
}
if (messageCount <= 1) {
message.reply("Hi " +name+" \n" + "insert text here");
}
});
};
accidentally removed part of the script, fixed with the following code:
messages.forEach ((m, j) => {
let name = m.getFrom();
m.reply("Hi " +name+" \n" + "insert text here");
});
Replace
let name = messages.getFrom();
by
let name = messages[0].getFrom();
The above because getFrom() is method from Class GmailMessage but messages is an Array.
Reference
https://developers.google.com/apps-script/reference/gmail/gmail-message#getfrom

I want to read a certain amount of lines from a text file, and with them to create an object after reading the lines using JavaScript

okay, so this is my requirement: The application must read each line from the text file. A class can be used so that after reading a certain number of lines an object is created (in this way the application is more clearly structured). After reading a data set that corresponds to a student's data, it will add this data set to a string (separate so that it is presented in consecutive rows).
So i have these information of 2 students which are one under the other like in the picture below but without the name address etc.(it doesn't show quite right in here).
Ebonie Rangel
7175 Yukon Street
(507) 833-3567
Geography
Keenan Ellwood
2 Elm Lane
(894) 831-6482
History
which are in that file. and after reading every line, I am supposed to add Name in front of the first line, Address in front of the second.. phone and Course and so on.
The result should look like this:
This is what i have for now (I have to use Fetch to get to the file, async and await. or with Promise)
let button = document.getElementById("text-button");
let textArea = document.getElementById("text-area");
button.addEventListener("click", function () {
getData();
});
//cod fetch
async function getData() {
try {
let response = await fetch('fileName.txt');
if (response.status !== 200) {
throw new Error("Error while reading file");
}
let text = await response.text();
textArea.innerHtml = text;
} catch (err) {
textArea.innerHTML = 'Problem occurred: ' + err.message;
}
}
please help! I am stuck since forever on this.
Since you're pulling from a .txt file I think its important to understand the line breaks being used in the file. Here's a decent link I found that says all you need at the top of the article: End of Line or Newline Characters
I opened up the .txt file in Notepad++ like the article recommended and saw this:
The [CR][LF] being displayed after each line means that the newline characters used are \r\n.
When you understand that you realize you can use those line breaks to separate your string at each line break.
Here's the MDN for String.split() String.prototype.split()
String.split('\r\n') will return an Array of items, specifically the strings that were between but not including the \r\n characters.
Let's add this to the getData function:
let button = document.getElementById("text-button");
let textArea = document.getElementById("text-area");
button.addEventListener("click", function () {
getData();
});
//cod fetch
async function getData() {
try {
let response = await fetch('fileName.txt');
if (response.status !== 200) {
throw new Error("Error while reading file");
}
let text = await response.text();
//New stuff:
let arrayOfText = text.split('\r\n');
//Now we could add what we want before the text.
//We need to do every 4 lines so lets use this as a chance to learn % better
arrayOfText = arrayOfText.map((textItem, index) => {
let remainder = (index) % 4 //This will return 0, 1, 2, 3
//switch but you could use anything
switch (remainder) {
case 0:
textItem = 'Name: ' + textItem + '\r\n';
break;
case 1:
textItem = 'Address: ' + textItem + '\r\n';
break;
case 2:
textItem = 'Phone: ' + textItem + '\r\n';
break;
case 3:
textItem = 'Course: ' + textItem + '\r\n\r\n'; //two here to separate the groups
break;
//we need a default so lets make it just return textItem if something goes wrong
default:
break;
};
//Our new array has all the info so we can use
//Array.prototype.join('') with an empty string to make it a string.
//We need those old line breaks though so lets put them
//in the switch returns above.
text = arrayOfText.join('');
//End of my changes/////////////
textArea.innerHtml = text;
} catch (err) {
textArea.innerHTML = 'Problem occurred: ' + err.message;
}
}
I hope this works out for you. Its not the most glamorous solution but its a good learning solution because it uses only things you learn early on in your studies.
Let me know if I can clarify anything!
async function getData() {
try {
let response = await fetch('https://v-dresevic.github.io/Advanced-JavaScript-Programming/data/students.txt');
if (response.status !== 200) {
throw new Error("Error while reading file");
}
let text = await response.text();
const lines = text.split('\n');
const CHUNK_SIZE = 4;
textArea.innerHTML = new Array(Math.ceil(lines.length / CHUNK_SIZE))
.fill()
.map(_ => lines.splice(0, CHUNK_SIZE))
.map(chunk => {
const [Name, Address, Phone, Course] = chunk;
return {Name, Address, Phone, Course};
})
.reduce((text, record) => {
text += Object.keys(record).map(key => `${key} ${record[key]}`).join('\n') + '\n';
return text;
}, '');
} catch (err) {
textArea.innerHTML = 'Problem occurred: ' + err.message;
}
}

JavaScript How to create a new object in a function?

I'm writing up a discord bot that will store a request from a message via an object.
The idea is you call a function that will create a new object that can be referenced as a way to store information, rather than having 1 giant file or variable that has to be referenced every time a request to display said information.
Currently my code is setup with a rudimentary version of what I want.
var order1 = {
content: "",
author: "",
}
var order2 = {
content: "",
author: "",
}
var order3 = {
content: "",
author: "",
}
Even from my limited experience of programming, I know that is something is repeated, and often, there is usually a more effective way to write it.
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
// Interpret Command
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
var messagecont = message.content.replace('!haul.order', ""); // Remove command string
if(command === 'haul.order'){
message.channel.send("Hual order for:" + messagecont + " by: " + message.author.username);
orderNum++; // Update the current number order
if (orderNum > 3) {
message.channel.send("Sorry we only have 3 storage objects! Our programmer is to lazy to fix
this!");
}
if (orderNum == 1) {
order1.content = messagecont;
order1.author = message.author.username + ". ";
} else if (orderNum == 2) {
order2.content = messagecont;
order2.author = message.author.username + ". ";
} else if (orderNum == 3) {
order3.content = messagecont;
order3.author = message.author.username + ". ";
}
} else if (command =="show.orders") {
message.channel.send("Orderlist:" + order1.content + " by: " + order1.author + order2.content + " by: " + order2.author + order3.content + " by: " + order3.author);
}
});
For demonstration this code currently has only three storage objects, however adding more would "fix" the issue but in the wrong way. I ask again, is there a way to create a new object via a function? Something like order1, than order2 gets created. I know Create.object() exists, but from my knowledge, it only applies a template to a variable you had to declare.
It would be more dynamic by storing the orders in an array. To such array you may push() as many entries as you like.
//REM: Containing all the orders
const _listOfOrders = [];
document.querySelector('button').addEventListener('click', function(){
//REM: Getting input values
let tContent = document.getElementById('content')?.value || '';
let tAuthor = document.getElementById('author')?.value || '';
//REM: Adding the values to the list of orders
_listOfOrders.push({
Content: tContent,
Author: tAuthor
});
//REM: Outputting the current list
console.table(_listOfOrders)
});
<input type = 'text' id = 'content' value = 'Content'>
<input type = 'text' id = 'author' value = 'Author'>
<button>order</button>
Open the console to see the result.

Callback and/or Promises javascript

It's been 2 days since I'm trying to understand my error. So far what I've learnt is that i will never be able to bypass "undefined" returned value because i cannot understand callback or promises... I rode all the poste , did some easy exemple , but I 'm not undertanding how to make it happen on my code ...
function realloot(data){
return data;
console.log(`${data}`);
}
function lootbox_openning(callback, user, type, nombre){
let sqlQueryopenbox = `SELECT item_qty FROM users_items WHERE discord_id = '${user}' AND item_id = ${type};`
let token_won=0;
let real_token_won=0;
let common_pp_looted = 0;
let rare_pp_looted = 0;
let epic_pp_looted = 0;
db.query(sqlQueryopenbox, (err, rows) => {
let user_box_real_qty = rows[0].item_qty;
let sql;
if (err) {
real_token_won="sql error";
throw err;
}
if (nombre > user_box_real_qty){real_token_won="error number";}
else {
//function open
if (type==1) {
for (var i = 0; i <= nombre; i++){
token_won=little_box_open();
real_token_won=real_token_won+token_won;
}
var myreturn = callback(real_token_won);
console.log(`${myreturn}`);
return myreturn;
}
if (type==2) {}
if (type==3) {}
}
});
}
//this is a bot discord so huge on.message here...
case "open":
if (!args[1]) return message.channel.send('please give value box | bigbox');
if (args[1] ==='box' ){
if (!args[2]) {message.channel.send ("Specify number please");}
if (args[2]) {
var number = parseInt(args[2]);
if (Number.isInteger(number)){
message.channel.send ("You re openning "+args[2]+" boxes");
**var token_won = lootbox_openning(realloot, message.author.id, 1, args[2]);** //PROBLEM IS HERE
if (token_won==="error number"){message.channel.send ("Vous n'avez pas assez de box !");}
else {message.channel.send ("you won : "+token_won+" tokens !");}
}
else message.channel.send ("Give a valid number");
}
}
Please be gentle, I already hit my head so hard on others posts but it seems like I need more explanations...
async logic is a common place for newcommers to get tripped up on. But, it basically boils down to doing this:
Example of a synchronous code:
(this is assuming that db.query() was written as a sync function, which its not)
function doQuery(id) {
let res = db.query(`SELECT * FROM table WHERE id=${id}`)
return res
}
Example of asynchronous code (which using db.query() as an async function)
function doQuery(id, callback) {
db.query(`SELECT * FROM table WHERE id=${id}`, function(res) {
callback(res)
})
}
The main difference here is that instead of doing return res you have to do callback(res). This will always be the case when working with async code.
And its important to note that once you're in the async world, you can never go back to a sync world. i.e. This is impossible:
// some sync logic
let resultOfAsyncOperation = someAsyncFunction()
// some sync logic
Once you're dealing with callbacks, you have to use callbacks everywhere. This is because the user of an async function has to itself be async. The only exception is if you don't care about what's getting returned or when, you just want it to go off and do some task.
So, this is how these principles applies to your specific chunk of code. This snippet of code is exactly the issue I was describing - you're trying to use an async function inside of sync logic.
var number = parseInt(args[2]);
if (Number.isInteger(number)) {
message.channel.send("You re openning " + args[2] + " boxes"); **
var token_won = lootbox_openning(realloot, message.author.id, 1, args[2]); ** //PROBLEM IS HERE
if (token_won === "error number") {
message.channel.send("Vous n'avez pas assez de box !");
} else {
message.channel.send("you won : " + token_won + " tokens !");
}
} else message.channel.send("Give a valid number");
You'll have to convert this chunk of code to also be async, like this:
message.channel.send("You re openning " + args[2] + " boxes");
function callback(token_won) {
realloot(token_won)
if (token_won === "error number") {
message.channel.send("Vous n'avez pas assez de box !");
} else {
message.channel.send("you won : " + token_won + " tokens !");
}
}
lootbox_openning(callback, message.author.id, 1, args[2]);
(it's possible I didn't fully understand how you intended your original code to work, so take this example with a grain of salt. It shows the principle, but you'll have to tweak it to work for your needs)

Javascript e-mail validation of specific domains

I can’t figure out what is missing so that when e-mail is valid it will skip the last invalid message and move to next item on form for validation:
enter code here
if (document.form1.email.value.length > 0) {
var tst = document.form1.email.value;
var okd = ['bankofamerica.com','baml.com','magner.com','ml.com','ust.com','ustrust.com']
for (var i = 0; i < okd.length; i++) { okd[i] == okd[i].toLowerCase() }
var emailRE = /^[a-zA-Z0-9._+-]+#([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})$/
var aLst = emailRE.exec(tst)
if (!aLst) {
alert(tst + ' is not a valid e-mail')
} else {
var sLst = aLst[1].toLowerCase()
for (var i = 0; i < okd.length; i++) {
if (sLst == okd[i]) {
// alert(aLst[1] + ' is allowed');-->
}
}
if (i == okd.length) alert(aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.')
document.form1.email.select();
return false;
}
}
I'd recommend placing this code into a function, maybe named ValidateEmail().
In your loop: if you've determined the email is valid, return true;. This will prevent further execution. If that domain doesn't match, have it continue looping to check the others.
If the loop completes without returning true, you'll know it didn't match anything so return false; at the very end.
EDIT: Use try/catch instead:
if (document.form1.email.value.length > 0) {
var tst = document.form1.email.value;
var okd = ['bankofamerica.com','baml.com','magner.com','ml.com','ust.com','ustrust.com']
for (var i = 0; i < okd.length; i++) { okd[i] == okd[i].toLowerCase() }
try {
var emailRE = /^[a-zA-Z0-9._+-]+#([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})$/
var aLst = emailRE.exec(tst)
if (!aLst)
throw (tst + ' is not a valid e-mail');
// isValidDomain will be changed to 'true' only if it matches an item in the array
var isValidDomain = false;
var sLst = aLst[1].toLowerCase()
for (var i = 0; i < okd.length; i++) {
if (sLst == okd[i]) {
isValidDomain = true;
// We break here because a match has been found - no need to compare against the other domain names.
break;
}
}
if(!isValidDomain)
throw (aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.');
// If execution reaches here, you know it passed both tests!
return true;
}
catch(err) {
// This code block runs whenever an error occurs
alert(err);
document.form1.email.select();
return false;
}
}
throw basically acts like a goto command. It will jump directly to the catch(err) portion of the code.
More info about try, catch, and throw:
http://www.w3schools.com/js/js_try_catch.asp
http://www.w3schools.com/js/js_throw.asp
Thank you very much Colin!
I had to remove the following 2 lines to avoid halting the code from running on to next validation field:
isValidDomain = true;
// We break here because a match has been found - no need to compare against the other domain names.
// break - exits code from running on down to next item on page
}
}
if (!isValidDomain)
throw (aLst[1] + ' is not allowed. Please enter an email address with an authorized domain.');
// If execution reaches here, you know it passed both tests!
// return true; - was not needed, stops code from running on page
}
catch (err) {

Categories

Resources