DISCORD.JS own.map is not a function - node.js

Heyy, I want to make an owner command with embed, my script is simple to understand but I have an error with the description the embed, I don't know why, there is my code:
let own = await db.get(`${process.env.owner}.owner`)
let ownc = await db.get(`${process.env.owner}.ownercount`)
if(ownc === null|| "Nan" )ownc=1
let p0 = 0;
let p1 = 30;
let page = 1;
let embed = new Discord.MessageEmbed()
embed.setTitle("Owner")
.setColor(color)
.setDescription(!own ? "None":own.map((user, i) => `[${i}] <#${user}>`).slice(0, 30).join("\n")
)
.setFooter(`${page}/${Math.ceil(ownc||1/ 30)} • ${footer}`)
message.channel.send(embed)
Version of discord.js: 12.5.3
Module for db: #turph/quickmongo
Database: MongoDB

Related

How can I take multiple words as one argument in Discord.Js

I want to make a command like !ban <mentioned_user> <reason>.
But I tried many ways to do but nothing suits for my code, I want to get the reason string as args[1].
I used this code to fetch all arguments and to store all argument in args variable...
let messageArray = message.content.split(" ");
let command = messageArray[0].toLowerCase();
let args = messageArray.slice(1);
Try something like that
const argument = msg.content.trim().split(/ +/g);
const comand = argument.shift().toLowerCase();
if(comand === `${prefix}ban`) {
const user = argument[0];
const reason = argument.slice(1).join(' ');
// ban user
}
If I understand well, message.content contains "<mentioned_user> <reason>"
If I'm correct, you can get each in a variable and then do what you want with it
const [mentionedUser, ...arrRreason] = message.content.split(" ");
const reason = arrReason.join(' ');
// or
const reason = message.content.substring(message.content.indexOf(' ') + 1);

Quickdb add Is not a function error with Quick.db

Tried making a warning system by following a tutorial on youtube, guess it was outdated because I get this error
UnhandledPromiseRejectionWarning: TypeError: db.add is not a function
Here is how the code works.
const db = require('quickdb')
const member = message.member
const user = message.mentions.members.first()
const reason = args.slice(1).join(" ")
if (reason) {
let embed = new Discord.MessageEmbed()
.setTitle('Warning')
.setColor('GREEN')
.setDescription(`${user.user.username} Was Warned For ${reason} By ${member.user.username}`)
.setFooter(`Bot by Yaay#6969`);
user.send(`You have been warned in **${message.guild.name}** for ${reason} By ${member.user.username}`)
db.add('userInfo.warningsnumber', 1)
db.push('userInfo.warnings', `${reason}`)
db.get('userInfo.warningsnumber')
db.get('userInfo.warnings')
message.channel.send(embed)
}
try to require it like this
const db = require('quick.db');
I think you have a typo here
const db = require('quickdb') //TYPO it's quick.db not quickdb

How to push the file to TFS using azure-devops-node-api library in NodeJS?

I'm trying to push the files to repository in Azure Repos. I'm using azure-devops-node-api library to connect and push the file to the repository. I'm beginner in NodeJS. Please find the below code. I'm not sure how to proceed further.
Please help!
const orgUrl = "https://dev.azure.com/orgname";
const azure = require('azure-devops-node-api');
var accessToken = "ACCESS_TOKEN";
var authHandler = azure.getPersonalAccessTokenHandler(accessToken);
var connection = new azure.WebApi(orgUrl, authHandler);
connection.getGitApi().then( gitapi1 => {
// I don't know how to use gitapi1 to commit and push the file
});
How to push the file to TFS using azure-devops-node-api library in NodeJS?
To push the files to repository in Azure Repos, we could use the git.createPush to push the code to the repository in Azure Repos. To use the git.createPush, we need to get the repostoryId. You can check below sample demo for some more details:
import * as azdev from "azure-devops-node-api";
import * as gitclient from "azure-devops-node-api/GitApi"
//import { GitRepository } from 'azure-devops-node-api/interfaces/TfvcInterfaces';
import { GitRepository, GitPush,GitCommitRef,GitCommit, GitChange, ItemContent, GitItem, GitRefUpdate } from 'azure-devops-node-api/interfaces/GitInterfaces';
let orgUrl = 'https://dev.azure.com/yourorg'
let repostories:GitRepository[];
let token: string = "PATTokne";//patToken
let project:string = 'projectName'
let repostoryName = 'repostoryName';
let authHandler = azdev.getPersonalAccessTokenHandler(token);
let connection = new azdev.WebApi(orgUrl, authHandler);
let file:string = 'C:\\Users\\xxx\\typescript-node\\test.png';
let refName:string = 'refs/heads/master';
var fs = require('fs');
var base64str = base64_encode(file);
console.log(base64str);
// function to encode file data to base64 encoded string
function base64_encode(filePath:string) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
async function run(filePath:string,refName:string,project:string,repostoryName:string)
{
let git:gitclient.IGitApi = await connection.getGitApi();
repostories = await git.getRepositories(project);
let gitrepo = repostories.find(element => element.name === repostoryName);
let repostoryId = gitrepo?.id;
let gitChanges:GitChange[] = [<GitChange>{
changeType:1,
newContent:<ItemContent>{content:base64str,contentType:1 }, //0-> RawText = 0, Base64Encoded = 1,
item:<GitItem>{
path:'/testUpdate.png'
}
}];
if(typeof(repostoryId) ==="string")
{
let ref = (await git.getRefs(repostoryId,project)).find(element => element.name === refName)
let refUpdates:GitRefUpdate[] = [<GitRefUpdate> {
name:ref?.name,
oldObjectId:ref?.objectId //get ref->object id
}];
let gitCommitRef:GitCommitRef[] = [
<GitCommitRef>{
changes:gitChanges,
comment:'Add a file'
}
]
let gitPush:GitPush = <GitPush>{
commits:gitCommitRef,
refUpdates:refUpdates,
repository:gitrepo
};
console.log(repostoryId)
await git.createPush(gitPush,repostoryId,project);
}
}
run(file,refName,project,repostoryName);
console.log("test");
Hope this helps.

Passed function is not well-serializable

I am using Puppeteer to scrape the web from a file template that contains the data of an order.
For this, I am using a puppeteer evaluation function, which works correctly while the file is in .js
However, when the "pkg" package is used to compile the .exe file or evaluate to execute and initiate a return or error: "The passed function is not quite serializable!"
Below is the code:
const dados = {name: 'foo', year: 1}
await page.evaluate(dados => {
let dom = document.querySelector('body');
const tags = Object.keys(dados);
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
dom.innerHTML = dom.innerHTML.split(`{{${tag}}}`).join(dados[tag]);
}
}, dados);
I try to add --public argument with pkg.
Like: pkg start.js -t node14-win-x64 --public
Then I can freely use ElementHandle.evaluate( (elem)=> elem.textContent );
With the manual of pkg, the --public means that : speed up and disclose the sources of top-level project.
BTW
To fixup cannot find chrome binary file
browser = await puppeteer.launch({
executablePath: "node_modules/puppeteer/.local-chromium/win64-782078/chrome-win/chrome.exe"
});
(The path above can set anywhere as you like.)
To fixup start.exe cannot run
Sometime the output binary exe cannot executable. It
always popup a new cmd prompt window when we enter start.exe. (or just double click.)
Just delete the output exe then rerun pkg
Check the code whether is runnable with node start.js or not
The easiest solution for me is to wrap it with eval() :
async getText(selector: string) {
await this.page.waitForSelector(selector);
let text = await eval(`this.page.$eval('${selector}', el => el.textContent)`)
return text;
}
or this:
await eval(`this.page.evaluate(
(selector) => { (document.querySelector(selector).value = ''); },
selector);`);
I had this exact issue relating to puppeteer and pkg. For some reason pkg doesn't correctly interpret the contents of the callback. The solution that worked for me was to pass a string to evaluate rather than a function:
Change:
const dados = {name: 'foo', year: 1}
await page.evaluate(dados => {
let dom = document.querySelector('body');
const tags = Object.keys(dados);
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
dom.innerHTML = dom.innerHTML.split(`{{${tag}}}`).join(dados[tag]);
}
}, dados);
to
await page.evaluate(`
(() => {
const dados = {name: 'foo', year: 1};
let dom = document.querySelector('body');
const tags = Object.keys(dados);
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
dom.innerHTML = dom.innerHTML.split(`{{${tag}}}`).join(dados[tag]);
}
// return dom to do something with the data in node
return dom.innerHTML
})()`);
This answer on github suggests an alternative solution - using the pkg api to inject the callback at compile time, however it didn't work for me.

How to pass a variable from one module to another?

I know there may be a duplicate question but I've been reading and really struggling to understand and figure out how to pass a variable from a command module into an event module shown below.
Command:
exports.run = async (client, message, args) => {
const embed = new Discord.RichEmbed()
.addField(':heart:', `${xb.toString()}`, true)
.addField(':black_heart:', `${ps.toString()}`, true)
.addField(':yellow_heart:', `${nin.toString()}`, true)
.addField(':purple_heart:', `${pcmr.toString()}`, true)
message.channel.send(embed).then(async msg => {
let embedid = msg.id;
module.exports.embedid = embedid;
await msg.react('❤');
await msg.react('🖤');
await msg.react('💛');
await msg.react('💜');
});
}
Event:
module.exports = async (client, messageReaction, user) => {
const message = messageReaction.message;
const channel = message.guild.channels.find(c => c.name === 'role-assignment');
const member = message.guild.members.get(user.id);
if(member.user.bot) return;
const xb = message.guild.roles.get('540281375106924555');
const ps = message.guild.roles.get('540296583632388115');
const nin = message.guild.roles.get('540296630260203520');
const pcmr = message.guild.roles.get('540296669733060618');
if(['❤', '🖤', '💛', '💜'].includes(messageReaction.emoji.name) && message.channel.id === channel.id && messageReaction.message.id === embedid) {};
I'm hoping to pass embedid, embed2id and so on to the event module so I can filter by the message ID that is generated when sending the RichEmbed()
Thanks in advance, I've been running in circles for days!
So I figured it out by looking into what exports actually do, which really, should have been the first thing I did, here :
What is the purpose of Node.js module.exports and how do you use it?
Using the info learned here, I made the following changes to my event:
const e1 = require('../commands/startroles'); // At the top of my messageReactionAdd.js file before module.exports[...]
messageReaction.message.id === e1.embedid // added the e1. to import the variable.

Resources