Setting Postman env variable based on the repsonse where certain criteria is met - arrays

When I get a response in Postman, I want to be able to set an environment variable (using
pm.environment.set("variable_key", "variable_value");
when a condition is met from the response array.
So the requirements:
set an environment variable named idForAbc to the value of someArray.id where someArray.criteria = "ABC" (so idForAbc = 1)
set an environment variable named idForXyz to the value of someArray.id where someArray.criteria = "XYZ" (so idForXyz = 2)
Here is my sample response:

You can choose one of 2 ways:
const res = pm.response.json();
const abc = res.someArray.find(e => e.criteria === "ABC");
if(abc){
pm.environment.set(`idFor${abc.criteria}`,abc.id)
}
const xyz = res.someArray.find(e => e.criteria === "XYZ");
if(xyz){
pm.environment.set(`idFor${xyz.criteria}`,xyz.id)
}
or
const res = pm.response.json();
function saveVarByCriteria(arr, value){
const obj = arr.find(e => e.criteria === value);
if(obj){
pm.environment.set(`idFor${obj.criteria}`, obj.id)
}
}
saveVarByCriteria(res.someArray, "ABC");
saveVarByCriteria(res.someArray, "XYZ");

Related

React-URLSearchParams returning Null object

I am using the following code to retrieve query parameters from URL but URLSearchParams returns an empty object.
PS: uselocation.search returning correct output.
const stringdata = useLocation().search
const queryparameter = new URLSearchParams(stringdata)
console.log("query parameter :", queryparameter)
const query = queryparameter.get('q');
var url_string = `http://localhost:3000/recipes${query}`
You can try using window.location.search over user search params.
That should look something like:
const queryParams = new URLSearchParams(window.location.search);
const query = queryParams.get('q');
let url_string = `http://localhost:3000/recipes${query}`;
The search property returns the querystring part of a URL, including the question mark (?).
const queryParams = new URLSearchParams(window.location.search);
Then you need to check if queryparameter.get('q') exists, otherwise it will return null and will append null to url.
let query;
if(queryParameter.has('q')){
query = queryparameter.get('q');
}
then
var url_string = `http://localhost:3000/recipes/${query}`

Loop script for all values of dropdown

I'm looking to make a script that cycles through a dropdown list and creates a pdf for each.
https://docs.google.com/spreadsheets/d/1HrXWkNXT7aEWOXkngiuSX9Sr1F0V4Y_rZH6Eg3mjaJQ/edit?usp=sharing
First I would like to check if B2 is not empty, then if so create pdf and change A2 to the next option until all are complete. I have a basic script but feel free to disregard!
function loopScript() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const interface = ss.getSheetByName("Interface");
var folderID = "###GOOGLE DRIVE FOLDER ID###";
var folder = DriveApp.getFolderById(folderID);
const exportOptions = 'exportFormat=pdf&format=pdf'
+ '&size=A4'
+ '&portrait=true'
+ '&scale=4'
+ '&fith=true&source=labnol'
+ '&top_margin=0.05'
+ '&bottom_margin=0.05'
+ '&left_margin=1.00'
+ '&right_margin=0.25'
+ '&sheetnames=false&printtitle=false'
+ '&pagenumbers=false&gridlines=false'
+ '&fzr=false'
+ '&gid=125740569';
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
const nameFile = "NAME OF FILE" + ".pdf" ;
folder.createFile(response.setName(nameFile));
DriveApp.createFile(response.setName(nameFile));
}
I believe your goal is as follows.
You want to check the cell "B2". When the cell "B2" is not empty, you want to set the value of the dropdown list of cell "A2" to the next value of the list.
For example, when the dropdown list is Joe, Barry, Jane, Fred and the cell "A2" is Barry, you want to set the cell to Jane.
In this case, how about the following modified script?
Modified script:
From:
const ss = SpreadsheetApp.getActiveSpreadsheet();
const interface = ss.getSheetByName("Interface");
To:
const ss = SpreadsheetApp.getActiveSpreadsheet();
const interface = ss.getSheetByName("Interface");
if (interface.getRange("B2").isBlank()) return;
const range = interface.getRange("A2");
const values = [...new Set(range.getDataValidation().getCriteriaValues()[0].getValues().flat())];
const nextValue = values[values.indexOf(range.getValue()) + 1] || values[0];
range.setValue(nextValue);
In this modified script, when the cell "B2" is empty, the script is finished. When the cell "B2" is not empty, the script is run and the cell "A2" is updated and your script for creating the PDF file is run.
Note:
In above modified script, when the dropdown list is Joe, Barry, Jane, Fred and the cell "A2" is Fred, the value of Joe is set. If you want to change this, please modify the above script.
In your current script, url is not defined. Please be careful this.
References:
isBlank()
getDataValidation()
getCriteriaValues()
Issue:
If I understand you correctly, you want to do the following:
For each dropdown in A2, check if the formula in B2 populates any values (based on data from sheet Data).
If any value is populated in B due to the formula, create a PDF file using the value of A2 for the file name (you have achieved this already).
Method 1:
In this case, I'd suggest the following workflow:
Retrieve an array with the accepted values from A2 dropdown (you can use the method used in Tanaike's answer).
Iterate through these values, and for each one, set the A2 value, using Range.setValue.
Call flush in order to update the data in B2 according to the current value in A2.
Check if B2 is blank (using Range.isBlank, for example).
If B2 is not blank, create the drive file.
function loopScript() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const interface = ss.getSheetByName("Interface");
const range = interface.getRange("A2");
const values = [...new Set(range.getDataValidation().getCriteriaValues()[0].getValues().flat())].filter(String);
values.forEach(name => {
range.setValue(name);
SpreadsheetApp.flush();
if (!interface.getRange("B2").isBlank()) {
// CODE FOR CREATING FILE
}
});
}
Method 2:
In the previous method, setValue, flush, getRange and isBlank are used iteratively, greatly increasing the amount of calls to the spreadsheet. This is not the best practice, as it will slow down the script (see Minimize calls to other services), and this will get worse if there are more valid options for the dropdown.
Therefore, since the data this formula is using can be found in sheet Data, I'd suggest using that source data instead of the formula, in order to minimize the calls to the spreadsheet.
In this case, you could follow this workflow:
Get all data in Data at once using Range.getValues.
Get all valid options in the data validation from A2, as in method 1.
For each option, check if there's any row in Data that has this option in column A and a non-empty cell in B.
If there is some data for that option, create the file.
function loopScript() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const interface = ss.getSheetByName("Interface");
const data = ss.getSheetByName("Data");
const DATA_FIRST_ROW = 2;
const dataValues = data.getRange(DATA_FIRST_ROW,1,data.getLastRow()-DATA_FIRST_ROW+1,2).getValues();
const range = interface.getRange("A2");
const values = [...new Set(range.getDataValidation().getCriteriaValues()[0].getValues().flat())].filter(String);
values.forEach(name => {
const optionValues = dataValues.filter(dataRow => dataRow[0] === name);
const nonEmpty = optionValues.some(optionValue => optionValue[1] !== "");
if (nonEmpty) {
// CODE FOR CREATING FILE
}
});
}
Thanks to everyone's help, I ended up using Tanaike's advice and continued on to come up with this:
function sendAll() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var interface = ss.getSheetByName("Interface");
var range = interface.getRange("A2");
// Cell of validation
const values = [...new Set(range.getDataValidation().getCriteriaValues()
[0].getValues().flat())]; // Gets array of validation
var first = values[0];
// 1st cell of validation
var number = values.length - 1;
// Length of validation
range.setValue(first);
// Sets value to first one
for(i = 0;i < number;i++) {
// Loop number of names
if (interface.getRange("B2").getValue().length > 0) {
// Sheet isn't empty
var person = interface.getRange("A2").getValue();
const url = 'MY SHEET URL';
var folderID = "MY FOLDER ID";
var folder = DriveApp.getFolderById(folderID);
const exportOptions = 'exportFormat=pdf&format=pdf'
+ '&size=A4'
+ '&portrait=true'
+ '&scale=4'
+ '&fith=true&source=labnol'
+ '&top_margin=0.05'
+ '&bottom_margin=0.05'
+ '&left_margin=1.00'
+ '&right_margin=0.25'
+ '&sheetnames=false&printtitle=false'
+ '&pagenumbers=false&gridlines=false'
+ '&fzr=false'
+ '&gid=0';
var params = {method:"GET",headers:{"authorization":"Bearer "+
ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
const nameFile = person + ".pdf" ;
folder.createFile(response.setName(nameFile));
DriveApp.createFile(response.setName(nameFile));
const nextValue = values[values.indexOf(range.getValue()) + 1] || values[0];
range.setValue(nextValue);
}
else {const nextValue = values[values.indexOf(range.getValue()) + 1] ||
values[0];
range.setValue(nextValue);}
}
}

discord.py number of bans in a server

I was wondering how I can show how many bans a server has. For example if a server has 5 bans, How can I show that the server has 5 bans.
#client.command()
#commands.cooldown(1,3,BucketType.channel)
async def serverinfo(ctx):
embed = discord.Embed(
color = discord.Color(0xff3400),
title = f"•{ctx.guild.name}•")
embed.add_field(name="**•Server Created At•**", value=f"{ctx.guild.created_at.date()}", inline = False)
embed.add_field(name="**✧Owner**", value=f"{ctx.guild.owner.mention}", inline = False)
embed.add_field(name="**•Member Count•**", value=f"{len(ctx.guild.members)}", inline = False)
embed.add_field(name = "**•Role Count•**", value = f"{len(ctx.guild.roles)}", inline = False)
embed.add_field(name = "**•Channel + Category Count•**", value = f"{len(ctx.guild.channels)}", inline = False)
embed.add_field(name = "**•Emoji Count•**", value = f"{len(ctx.guild.emojis)}", inline = False)
embed.add_field(name = "**•Bans•**", value = f"{ctx.guild.bans}", inline = False)
embed.set_thumbnail(url = f"{ctx.guild.icon_url}")
embed.set_footer(icon_url = f"{ctx.author.avatar_url}", text = f"Requested by {ctx.author}")
embed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=embed)
You can use len() on the guild's bans
len(await ctx.guild.bans())

TypeError: Cannot read property 'send' of undefined discord.js v12

i have this reaction role system everything works up to the last part where the coulour slection happens
async run(message, client, con) {
await message.channel.send("Give the color for the embed.")
answer = await message.channel.awaitMessages(answer => answer.author.id === message.author.id,{max: 1});
var color = (answer.map(answers => answers.content).join()).toUpperCase()
if(color.toUpperCase()==='CANCEL') return (message.channel.send("The Process Has Been Cancelled!"))
function embstr(){
var finalString = '';
for(var i =0;i<n;i++){
finalString += b[i]+ ' - '+a[i] +'\n';
}
return finalString;
}
const botmsg = message.client.channels.cache.get(channel => channel.id === reactChannel)
const embed = new MessageEmbed()
.setTitle(embtitle)
.setColor(color)
.setDescription(embstr());
botmsg.send(embed);
message.channel.send("Reaction Role has been created successfully")
here is the error message
{
"stack": "TypeError: Cannot read property 'send' of undefined
at SlowmodeCommand.run (B:\\stuff\\Downloads\\Admeeeeeen bot\\src\\commands\\reactionroles\\createreactionrole.js:100:22)
at processTicksAndRejections (node:internal/process/task_queues:93:5)"
}
The .get() method takes in a snowflake as its parameter. AKA an ID of a certain object. It is not an iterator, meaning that what you're currently attempting to do is not right JavaScript wise.
Instead of passing in a parameter to represent a channel object, we'll just want to pass in the ID of the channel that we'd like to get. Alternatively, you could replace .get() with .find() there, which is in fact an iterator that uses this form of a callback, although it's insufficient in our case considering we can just use .get() which is more accurate when it comes to IDs.
/**
* Insufficient code:
* const botmsg = message.client.channels.cache.find(channel => channel.id === reactChannel)
*/
const botmsg = message.client.channels.cache.get(reactChannel /* assuming that reactChannel represents a channel ID */)

How to make this bot listen to argument after prefix and answer?

so i'm trying this 8ball bot, and everything is working fine, but i can't get how can i leave in the condition that only when the bot get "!verda arg1 arg2" it answers one of the replies in the array.
meanwhile my condition is if the user type the prefix "!verda" only, it replies , i want to include the argument too in the condition
const Discord = require("discord.js");
const client = new Discord.Client();
const cfg = require("./config.json");
const prefix = cfg.prefix;
client.on("message", msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase;
if (msg.content === prefix){
let replies = [
"Yes.",
"No.",
"I don't know.",
"Maybe."
];
let result = Math.floor((Math.random() * replies.length));
msg.channel.send(replies[result]);
}
else if (msg.content === "!help"){
msg.channel.send("I have only 1 command [!verda]");
}
})
client.login(cfg.token);
const command = args.shift().toLowerCase;
toLowerCase is a function and therefore should be
const command = args.shift().toLowerCase();
By doing msg.content === prefix, you are checking if the whole content of the message is equal to that of cfg.prefix
if(msg.content.startsWith(`${prefix}8ball`) {
}
The answer was simple as i figured it out, i simply had to join the spaces
if (msg.content === `${prefix} ${args.join(" ")}`)

Resources