I'm working on the twich bot and I'm trying to check if specific user already ran a command. I have this piece of code:
if (message === '!iq') {
var iqNum = Math.floor(Math.random() * 200) + 1;
client.action('jimmytag', `${user['display-name']} Your IQ is ` + iqNum);
}
It just randomizes the number between 1-200. But I want it to check if user already ran it before, and print the difference. So if I type the command two times, the first time for example it will print "Your IQ is 100"; But the second time it should be "Your IQ is 150 (+50)". How can I do that?
Create an empty object (below const client)
const userIQ = {};
Code for the Twich chat command
if (message.toLowerCase() === '!iq') {
const hasIQ = userIQ.hasOwnProperty('userid');
if (hasIQ == true) {
var oldiqNum = userIQ['useriq']
var newiqNum = Math.floor(Math.random() * 200) + 1;
var iqDif = newiqNum-oldiqNum;
userIQ.useriq = newiqNum;
if(iqDif>0){
client.action(channel, `#${userstate.username} Your IQ is ` + newiqNum + `(` + `+` + iqDif + `)`);
} else {
client.action(channel, `#${userstate.username} Your IQ is ` + newiqNum + `(` + iqDif + `)`);
}
} else {
var iqNum = Math.floor(Math.random() * 200) + 1;
var userid = userstate['user-id'];
userIQ.userid = userid;
userIQ.useriq = iqNum;
client.action(channel, `#${userstate.username} Your IQ is ` + iqNum);
}
}
Related
I am writing my first Discord bot and I am fairly new to JavaScript, especially dealing with libraries such as Discord.JS. My project here is a Reminder Discord bot, which takes a user input by prefix, stores and checks data based on time, then outputs a user inputted message when the user time set is the same as current time (to alert).
My current issue is that I don't know how to send a message to a discord channel using the client outside of the two specificed scopes. Ideally, I'd like to send a message between
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
}
Thank you
const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField, Permissions } = require(`discord.js`);
const { type } = require("os");
const prefix = '!';
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
var machineTime = null;
var userTime = null;
// Discord Client Ready Check
client.on("ready", () => {
console.log("Bot is online!")
})
// Message Listener
client.on("messageCreate", (message) => {
if (message.author.bot) return;
//Split input into array & get current date
var content = message.content.split(" ");
console.log(content);
// Output
if (content[0] === prefix + 'set-reminder'){
//Start timer
setInterval(checkTime, 1000);
//Convert user time
var inputTime = content[2].split(':');
var inputDate = content[1].split('/');
//Change store metrics and format date
var convertMinutes = parseInt(inputTime[1]);
var convertHours = parseInt(inputTime[0]);
var convertMonth = parseInt(inputDate[0]);
var convertDay = parseInt(inputDate[1]);
var formatDate = convertMonth + "/" + convertDay + "/" + inputDate[2];
//If PM add 12 hours to time input
if (content[3].toLowerCase() === "pm") {
convertHours += 12;
}
userTime = formatDate + " " + convertHours + " " + convertMinutes;
//Send reminder confirmation
message.channel.send("Members will be alerted at " + content[1] + ":white_check_mark:");
}
// Input Array: 0 = prefix, 1 = date, 2 = time, 3 = am/pm, 4 = channel, 5 = message
})
//Current Time Check
const checkTime = () => {
var machineOutput = new Date();
var machineDate = machineOutput.toLocaleDateString();
var machineMinutes = machineOutput.getMinutes();
var machineHours = machineOutput.getHours();
machineTime = machineDate + " " + machineHours + " " + machineMinutes;
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
}
console.log(machineTime);
}
client.login("MY_LOGIN_KEY");```
As long as you have access to the client, you can send a message to any channel.
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
const channel = await client.channels.fetch('channel id');
channel.send('...');
}
I am attaching the URL to the issue I am talking about. If inspected, you can see the error.
I have program that is taking in data in a form and comparing it against json data and then outputting json data. I used an xmlhttprequest to grab the json and convert it to javascript array. I keep getting an error specifically about the following line of code. I will past the entire js file underneath.
Now the code is actually working at this time, but earlier it was not, and obviously I should find and fix the errors no matter what. I have been researching for hours, and can't fix the problem. Help would be so appreciated.
URL: https://oacaa.org/self-sufficiency-calculator/
if (arrBirds[i][1] === userAdultInt && arrBirds[i][2] === userInfantInt && arrBirds[i][3] === userPreschoolInt && arrBirds[i][4] === userSchoolageInt && arrBirds[i][5] === userTeenageInt && arrBirds[i][9] === userCounty)
function overIt() {
// Create XMLHttpRequest object.
var oXHR = new XMLHttpRequest();
// Initiate request.
oXHR.onreadystatechange = reportStatus;
oXHR.open("GET","/oacaa.json", true); // get json file.
oXHR.send();
function reportStatus() {
if (oXHR.readyState == 4) { // Check if request is complete.
// Create an HTML table using response from server.
createTableFromJSON(this.responseText);
}
}
// Create an HTML table using the JSON data.
function createTableFromJSON(jsonData) {
const userAdult = document.getElementById("adult").value;
const userAdultInt = parseInt(userAdult,10);
const userInfant = document.getElementById("infant").value;
const userInfantInt = parseInt(userInfant,10);
const userPreschool = document.getElementById("preschool").value;
const userPreschoolInt = parseInt(userPreschool,10);
const userSchoolage = document.getElementById("schoolage").value;
const userSchoolageInt = parseInt(userSchoolage,10);
const userTeenage = document.getElementById("teenage").value;
const userTeenageInt = parseInt(userTeenage,10);
const userCounty = document.getElementById("county").value;
const userChildren = Number(userInfantInt) + Number(userPreschoolInt) + Number(userSchoolageInt) + Number(userTeenageInt);
var arrBirds = [];
arrBirds = JSON.parse(jsonData); // Convert JSON to array.
for (i = 0; i < 63274; i++){
if (arrBirds[i][1] === userAdultInt && arrBirds[i][2] === userInfantInt && arrBirds[i][3] === userPreschoolInt && arrBirds[i][4] === userSchoolageInt && arrBirds[i][5] === userTeenageInt && arrBirds[i][9] === userCounty) {
// EXPENSES
document.getElementById("housing").innerHTML = arrBirds[i][10];
document.getElementById("childcare").innerHTML = arrBirds[i][11];
document.getElementById("food").innerHTML = arrBirds[i][12];
document.getElementById("transportation").innerHTML = arrBirds[i][13];
document.getElementById("healthcare").innerHTML = arrBirds[i][14];
document.getElementById("misc").innerHTML = arrBirds[i][15];
document.getElementById("taxes").innerHTML = arrBirds[i][16];
// TAX CREDITS
document.getElementById("EITC").innerHTML = arrBirds[i][17];
document.getElementById("CCTC").innerHTML = arrBirds[i][18];
document.getElementById("CTC").innerHTML = arrBirds[i][19];
// SELF SUFFICIENCY WAGE
document.getElementById("hourly").innerHTML = arrBirds[i][20];
document.getElementById("monthly").innerHTML = arrBirds[i][21];
document.getElementById("annual").innerHTML = arrBirds[i][22];
document.getElementById("emergency").innerHTML = arrBirds[i][23];
const userName = document.getElementById("name").value;
const userCounty = document.getElementById("county").value;
//PERSONAL INFO
document.getElementById("personal-info").innerHTML = "Self Sufficiency Report for" + " " + userName + "'s" + " " + "household living in " + " " + userCounty + "." + " " + "The residents in this household include" + " " + userAdultInt + " " + "adult(s)" + " " + "and" + " " + userChildren + " " + "child(ren)" + ".";
var x = document.getElementById("form-user-input");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
var j = document.getElementById("income-form");
if (j.style.display === "block") {
j.style.display = "none";
} else {
j.style.display = "block";
}
} else {
document.getElementById('error').innerHTML = "We do not currently have information for this family type. We apologize in advance." }
}
}
}
I've been working on a project for a friend's discord server, where I want to keep sort of a 'database' on our members, like a warning (or strike) count, their age (because we've been having issues with underage members) and some notes. I've been using tutorials as I'm pretty new to javascript, and really new to Discord.js, so, I'm not really sure on what I'm doing yet.
(to clarify, I'm not getting any errors, it's just not updating to the new file)
Here are the resources I've used:
https://www.youtube.com/watch?v=JB1rWJRafRA
https://discordjs.guide/popular-topics/collectors.html#message-collectors
https://www.youtube.com/watch?v=J2bKyv5pp-M
And my code: (sorry in advance, it's really messy)
const Discord = require('discord.js');
const fs = require('fs');
const jsonfile = require('jsonfile');
const Client = new Discord.Client();
var data = {}; //start of member activeness tracker
if (fs.existsSync('data.json')) {
data = jsonfile.readFileSync('data.json');
}
console.log("Bot Starting...");
Client.on("ready", () => console.log('ServerMgr is ready! Now managing servers!')); //bot init complete
Client.on("message", (message) => {
if (message.guild.id in data === false) {data[message.guild.id] = {} } //if new guild
const guildData = data[message.guild.id];
if (message.author.id in guildData === false) {
guildData[message.author.id] = {
username: message.author.username,
message_count: 0,
last_message: 0,
age: 0,
times_left: 0,
strikes: 0,
notes: ""
}
}
const userData = guildData[message.author.id];
userData.message_count ++
userData.last_message = Date.now();
jsonfile.writeFileSync('data.json', data)
const parts = message.content.split(' ')
if(parts[0] === ';ping') {message.reply('```SeverMgr is online!\nCurrent Ping: ' + (Math.abs(Date.now() - message.createdTimestamp))/ 100 + " ms```")}
if(parts[0] === ';read') {
if (message.mentions.members.first()) {
var user = message.mentions.users.first()
const id = user.id
const userData = guildData[id]
const lastMessage = new Date(userData.last_message)
message.channel.send("Getting data for " + user.username + "#" + user.discriminator + "...")
message.channel.send("Sent " + userData.message_count + " messages\n" +
"Last message was sent at: " + lastMessage + "\n" +
"Age: " + userData.age + "\n" +
"Times user left server: " + userData.times_left + "\n" +
"Strikes: " + userData.strikes + "\n" +
userData.notes);
} else {
message.reply("You need to mention a user to get their data!");
}
}
if(parts[0] === ';write') {
if (message.mentions.members.first()) {
var user = message.mentions.users.first();
const id = user.id;
const userData = guildData[id];
message.channel.send("What data point do you want to edit? \n Accepted responses are: \n `message count` \n `age` \n `times left` \n `strikes` \n `notes` ")
let filter = m => m.content.includes('message count' || 'age' || 'times left' || 'strikes' || 'notes') && !m.author.bot ;
let collector = new Discord.MessageCollector(message.channel, filter);
collector.on('collect', (m,col) => {
var res = "";
let mess = m.content;
console.log(mess);
if (mess == ("message count")) {res = 'message_count' }
if (mess == ("age")) {res = 'age' }
if (mess == ("times left")) {res = 'times_left' }
if (mess == ("strikes")) {res = 'strikes' }
if (mess == ("notes")) {res = 'notes' }
console.log(res);
message.channel.send("Editing " + res + "\n The current value is:");
if (res == "message count") {message.channel.send(userData.message_count) }
if (res == "age") {message.channel.send(userData.age)}
if (res == "times left") {message.channel.send(userData.times_left)}
if (res == "strikes") {message.channel.send(userData.strikes)}
if (res == "notes") {message.channel.send(userData.notes)}
collector.stop();
message.channel.send("The value currently located inside of " + res + " will be overwritten, so if you want to edit the content directly, copy the message above, and paste it into the send box.");
let filter = m => !m.author.bot;
let collector2 = new Discord.MessageCollector(message.channel, filter);
});
collector2.on('collect', m => {
var mess = m.content;
if (res === "message count") {userData.message_count = mess }
if (res == "age") {userData.age = mess}
if (res == "times left") {userData.times_left = mess}
if (res == "strikes") {userData.strikes = mess}
if (res == "notes") {userData.notes = mess}
message.channel.send("Data saved!");
console.log("Saving " + mess);
var guildData = data[message.guild.id];
var userData = guildData[message.author.id];
var pointData = userData[res];
console.log("old data");
console.log(pointData);
pointData = mess;
console.log("new data");
console.log(pointData);
jsonfile.writeFileSync('data.json', data) //HERE IS THE ISSUE
collector2.stop();
});
} else {
message.reply("You need to mention a user to edit their data!");
}
}
});
Client.login('TOKEN');
The data is stored as such:
'779904676879007744': {
username: 'SeverMgr',
message_count: 129,
last_message: 1606028233445,
age: 0,
times_left: 0,
strikes: 0,
notes: ''
Thanks for any help!
The equal sign will create a copy of your variable. If you update the new variable it won't update the value of the previous one, since it's not a reference.
Example
var x = 1
var y = x
var y = 2
---
x will still be 1
y will be 2
So in your case you could do this to update the data variable
data[message.guild.id][message.author.id][res] = mess
Instead of this, since you are updating copies and not data directly.
var guildData = data[message.guild.id]
var userData = guildData[message.author.id]
var pointData = userData[res]
pointData = mess
Can some body help me modify this script.
The purpose of the script is to change bids for the keywords based on average position. One of the assumptions that the script has is that it sets a firstpagebid for the keyword but it won't allow for the bid to go below the firstpagebid even if the position is too high.
Is there a way to remove this restriction? so basically if the new cpc calculated is lower than the first page bid then it allows for the new cpc to be lower than the firstpage bid.
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.5
* Updated 2015-09-28 to correct for report column name changes
* Updated 2016-02-05 to correct label reading, add extra checks and
* be able to adjust maximum bid increases and decreases separately
* Updated 2016-08-30 to correct label reading from reports
* Updated 2016-09-14 to update keywords in batches
* Updated 2016-10-26 to avoid DriveApp bug
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 14.50;
// Bids will not be increased past this maximum.
var minBid = 3.0;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 10.00;
// The script avoids reducing a keyword's bid below its first page bid estimate. If you think
// Google's first page bid estimates are too high then use this to overrule them.
var dataFile = "AveragePositionData.txt";
// This name is used to create a file in your Google Drive to store today's performance so far,
// for reference the next time the script is run.
var useFirstPageBidsOnKeywordsWithNoImpressions = true;
// If this is true, then if a keyword has had no impressions since the last time the script was run
// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).
// If this is false, keywords with no recent impressions will be left alone.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Advanced Options
var bidIncreaseProportion = 0.20;
var bidDecreaseProportion = 0.25;
var targetPositionTolerance = 0.3;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"\n");
Logger.log("File '" + dataFile + "' has been created.");
} else {
var file = files.next();
if (files.hasNext()) {
Logger.log("Error - more than one file named '" + dataFile + "'");
return;
}
Logger.log("File '" + dataFile + "' has been read.");
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Get the current date/time
var currentTime = new Date(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "MMM dd,yyyy HH:mm:ss"));
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var hourOfDay = currentTime.getHours();
var dayOfWeek = days[currentTime.getDay()]; //Added on 9/21/2015
// Prevent adjustments if not in between 8am and 11pm and Diffrent running time by date - Added on 9/21/2015 (important allows to set time based on day)
switch (dayOfWeek) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
if (hourOfDay < 8 || hourOfDay >= 21) {
Logger.log("Not the Right Time");
return;
}
break;
case 'Saturday':
case 'Sunday':
if (hourOfDay < 8 || hourOfDay >= 18) {
Logger.log("Not the Right Time");
return;
}
break;
}
Logger.log("Right Time");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
Logger.log(labelIds.length + " position labels have been found.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var keywordData = {
//UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },
//CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,
//Criteria: }
}
var ids = [];
var uniqueIds = [];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var report = AdWordsApp.report(
'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED ' +
'AND LabelIds CONTAINS_ANY [' + labelIds.join(",") + '] ' +
'AND AdNetworkType2 = SEARCH ' +
'AND Device NOT_IN ["HIGH_END_MOBILE"] ' +
'DURING TODAY'
);
var rows = report.rows();
while(rows.hasNext()){
var row = rows.next();
if (row["BiddingStrategyType"] != "cpc") {
if (row["BiddingStrategyType"] == "Enhanced CPC"
|| row["BiddingStrategyType"] == "Target search page location"
|| row["BiddingStrategyType"] == "Target Outranking Share"
|| row["BiddingStrategyType"] == "None"
|| row["BiddingStrategyType"] == "unknown") {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses '" + row["BiddingStrategyType"] + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");
} else {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses the bidding strategy '" + row["BiddingStrategyType"] + "' rather than manual CPC. This keyword will be skipped.");
continue;
}
}
var positionTarget = "";
if (row["Labels"].trim() == "--") {
continue;
}
var labels = JSON.parse(row["Labels"].toLowerCase()); // Labels are returned as a JSON formatted string
for (var i=0; i<labels.length; i++) {
if (labels[i].substr(0,"position ".length) == "position ") {
var positionTarget = parseFloat(labels[i].substr("position ".length-1).replace(/,/g,"."),10);
break;
}
}
if (positionTarget == "") {
continue;
}
if (integrityCheck(positionTarget) == -1) {
Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row["Criteria"] + "' in campaign '" + row["CampaignName"] + "'");
continue;
}
ids.push(parseFloat(row['Id'],10));
var uniqueId = row['AdGroupId'] + idJoin + row['Id'];
uniqueIds.push(uniqueId);
keywordData[uniqueId] = {};
keywordData[uniqueId]['Criteria'] = row['Criteria'];
keywordData[uniqueId]['ThisHour'] = {};
keywordData[uniqueId]['ThisHour']['Impressions'] = parseFloat(row['Impressions'].replace(/,/g,""),10);
keywordData[uniqueId]['ThisHour']['AveragePosition'] = parseFloat(row['AveragePosition'].replace(/,/g,""),10);
keywordData[uniqueId]['CpcBid'] = parseFloat(row['CpcBid'].replace(/,/g,""),10);
keywordData[uniqueId]['FirstPageCpc'] = parseFloat(row['FirstPageCpc'].replace(/,/g,""),10);
setPositionTargets(uniqueId, positionTarget);
}
Logger.log(uniqueIds.length + " labelled keywords found");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
setBidChange();
setMinMaxBids();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/* var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "HH"), 10);
if (currentHour != 0) {
var data = file.getBlob().getDataAsString();
var data = data.split(lineJoin);
for(var i = 0; i < data.length; i++){
data[i] = data[i].split(fieldJoin);
var uniqueId = data[i][0];
if(keywordData.hasOwnProperty(uniqueId)){
keywordData[uniqueId]['LastHour'] = {};
keywordData[uniqueId]['LastHour']['Impressions'] = parseFloat(data[i][1],10);
keywordData[uniqueId]['LastHour']['AveragePosition'] = parseFloat(data[i][2],10);
}
}
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
findCurrentAveragePosition();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Batch the keyword IDs, as the iterator can't take them all at once
var idBatches = [];
var batchSize = 5000;
for (var i=0; i<uniqueIds.length; i += batchSize) {
idBatches.push(uniqueIds.slice(i,i+batchSize));
}
Logger.log("Updating keywords");
// Update each batch
for (var i=0; i<idBatches.length; i++) {
try {
updateKeywords(idBatches[i]);
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords(idBatches[i]);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Logger.log("Writing file.");
// var content = resultsString();
// file.setContent(content);
Logger.log("Finished.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function integrityCheck(target){
var n = parseFloat(target, 10);
if(!isNaN(n) && n >= 1){
return n;
}
else{
return -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setPositionTargets(uniqueId, target){
if(target !== -1){
keywordData[uniqueId]['HigherPositionTarget'] = Math.max(target-targetPositionTolerance, 1);
keywordData[uniqueId]['LowerPositionTarget'] = target+targetPositionTolerance;
}
else{
keywordData[uniqueId]['HigherPositionTarget'] = -1;
keywordData[uniqueId]['LowerPositionTarget'] = -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function bidChange(uniqueId){
var newBid = -1;
if(keywordData[uniqueId]['HigherPositionTarget'] === -1){
return newBid;
}
var cpcBid = keywordData[uniqueId]['CpcBid'];
var minBid = keywordData[uniqueId]['MinBid'];
var maxBid = keywordData[uniqueId]['MaxBid'];
if (isNaN(keywordData[uniqueId]['FirstPageCpc'])) {
Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
var firstPageBid = Math.min(keywordData[uniqueId]['FirstPageCpc'], keywordData[uniqueId]['FirstPageMaxBid'], maxBid);
var currentPosition = keywordData[uniqueId]['CurrentAveragePosition'];
var higherPositionTarget = keywordData[uniqueId]['HigherPositionTarget'];
var lowerPositionTarget = keywordData[uniqueId]['LowerPositionTarget'];
var bidIncrease = keywordData[uniqueId]['BidIncrease'];
var bidDecrease = keywordData[uniqueId]['BidDecrease'];
if((currentPosition > lowerPositionTarget) && (currentPosition !== 0)){
var linearBidModel = Math.min(2*bidIncrease,(2*bidIncrease/lowerPositionTarget)*(currentPosition-lowerPositionTarget));
var newBid = Math.min((cpcBid + linearBidModel), maxBid);
}
if((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {
var linearBidModel = Math.min(2*bidDecrease,((-4)*bidDecrease/higherPositionTarget)*(currentPosition-higherPositionTarget));
var newBid = Math.max((cpcBid-linearBidModel),minBid);
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
}
if((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)){
var newBid = firstPageBid;
}
if (isNaN(newBid)) {
Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
return newBid;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function findCurrentAveragePosition(){
for(var x in keywordData){
if(keywordData[x].hasOwnProperty('LastHour')){
keywordData[x]['CurrentAveragePosition'] = calculateAveragePosition(keywordData[x]);
} else {
keywordData[x]['CurrentAveragePosition'] = keywordData[x]['ThisHour']['AveragePosition'];
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function calculateAveragePosition(keywordDataElement){
var lastHourImpressions = keywordDataElement['LastHour']['Impressions'];
var lastHourAveragePosition = keywordDataElement['LastHour']['AveragePosition'];
var thisHourImpressions = keywordDataElement['ThisHour']['Impressions'];
var thisHourAveragePosition = keywordDataElement['ThisHour']['AveragePosition'];
if(thisHourImpressions == lastHourImpressions){
return 0;
}
else{
var currentPosition = (thisHourImpressions*thisHourAveragePosition-lastHourImpressions*lastHourAveragePosition)/(thisHourImpressions-lastHourImpressions);
if (currentPosition < 1) {
return 0;
} else {
return currentPosition;
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function keywordUniqueId(keyword){
var id = keyword.getId();
var idsIndex = ids.indexOf(id);
if(idsIndex === ids.lastIndexOf(id)){
return uniqueIds[idsIndex];
}
else{
var adGroupId = keyword.getAdGroup().getId();
return adGroupId + idJoin + id;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setMinMaxBids(){
for(var x in keywordData){
keywordData[x]['MinBid'] = minBid;
keywordData[x]['MaxBid'] = maxBid;
keywordData[x]['FirstPageMaxBid'] = firstPageMaxBid;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setBidChange(){
for(var x in keywordData){
keywordData[x]['BidIncrease'] = keywordData[x]['CpcBid'] * bidIncreaseProportion/2;
keywordData[x]['BidDecrease'] = keywordData[x]['CpcBid'] * bidDecreaseProportion/2;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function updateKeywords(idBatch) {
var keywordIterator = AdWordsApp.keywords()
.withIds(idBatch.map(function(str){return str.split(idJoin);}))
.get();
while(keywordIterator.hasNext()){
var keyword = keywordIterator.next();
var uniqueId = keywordUniqueId(keyword);
var newBid = bidChange(uniqueId);
if(newBid !== -1){
keyword.setMaxCpc(newBid);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*function resultsString(){
var results = [];
for(var uniqueId in keywordData){
var resultsRow = [uniqueId, keywordData[uniqueId]['ThisHour']['Impressions'], keywordData[uniqueId]['ThisHour']['AveragePosition']];
results.push(resultsRow.join(fieldJoin));
}
return results.join(lineJoin);
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
As I understand, the script increases the cpcBid when the current average position is too high, and decreases it when the position is too low.
But when the bid is decreased and the previous bid is more than firstPageBid, the new bid will not decrease below firstPageBid.
Remove
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
to allow your new bid to go lower than firstPageBid.
I am trying to open the serial port 2 on my beagle bone, using the following code:
var b = require('bonescript');
var x = '/dev/ttyO2';
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200,
parser: b.serialParsers.readline("\n")
});
The complete code:
var b = require('bonescript');
var x = '/dev/ttyO2';
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200,
parser: b.serialParsers.readline("\n")
});
b.pinMode("P9_17", b.OUTPUT);
var countTry =2;
var i = 0; // to loop over the array
var waiting_interval = 3000; // waiting for every slave to reply
var deli;
var slaves = ["S1", "S2" , "S3", "S4", "S5", "S6"];
var counter=[0 , 0 , 0 , 0 ,0 ,0];
var slave_exists = false;
serialPort.on('open',function onSerialOpen(){
console.log("opened");
serialPort.on('data', function listenToSlaves(data){
i--;
if(data.search("END" + slaves[i]) ==0){
console.log("ENDED");
slave_exists = true;
counter[i]=0;
}
else{
// if(data!="END" + slaves[i]){
if(data.search("END" + slaves[i])!==0){
deli = data.indexOf(":");
var parameter = data.substring(0, deli);
var value = data.substring(deli +1);
console.log("parameter is: " + parameter + " - Value is: " + value);
}
}
if(slave_exists){
counter[i] =0;
}
i++;
});
writeToSlaves();
});
function writeToSlaves(){
//If the previous slave (the slave before the one I am sending to
//in the next step doesnt exist, add the counter or consideer
//it not existing)
if(!slave_exists){
counter[i-1]+=1;
if(counter[i-1]>=countTry){
console.log("--------counter[" + i + "]: " + counter[i]);
// in case that the slave returned no data after trying
//to send him several times
console.log(slaves[i-1] + " doesn't exist");
}
}
//sending to the following slave
b.digitalWrite("P9_17", b.HIGH);
serialPort.write(slaves[i], function(){ slave_exists = false;});
b.digitalWrite("P9_17", b.LOW);
console.log("I wrote to slave: " + i);
if(i<slaves.length - 1) i++;
else i=0;
setTimeout(writeToSlaves, waiting_interval);
}
but I am always facing this error:events.js:72
throw er; // Unhandled 'error' event
^
Error: Cannot open /dev/ttyO2
I am running another file first (the code down), the I try to rerun the previous code, and it runs perfect. I need to do that whenever I want to run the first code!
The code that runs from the first time is here:
( I tried the following code alone, it writes to the serial port but doesnt recieve, no event at recieption):
var b = require('bonescript');
var rxport = '/dev/ttyO2';
var txport = '/dev/ttyO2';
var options = { baudrate: 115200, parity: 'even', parser: b.serialParsers.readline('\n') };
var teststring = "This is the string I'm sending out as a test";
b.serialOpen(rxport, options, onRxSerial);
function onRxSerial(x) {
console.log('rx.eventrx= ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
//readReapeatedly();
b.serialOpen(txport, options, onTxSerial);
}
if(x.event == 'data') {
console.log("I am receiving on rxport");
console.log('rx (' + x.data.length +
') = ' + x.data.toString('ascii'));
}
}
function onTxSerial(x) {
console.log('tx.event = ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
writeRepeatedly();
}
if(x.event == 'data') {
// console.log('tx (' + x.data.length +
// ') = ' + x.data.toString('ascii'));
console.log(x.data);
}
}
function printJSON(x) {
console.log(JSON.stringify(x));
}
function writeRepeatedly() {
console.log("write to serial");
b.serialWrite(txport, teststring, onSerialWrite);
console.log("I have sent data");
}
function onSerialWrite(x) {
console.log("Iam in the onSerialWrite function");
if(x.err) console.log('onSerialWrite err = ' + x.err);
if(x.event == 'callback') {setTimeout(writeRepeatedly, 5000);
console.log("HERE");
}
}
The problem was solved.
In /boot/uboot/uEnv.txt, Update the line:"#cape_enable=capemgr.enable_partno= " to be:
"cape_enable=capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4, BB-UART5 "
or add the last line to the mentioned file. In some cases, you need to try this line instead of the mentioned:
"optargs=capemgr.enable_partno=BB-UART1,BB-UART2,BB-UART4, BB-UART5" (this is my case - but it disabled the HDMI interface of my BBB).
You can specify the UART you want to enable.
A helpful webpage is here.