Ledger nano S interraction error: Ledger device: Incorrect length (0x6700) - web3js

const LedgerWalletProvider = require('#ledgerhq/web3-subprovider');
const createLedgerSubprovider = LedgerWalletProvider.default;
const TransportNodeHid = require('#ledgerhq/hw-transport-node-hid');
const ProviderEngine = require('web3-provider-engine');
const RpcSubprovider = require('web3-provider-engine/subproviders/rpc');
const Web3 = require('web3');
const engine = new ProviderEngine();
const getTransport = () => TransportNodeHid.default.create();
const ledger = createLedgerSubprovider(getTransport, { networkId: 3 });
engine.addProvider(ledger);
engine.addProvider(new RpcSubprovider({ rpcUrl: 'https://ropsten.infura.io/v3' + infuraKey }));
engine.start();
const web3 = new Web3(engine);
web3.eth.getAccounts((err, res) => {
console.log(err.message); // Ledger device: Incorrect length (0x6700)
});
I want to create a node app with Ledger Nano S to keep my keys and sign transaction.
This is my code ^, but I get the following error
Ledger device: Incorrect length (0x6700)

Related

how to check if nested docs and collection in firebase exist and if don't how to create, in react native

I am new to Firebase and I have to create a chat system. I found that the doc structure should be nested
e.g if a person sends a message, a new doc with its id will be created in the main collection and then a new collection will be added to the doc. now each doc in that nested collection will be considered as a message obj.
a rough sketch of how the new message in the nested document will be added
but the problem is when there is no doc with UI exist or no collection in that doc exist
firestore().collection("chatBox").doc(uid).collection("message").add(
{
text: "this is my first message",
user: {_id:356},
avatar: "link of avatar",
name: "john",
createdAt: new Date().getTime()
}
)
const sendMessage = async (messages = []) => {
const msg = messages[0];
const id = msg.user?._id?.toString();
const collectionRef = firestore().collection(CHATBOX);
const doc = collectionRef.doc(id);
const docExists = await doc.get().then(function (doc) {
return doc.exists;
});
if (docExists) {
const collection = doc.collection(MESSAGES);
const isCollectionEmpty = collection.get().then(col => {
return col.empty;
});
if (isCollectionEmpty) doc.set({id: MESSAGES});//creating new collection
else collection.add({...msg, createdAt: new Date().getTime()});//inserting doc if collection exist
} else {
collectionRef.add(id);// creating doc in main collection
}
};
The ability to create a document only if it does not exist can be done using the following Transaction. Here, the createDocIfNotExist method creates the document with the given data, only if it does not already exist. It returns a Promise<boolean> indicating whether the document was freshly created or not.
async createDocIfNotExist(docRef, initData) {
return docRef
.firestore
.runTransaction((transaction) => {
const docSnap = await transaction.get(docRef);
if (docSnap.exists)
return false; // exists already
transaction.set(docRef, initData);
return true; // was created
});
}
Applying this to your code then gives:
const sendMessage = async (messages = []) => {
const msg = messages[0];
const msgUserId = msg.user!._id!.toString(); // id renamed, consider using senderId/recipientId instead
const chatboxColRef = firestore().collection(CHATBOX); // collectionRef renamed
const userChatboxDocRef = chatboxColRef.doc(msgUserId); // doc renamed
const isNewChatbox = await createDocIfNotExist(
userChatboxDocRef,
{ id: msgUserId }
);
const userChatboxMessagesColRef = userChatboxDocRef.collection(MESSAGES); // collection renamed
return userChatboxMessagesColRef
.add({
...msg,
createdAt: new Date().getTime() // consider using firebase.firestore.FieldValue.serverTimestamp() instead
});
};
This can be further reduced to:
const sendMessage = async (messages = []) => {
const msg = messages[0];
const msgUserId = msg.user!._id!.toString();
const userChatboxDocRef = firestore()
.collection(CHATBOX);
.doc(msgUserId);
await createDocIfNotExist(
userChatboxDocRef,
{ id: msgUserId }
);
return userChatboxDocRef
.collection(MESSAGES)
.add({
...msg,
createdAt: new Date().getTime()
});
};
Note: Avoid using the variable name doc as it is ambiguous and could be an instance of DocumentData, DocumentReference, or DocumentSnapshot (at minimum, use docData, docRef and docSnap/docSnapshot respectively). Similarly, use colRef for a CollectionReference and qSnap/querySnap for QuerySnapshot objects.

How can I change the order of dates in my table column?

Each row goes into the array correctly. There are dates between A13-A28 in my spreadsheet, but it may not always be between A13 and A28. Can I sort them as I want?
I extracted the regex if there is only the date line in the column. Is there a more practical way to both filter and sort?
const [columns, setColumns] = useState([]);
const handFile = async (e) => {
const file = e.target.files[0];
const fileReader = new FileReader()
setFileName(file.name)
const data = await file.arrayBuffer();
const workbook = XLSX.readFile(data);
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonData = XLSX.utils.sheet_to_json(worksheet, {
header: 1,
defval: "",
blankrows: false, //boş satırları göstermez
});
fileReader.onerror = ((error) => {
console.dir(error, { depth: null })
});
setexcData(jsonData);
}

TypeError [CLIENT_MISSING_INTENTS]

Today I tried to start my bot but I got this error :
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
And this is my code:
const Discord = require('discord.js'),
client = new Discord.Client(),
nodeHtmlToImage = require('node-html-to-image'),
config = require('./config.json'),
puppeteer = require('puppeteer'),
express = require('express'),
app = express()
var mime = require('mime'),
fs = require('fs'),
path = require('path')
const port = 3e3
async function nitrogenerator(e, t) {
let a = formatAMPM(new Date())
let n = formatAMPM(new Date(Date.now() - 6e4)),
o = await fs.readFileSync(`${__dirname}/testingboost.html`, 'utf8')
;(datatosend = o),
(datatosend = datatosend.replace(
'FIRSTAUTHORURL',
e.author.displayAvatarURL()
)),
(datatosend = datatosend.replace('THEFIRSTAUTHOR', e.author.username)),
(datatosend = datatosend.replace(
'SECONDAUTHORURL',
client.users.cache.random().displayAvatarURL()
)),
(datatosend = datatosend.replace('THESECONDAUTHOR', t.shift())),
(datatosend = datatosend.replace('RESPONSETONITRO', t.join(' '))),
(datatosend = datatosend.replace('FIRSTAUTHORDATE', 'Today at ' + n)),
(datatosend = datatosend.replace('SECONDAUTHORDATE', 'Today at ' + a)),
app.get('/font', function (e, t) {
const a = `${__dirname}/Whitneyfont.woff`
t.sendFile(a)
}),
app.get('/', function (e, t) {
t.send(datatosend)
})
let r = app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
const s = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
}),
i = await s.newPage()
await i.goto(`http://localhost:${port}`),
await i.waitForSelector('.scrollerInner-2YIMLh')
const d = await i.$('.scrollerInner-2YIMLh')
let c = await d.screenshot({ type: 'png' })
await s.close()
const l = new Discord.MessageAttachment(c, 'NitroProof.png')
e.channel.send(`${e.author}`, l), r.close()
}
function formatAMPM(e) {
var t = e.getHours(),
a = e.getMinutes(),
n = t >= 12 ? 'PM' : 'AM'
return (t = (t %= 12) || 12) + ':' + (a = a < 10 ? '0' + a : a) + ' ' + n
}
client.on('ready', () => {
function randomStatus() {
let status = ['ShadowWLX#0001', 'Hehe Boy'] // You can change it whatever you want.
let rstatus = Math.floor(Math.random() * status.length)
// client.user.setActivity(status[rstatus], {type: "WATCHING"});
// You can change the "WATCHING" into STREAMING, LISTENING, and PLAYING.
// Example: streaming
client.user.setActivity(status[rstatus], {
type: 'LISTENING',
url: 'https://discord.gg/MZUHeefXqx',
})
}
setInterval(randomStatus, 5000) // Time in ms. 30000ms = 30 seconds. Min: 20 seconds, to avoid ratelimit.
console.log('Online.')
})
client.on('message', async (e) => {
if ('dm' === e.channel.type) return
if (e.author.bot) return
if (0 !== e.content.indexOf(config.prefix)) return
const t = e.content.slice(config.prefix.length).trim().split(/ +/g)
'boost' === t.shift().toLowerCase() && (await nitrogenerator(e, t))
}),
client.login(config.token)
I know I need to add intents but I don't know how and what intents to add. I think I need to add the GUILD_PRESENCE intent but I don't know how to add it.
You can add intents to the Client like this-
const client = new Discord.Client({
intents: ["GUILD"] //If you want to add all intents just type 32767 instead of array
})
You must add intents in main.js, where you initialize bot.
const myIntents = new Intents();
myIntents.add(Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MEMBERS);
const client = new Client({ intents: myIntents });
List of all intents
GUILDS
GUILD_MEMBERS
GUILD_BANS
GUILD_EMOJIS_AND_STICKERS
GUILD_INTEGRATIONS
GUILD_WEBHOOKS
GUILD_INVITES
GUILD_VOICE_STATES
GUILD_PRESENCES
GUILD_MESSAGES
GUILD_MESSAGE_REACTIONS
GUILD_MESSAGE_TYPING
DIRECT_MESSAGES
DIRECT_MESSAGE_REACTIONS
DIRECT_MESSAGE_TYPING
GUILD_SCHEDULED_EVENTS

How to update servercount automatically after bot is added to a server

I'm having some trouble with automating my bots servercount in its status whenever it gets added to a server, but the member count updates as expected, the server count is the one that is not updating (I have to restart my bot to get it to update the server count).
ready.js
const client = require("../index");
const config = require("../botconfig");
const chalk = require('chalk');
client.on("ready", () => {
client.logger.log("READY", `${client.user.tag} has logged in!`)
const arrayOfStatus = [
{ name: `version ${config.version} | ${config.defaultPrefix}help`, type: 'PLAYING'},
{ name: `${client.guilds.cache.size} servers`, type: 'WATCHING'},
{ name: `${client.users.cache.size} users`, type: 'WATCHING'}
];
let index = 0;
setInterval(() => {
if (index === arrayOfStatus.length) index = 0;
const status = arrayOfStatus[index];
client.user.setActivity(status);
index++;
}, 5000);
const clientDetails = {
guilds: client.guilds.cache.size,
users: client.users.cache.size,
};
});

Want a code that detects custom status and gives the person a role on discord

I am trying to make a code that searches a custom status for the phrase ".gg/RoundTable" and will then give the person a certain role I have in my server.
Here is my code so far , the code runs with no errors but it will not assign the role.
const Discord = require("discord.js")
const client = new Discord.Client()
const mySecret = process.env['TOKEN']
client.login(mySecret)
const roleID = 865801753462702090
client.on('presenceUpdate', async (oldPresence, newPresence) => {
const role = newPresence.guild.roles.cache.find(role => role.name === 'Pic Perms (.gg/RoundTable)');
const status = ".gg/RoundTable"
const member = newPresence.member
console.log(member.user.presence.activities[0].state)
if(member.presence.activities[0].state.includes(status)){
return newPresence.member.roles.add(roleID)
} else {
if(member.roles.cache.has(roleID)) {
newPresence.member.roles.remove(roleID)
}
}
})
Try this:
const Discord = require("discord.js");
const client = new Discord.Client();
const roleID = "851563088314105867";
client.on("presenceUpdate", async (_, newPresence) => {
const role = newPresence.guild.roles.cache.get(roleID);
const status = ".gg/RoundTable";
const member = newPresence.member;
if (member.presence.activities[0].state?.includes(status)) {
return newPresence.member.roles.add(role);
} else {
if (member.roles.cache.has(role)) {
newPresence.member.roles.remove(role);
}
}
});
client.login("your-token");
I'd recommend finding your role in the RoleManager.cache using get() as you already have the roleID and then actually assign that role instead of the roleID. Note I added an optional chaining operator since if a user does not have a custom status .state will be null.

Resources