I am trying to get the message ID of a newly created message like this.
What would I use instead of message.channel.fetch(id) to fetch a message id? I can't seem to find it:
async function messageSend() {
let messageId = await message.channel.send('Test');
let { id } = messageId;
const emojiCheck = '✅';
const emojiNo = '❌';
const nebzlaID = '569860318608490496';
message.channel.messages.fetch(id).react(emojiCheck);
message.channel.messages.fetch(id).react(emojiNo);
const suggestionDM = new Discord.MessageEmbed()
.setColor('#fffff')
.setTitle('There is a new suggestion in abc!').setDescription(`
User: ${suggestUser}
\n\nSuggestion: ${suggestion}
`);
// ...
channel.messages.fetch() returns a promise, it means you need to resolve it first to get the message you can react to. You can use await:
async function messageSend() {
const { id } = await message.channel.send('Test');
const emojiCheck = '✅';
const emojiNo = '❌';
const nebzlaID = '569860318608490496';
const messageToReact = await message.channel.messages.fetch(id);
messageToReact.react(emojiCheck);
messageToReact.react(emojiNo);
// ...
Although it's not necessary to fetch it again, you could simply react to the returned message:
async function messageSend() {
const sentMessage = await message.channel.send('Test');
const emojiCheck = '✅';
const emojiNo = '❌';
const nebzlaID = '569860318608490496';
sendMessage.react(emojiCheck);
sendMessage.react(emojiNo);
// ...
Related
In React Native I want to store object array data with a unique id each time I type in the textbox. I'm using async storage but don't know how to handle that.
You could implement something like this
First run
npm i #react-native-async-storage/async-storage
And then create a AsyncStore.js or similar file:
import AsyncStorage from '#react-native-async-storage/async-storage';
export const storeObject = async (object) => {
const id = await createId()
const identified = {...object, id }
const jsonValue = JSON.stringify(identified);
await AsyncStorage.setItem('#object-' + id, jsonValue);
};
export const getObject = async (id) => {
const storedObject = await AsyncStorage.getItem('#object-' + id);
if (storedObject){
return JSON.parse(storedObject );
}
};
export const storeIds = async (ids) => {
const jsonValue = JSON.stringify(ids);
await AsyncStorage.setItem('#object-ids', jsonValue);
};
export const getIds = async (id, ids) => {
const storedIds = await AsyncStorage.getItem('#object-ids');
if (storedIds) {
return JSON.parse(storedIds );
}
};
const createId = async() => {
const ids = await getIds();
const id = Math.max(ids) + 1
await storeIds([...ids,id])
return id;
}
Edit: I added some untested unique identifier code
I tried it without the timeout, without transfering the steamID into a string (both "Cannot send an empty message")an some more. But I haven't gotten any further for like 30 minutes.
(vanityURL = input)
My Function(The API is completly working):
const fetch = require("node-fetch");
const botconfig = require("../botconfig.json")
async function getSteamID(vanityURL) {
const response = await fetch(`https://api.steampowered.com/ISteamUser/ResolveVanityURL/v1/?key=${botconfig.steamapikey}&vanityurl=${vanityURL}`);
const data = await response.json();
const listDataRaw = JSON.stringify(data);
const listData = listDataRaw.toString();
var steamID = listData.replace(/{"response":{"steamid":"|","success":1}}/g, "") // Filter
console.log(steamID)
return steamID;
}
module.exports = { getSteamID }
My test command:
const getSteamInfo = require('../functions/getSteamInfo');
module.exports.run = async (bot, message, args) => {
var vanityURL = args.join(' ')
const rawSteamID = getSteamInfo.getSteamID(vanityURL);
await new Promise(r => setTimeout(r, 1000));
let steamID = rawSteamID.toString();
message.channel.send(steamID)
};
module.exports.command = {
name: `test`
}
Thanks for help!
You forgot to await your call to getSteamInfo.getSteamID.
(You also forgot to await the call to message.channel.send so right now any errors thrown by it would turn into an unhandled rejection.)
const getSteamInfo = require('../functions/getSteamInfo');
module.exports.run = async (bot, message, args) => {
const vanityURL = args.join(' ')
const rawSteamID = await getSteamInfo.getSteamID(vanityURL)
// ^^^^^
const steamID = rawSteamID.toString() // not sure this is even needed...?
await message.channel.send(steamID)
//^^^
}
module.exports.command = {
name: `test`
}
Just put "await"
const rawSteamID = await getSteamInfo.getSteamID(vanityURL);
and see it is working
Here's some code to join something from 3 object stores:
let db;
indexedDB.open('db', 1).onsuccess = ev => {
db = ev.target.result;
const tran = db.transaction(['s1', 's2', 's3']);
tran.objectStore('s1').get('third').onsuccess = ev1 =>
tran.objectStore('s2').index('connectTo').get('third').onsuccess = ev2 =>
tran.objectStore('s3').index('connectTo').get('third').onsuccess = ev3 => {
const [res1, res2, res3] = [ev1.target.result, ev2.target.result, ev3.target.result];
const result = {...res1, ...res2, ...res3};
......
}
}
Can I use promises or other means like async/await to avoid the heavy nesting? It'd be good if I can put these query processes in a function and get the result object as the return value.
Something like this should work.
const someFunction = async () => {
let db
const openDB = await indexedDB.open('db', 1)
db = openDB.target.result
const tran = db.transaction(['s1', 's2', 's3'])
const ev1 = await tran.objectStore('s1').get('third')
const ev2 = await tran.objectStore('s2').index('connectTo').get('third')
const ev3 = await tran.objectStore('s3').index('connectTo').get('third')
const [res1, res2, res3] = [
ev1.target.result,
ev2.target.result,
ev3.target.result,
]
const result = { ...res1, ...res2, ...res3 }
}
someFunction()
Personally I would store the results like this and eliminate the need for copies (if possible for you).
const result = { ...ev1.target.result, ...ev2.target.result, ...ev3.target.result }
I'm trying to read the dom content from indian superleague for example goals, attacking, mins per goal, etc using class and object. It gives an error like this
Evaluation failed: TypeError: Cannot read property 'textContent' of undefined
at puppeteer_evaluation_script:7:64
Here's the code
config.js
const puppeteer = require('puppeteer')
class Puppeteer{
constructor(){
this.param = {
path: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
url: 'https://indiansuperleague.com',
}
}
async connect(){
this.param.browser = await puppeteer.launch({executablePath: this.param.path, headless: false})
this.param.page = await this.param.browser.newPage()
await this.param.page.goto(this.param.url, {timeout: 0})
}
async disconnect(){
await this.param.browser.close()
}
}
module.exports = Puppeteer
states.js
class States{
constructor(param){
this.param = param
}
async fetchData(){
const page = this.param.page
const res = await page.evaluate(() => {
const title = 'si-fkt-sctn-title', value = 'si-fkt-sctn-number'
// const titleArray = document.getElementsByClassName(title)
// const valueArray = document.getElementsByClassName(value)
let key = document.getElementsByClassName(title)[0].textContent.trim()
let num = document.getElementsByClassName(value)[0].textContent.trim()
/* for(let i=0; i<titleArray.length; i++){
key[i] = titleArray[i].textContent.trim()
num[i] = valueArray[i].textContent.trim()
// Object.defineProperty(temp, key, {value:num,writable: true,configurable: true,enumerable: true})
} */
return {key, num}
})
console.log(res)
}
}
module.exports = States
app.js
const Puppeteer = require('./config')
const States = require('./modules/states')
const puppeteer = new Puppeteer()
const states = new States(puppeteer.param)
puppeteer.connect().then(async() => {
let res = await states.fetchData()
console.log(res)
await puppeteer.disconnect()
}).catch(e => console.log(e))
What is the solution?
The elements may be created dynamically after some time. You can try to use page.waitForSelector() before retrieving the data from them. For example:
'use strict';
const puppeteer = require('puppeteer');
(async function main() {
try {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.goto('https://indiansuperleague.com');
await Promise.all([
page.waitForSelector('.si-fkt-sctn-title'),
page.waitForSelector('.si-fkt-sctn-number'),
]);
const data = await page.evaluate(() => {
return [
document.querySelector('.si-fkt-sctn-title').textContent,
document.querySelector('.si-fkt-sctn-number').textContent,
];
});
console.log(data);
await browser.close();
} catch (err) {
console.error(err);
}
})();
Output:
[ ' Goals', ' 63' ]
I need some help returning a promise. I don't get why I am not getting the players value
The code
const playerSelectName = document.getElementById('sel1');
const playerSelectPosition = document.getElementById('sel2');
const playerSelectAge = document.getElementById('sel3');
const searchButton = document.getElementById('search-btn');
async function getPlayers() {
const response = await fetch('https://football-players-b31f2.firebaseio.com/players.json?print=pretty');
const playersObject = await response.json();
return playersObject;
}
searchButton.addEventListener('click', async () => {
const players = await getPlayers();
let [ name, position, age ] = [ playerSelectName.value, playerSelectPosition.value, playerSelectAge.value ];
yersObject.filter((playerAge) => {});
});
I cant get to access the code inside my listener function of the value players
the problem was in destructuring check the below snippet. I hope this will solve the issue . Also please update what you are trying to achieve in filter so i can add on the solution.
I didnt understood what are you trying to do in destructure part and after that filter
async function getPlayers() {
const response = await fetch('https://football-players-b31f2.firebaseio.com/players.json?print=pretty');
const playersObject = await response.json();
return playersObject;
}
const searchButton = document.getElementById('search-btn');
searchButton.addEventListener('click', async () => {
const players = await getPlayers();
players.forEach(player => {
const {name, nationality, position} = player
console.log(name, nationality, position)
})
});
<button id='search-btn'>
Load Results
</button>
Here's a simple example accessing the players to help get you started.
async function getPlayers() {
const response = await fetch('https://football-players-b31f2.firebaseio.com/players.json?print=pretty');
return response.json();
}
(async () => {
const players = await getPlayers();
console.log(players)
})();