"Parsing error: Unexpected token )" with bot - scripting

I'm making a discord bot and I'm trying to make a timer that every second it edits the message to time + 1 second like a real clock (Like 0:00). I'm a noob at this. This is my script:
const Discord = require("discord.js");
exports.run = async(bot, message, args) => {
let timerMessage = await message.channel.send('0');
for (i = 0, 10000000000) {
setTimeout(function() {
timerMessage.edit(timerMessage + 1);
}, 1000);
}
}
module.exports.help = {
name: "timer"
}
I have an error and it says: "Parsing error: Unexpected token )"
I would really appreciate it if you would help me with my problem, Thanks!
(Btw I'm using it in Glitch on Google Chrome)

It says that there's an unexpected token ) because you wrote your loop like this:
for (i = 0, 10000000000) {...}
You forgot to add the third argument (usually i++). Also, if you want it to run 10000000000 times you should write a comparison:
for (let i = 0; i < 10000000000; i++) {...}
I see what you're trying to achieve, but I would do it in a simpler way, using setInterval() instead of setTimeout().
setInterval(() => {
timerMessage.edit(timerMessage + 1);
}, 1000);

You seem to be missing a right parenthesis after the setTimeout function. I am not entirely familiar with what you are doing, but I would try something like this :
const Discord = require("discord.js");
exports.run = async (bot, message, args) => {
let timerMessage = await message.channel.send('0');
for (i = 0, 10000000000) {
setTimeout(function()) {
timerMessage.edit(timerMessage + 1);
}, 1000);
}
}
module.exports.help = {
name: "timer";
}
Although this should (maybe) replace the missing parenthesis in your code, it seems to have many other issues. For example, your for loop does not make much sense. Normally a for loop would look something like this (to repeat a certain number of times in java) :
for (int i = 0; i < 10; i++) {
System.out.println(i);
} // will print numbers 0-9, repeat 10 times
The whole chunk of code with the setTimeout bit seems to be messed up... It would help to have a little more context on what you are trying to do / some commenting in your code.
If you are trying to get into coding, I'd recommend something much more basic or some tutorials. CodingTrain has great coding videos on youtube and you will learn a ton no matter what language you go with. Hope this helped...

Related

Blacklisted words | Filter words discord.bs

I got one error with my blacklisted words, cannot read proprety ".id" of undefined. After "db.get(...)"
Thanks to help me!
// BLACKLISTED words
client.on('message', message => {
if(message.author.bot) return;
let wordarray = message.content.split(" ")
let filterWords = db.get(`blacklistwords_${message.guild.id}_${message.guild.id}`)
for(var i = 0; 1 < filterWords.length; i++) {
if(wordarray.includes(filterwords[i])) {
message.delete()
let Filter = new Discord.MessageEmbed()
.setColor('#FFE90F')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription('<a:AttentionPink:706154679796760657> | **This word is blacklisted from this guild!** Do not say that again!')
.setTimestamp()
message.author.send(Filter)
break;
}
}
});![enter image description here](https://i.stack.imgur.com/Gouis.jpg)
I think you should put your Guild ID in a var like so:
var guildID = message.guild.id;
If this is not working, well it's not the prettiest, but try using this line of code:
var guildID = bot.guilds.get(message.guild.id).id;
EDIT: Source
If the bot receives a message via DMs, it will not be able to get message.guild and that's why it says it is undefined. You can add something like if(message.channel.type === 'dm') return; so that the bot will not listen to DMs

SQLite database isn't holding multiple values under primary key in my Discord.js bot

To start off, here's my main bot.js code (Sorry if it seems like code spaghetti. I'm not the best with javascript):
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
const pack = require('./package.json');
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('ready', () => {
console.log(` Bot: ${client.user.tag}
Version: ${pack.version}
Logged in and clear for takeoff.`);
});
client.on("ready", () => {
const battle_leaderboard = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
if (!battle_leaderboard['count(*)']) {
sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER;").run();
sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
client.getScore = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points) VALUES (#id, #user, #guild, #points);");
client.removeScore = sql.prepare("DELETE FROM scores WHERE user=?");
});
client.on('message', message => {
if (!message.content.startsWith(auth.prefix) || message.author.bot) return;
const args = message.content.slice(auth.prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
switch (command) {
case 'ping':
client.commands.get('ping').execute(message, args);
break;
case 'mimic':
client.commands.get('mimic').execute(message, args);
break;
case 'add_role':
client.commands.get('add_role').execute(message, args);
break;
case 'remove_role':
client.commands.get('remove_role').execute(message, args);
break;
case 'bl_add_point':
if (message.member.roles.some(r=>["Fight Officiator"])) {
let score;
let member = message.mentions.members.first() || client.members.get(args[0]);
score = client.getScore.get(member.id, member.guild.id);
if (!score) {
score = { id: `${member.guild.id}-${member.id}`, user: member.username, guild: member.guild.id, points: 0}
}
score.points ++;
client.setScore.run(score);
message.channel.send(`Looks like ${member} got a win! Good one.`);
} else {
message.channel.send(`Sorry, this is only usable by GFOs.`);
};
break;
case '!bl_delete':
if (message.member.roles.some(r=>["Fight Officiator"])) {
let member = message.mentions.users.first();
client.removeScore.run(`${member.guild.id}-${member.id}`)
message.channel.send(`${member} has been set to zero on the leaderboard!`);
} else {
message.channel.send(`Sorry, this is only usable by GFOs.`);
};
break;
case 'bl':
const top5 = sql.prepare("SELECT * FROM scores WHERE guild = ? ORDER BY points DESC LIMIT 5;").all(message.guild.id);
const battleleaderboard = new Discord.RichEmbed()
.setColor('#FFD700')
.setTitle('The Battle Leaderboard - Current Rankings')
.setAuthor(`RankBot`)
.setDescription('The top fighters are displayed here.')
.setTimestamp()
.setFooter(`DM a Gang Fight Officiator to set up a spar with another member and possibly get your name registered onto RankBot's leaderboard!`);
for (const data of top5) {
battleleaderboard.addField(client.users.get(data.user), `${data.points} Win(s)`);
}
message.channel.send(battleleaderboard);
break;
};
});
client.login(auth.token);
I'm creating a bot that should be pretty simple:
The bot is a RankBot (at least that's what i dubbed it as), which is supposed to track the amount of wins in battles (since this is for a discord about a fighting game) using a special role that manually increments those wins with a command, then being able to pull up a leaderboard embed showing the people with the most wins. I'm testing it in a discord separate from the one it's for with a friend, and it seemingly worked until we commanded the bot to open the leaderboard. Nothing was shown. We thought it was strange, since it worked before when only one user was in the database, and I went to the PowerShell Command Line to see if there was an error message, and this showed up.
C:\Users\USER\Documents\OF_RankBot\bot.js:89
battleleaderboard.addField(client.users.get(data.user).tag || client.members.get(data.user).tag, `${data.points} Win(s)`);
^
TypeError: Cannot read property 'tag' of undefined
We were confused by what happened, so I removed the tag part of the command and used it again. The embed showed up this time, but it looked like this.
I assumed that what went wrong was that since they both had the same number of wins listed, the part of the bl command that sorts the users was confused. I then went and used bl_add_point on me and tried again. The near exact same embed was shown.
My guess as to what went wrong was that I messed up at some point when setting up the bl_add_point command, but I'm not sure how to fix the issue.
This isn't part of the main problem, but I can't seem to get bl_delete working either. No errors are shown when I use it. In fact, seemingly nothing happens. I'm not sure if these issues are connected, but I really only need the main issue fixed.
Thanks in advance.
edit: I found out partially what happened with the bl_delete issue, which was I simply put the prefix into the case when the prefix was already defined. Now when I put in the command, the PowerShell responds with:
C:\Users\USER\Documents\OF_RankBot\bot.js:72
client.removeScore.run(`${member.guild.id}-${member.id}`)
^
TypeError: Cannot read property 'id' of undefined

Dart splits long stdout data into two ProcessResult events

When listening to a long string output from a shell process, I receive the data in two chunks. How can I get the entire text?
Here is the code in question:
int i = 0;
Process.start('perl', ['print_text.pl']).then((Process p) {
p.stdout.transform(UTF8.decoder).listen((data) => print("${i++} ${data}"));
p.stdin.writeln('print');
});
The result from running this code is:
0 text.....
1 text.....
I've reported this issue as a bug here. You can run the sample app attached to the report to see the issue.
Try using UTF8.decodeStream().
import 'dart:io';
import 'dart:convert' show UTF8;
main() {
Process.start('ls', ['-la'])
.then((p) => UTF8.decodeStream(p.stdout))
.then((s) => print('Output:\n$s'));
}
I solved this problem by doing the following:
In the shell script, tag the start and the end of the shell's output with a random number.
In Dart, concatenate all the chunks together and use the tags to check if you got the complete result.
This solution does not require exiting the process to obtain the process result.
This is a sample code:
String text = '';
process.stdout.transform(UTF8.decoder).listen((String chunk) {
text = text + chunk;
if (text.substring(errors.length - 1) == text.substring(0, 1)) {
text = text.replaceFirst(new RegExp(r'^(\d+)'), '').replaceFirst(new RegExp(r'(\d+)$'), '');
// use process result then clear text value for subsequent process results
text = '';
}
});
It's not clear what the actual question is but I assume this is what you are looking for:
import 'dart:io';
import 'dart:convert' show UTF8;
void main() {
int i = 0;
String text = '';
Process.start('perl', ['analyze.pl']).then((p) {
p.stdout.transform(UTF8.decoder).listen((data) =>
text += data);
p.exitCode.then((_) => print(text));
});
}

Fiddler: Programmatically add word to Query string

Please be kind, I'm new to Fiddler
My purpose:I want to use Fiddler as a Google search filter
Summary:
I'm tired of manually adding "dog" every time I use Google.I do not want the "dog" appearing in my search results.
For example:
//www.google.com/search?q=cat+-dog
//www.google.com/search?q=baseball+-dog
CODE:
dog replaced with -torrent-watch-download
// ==UserScript==
// #name Tamper with Google Results
// #namespace http://superuser.com/users/145045/krowe
// #version 0.1
// #description This just modifies google results to exclude certain things.
// #match http://*.google.com
// #match https://*.google.com
// #copyright 2014+, KRowe
// ==/UserScript==
function GM_main () {
window.onload = function () {
var targ = window.location;
if(targ && targ.href && targ.href.match('https?:\/\/www.google.com/.+#q=.+') && targ.href.search("/+-torrent/+-watch/+-download")==-1) {
targ.href = targ.href +"+-torrent+-watch+-download";
}
};
}
//-- This is a standard-ish utility function:
function addJS_Node(text, s_URL, funcToRun, runOnLoad) {
var D=document, scriptNode = D.createElement('script');
if(runOnLoad) scriptNode.addEventListener("load", runOnLoad, false);
scriptNode.type = "text/javascript";
if(text) scriptNode.textContent = text;
if(s_URL) scriptNode.src = s_URL;
if(funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
targ.appendChild(scriptNode);
}
addJS_Node (null, null, GM_main);
At first I was going to go with Tampermonkey userscripts,Because I did not know about Fiddler
==================================================================================
Now,lets focus on Fiddler
Before Request:
I want Fiddler to add text at the end of Google Query string.
Someone suggested me to use
static function OnBeforeRequest(oSession: Session) {
if (oSession.uriContains("targetString")) {
var sText = "Enter a string to append to a URL";
oSession.fullUrl = oSession.fullUrl + sText;
}
}
Before Response:
This is where my problem lies
I totally love the HTML response,Now I just want to scrape/hide the word in the search box without changing the search results.How can it be done? Any Ideas?
http://i.stack.imgur.com/4mUSt.jpg
Can you guys please take the above information and fix the problem for me
Thank you
Basing on goal definition above, I believe you can achieve better results with your own free Google custom search engine service. In particular, because you have control over GCSE fine-tuning results, returned by regular Google search.
Links:
https://www.google.com/cse/all
https://developers.google.com/custom-search/docs/structured_search

Use of SPStatefulLongOperation

Can someone give me an example of the use of SPStatefulLongOperation? It's very poorly documented.
Here's an example of code I've just used. It applies a ThmxTheme (selectedTheme) to all SPWebs in an SPSite (site).
SPStatefulLongOperation.Begin(
"Applying theme to sites.",
"<span id='trailingSpan'></span>",
(op) =>
{
op.Run((opState) =>
{
for (int i = 0; i < site.AllWebs.Count; i++)
{
// Update status.
opState.Status = String.Format(
"<script type='text/javascript'>document.all.item('trailingSpan').innerText = '{0} ({1} of {2})';</script>",
site.AllWebs[i].Title,
i + 1,
site.AllWebs.Count);
// Set the theme.
selectedTheme.ApplyTo(site.AllWebs[i], true);
}
});
op.End(System.Web.HttpContext.Current.Request.UrlReferrer.ToString());
});
Note that the current value of opState.State is appended to the client's HTML (via HttpContext.Current.Response.Write and .Flush) every second. Thus you don't want to send any status message directly; you want to send some JavaScript that will update an existing status element on the page. (Here, the trailingSpan element.)