what's the issue with this command? im trying to select randomly an user who sent a message in a specific channel - random

**so yeah basically this is the entire code and when it doesn't work
**
client.on("message", async message => {
if (message.content === "!choose") {
const channel = message.guild.channels.cache.find(
channel => channel.name === "specific-channel"
);
if (!channel) return message.reply("Je ne peux pas trouver le canal");
const messages = await channel.messages.fetch({ limit: 100 });
const activeUsers = messages
.filter(msg => msg.createdTimestamp > Date.now() - 604800000)
.map(msg => msg.author.id)
.filter((id, index, self) => self.indexOf(id) === index);
const randomIndex = Math.floor(Math.random() * activeUsers.length);
const randomUser = message.guild.members.cache.get(activeUsers[randomIndex]);
message.channel.send(J'ai choisi aléatoirement : ${randomUser.user.username});
}
});
client.login("token");
app isn't answering

Related

useEffect => .then returns undefined

I try to fetch the current offer price for my NFT project but i currently get undefined in this function
useEffect(() => {
returnsCurrentOfferPrice(NFT.tokenId)
.then((offer) => {
console.log(offer);
setReturnCurrentOfferPrice(offer);
})
.catch((error) => {
console.log('Current offer price error', error);
});
}, [NFT.tokenId]);
This is my use State Snippet
const [returnCurrentOfferPrice, setReturnCurrentOfferPrice] = useState(null);
This is how i retrieve the function into my UI
const returnsCurrentOfferPrice = async (tokenId) => {
await getCurrentOfferPrice(tokenId)
}
And finally this is how i retrieve the data from the blockchain
const getCurrentOfferPrice = async (tokenId) => {
const web3Modal = new Web3Modal();
const connection = await web3Modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
const contract = signerOrProvider(provider);
const currentOfferPrice = await contract.getCurrentOfferAmount(tokenId);
const bigNumber = ethers.BigNumber.from(currentOfferPrice);
const currentOfferPriceInEther = ethers.utils.formatEther(bigNumber)
console.log('Current offer price', currentOfferPriceInEther );
return currentOfferPriceInEther;
}

New navigation request was received at LifecycleWatcher

I wanted to scrape using puppeteer with firefox. I got this error.
Here is my code.
const root = require('app-root-path');
const puppeteer = require('puppeteer');
const scraper = require(`${root}/index.js`);
const links = require(`${root}/link.json`);
async function getData() {
const browser = await puppeteer.launch({ headless: false, product: "firefox" })
const linksLimit = 30;
const tempArray = Array.from({ length: Math.ceil(links.length / linksLimit) }, (_, i) => i + 1);
const p = await Promise.allSettled(tempArray.map(slice => {
return new Promise(async (resolve, reject) => {
const start = (slice - 1) * linksLimit;
const end = slice * linksLimit;
const linksSlice = links.slice(start, end);
await scraper(browser, linksSlice);
resolve();
})
}));
return p[p.length - 1].status === 'fulfilled' ? true : false;
}
getData();
/home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/puppeteer/common/LifecycleWatcher.js:137
(_a = __classPrivateFieldGet(this, _LifecycleWatcher_navigationResponseReceived, "f")) === null || _a === void 0 ? void 0 : _a.reject(new Error('New navigation request was received'));
^
Error: New navigation request was received
at LifecycleWatcher._LifecycleWatcher_onRequest (/home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/puppeteer/common/LifecycleWatcher.js:137:139)
at /home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/vendor/mitt/src/index.js:51:68
at Array.map ()
at Object.emit (/home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/vendor/mitt/src/index.js:51:43)
at NetworkManager.emit (/home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/puppeteer/common/EventEmitter.js:72:22)
at NetworkManager._NetworkManager_onRequest (/home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/puppeteer/common/NetworkManager.js:312:10)
at NetworkManager._NetworkManager_onRequestWillBeSent (/home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/puppeteer/common/NetworkManager.js:219:93)
at /home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/vendor/mitt/src/index.js:51:68
at Array.map ()
at Object.emit (/home/moyen/projects/node/daraz/node_modules/puppeteer/lib/cjs/vendor/mitt/src/index.js:51:43)
Node.js v17.4.0

Reconnect websocket rxjs

I'm trying to get my websocket code to automatically attempt a reconnect (indefinitely) until successful. By sending a "ping" message every x seconds, I can detect when a pipe is broken, and the closeObserver is called.
However, I'm not sure how to get a reconnect sequence to initiate.
const notificationConnectionEpic: Epic<ActionTypes, any, RootState> = (
action$,
state$
) =>
action$.pipe(
filter(isActionOf(actions.connectNotificationPipeline.request)),
switchMap(async action => {
const resp = await requireValidToken(action$, state$, params =>
AdminHubs.getHubNotificationsToken({
...params,
id: action.payload.hubId
})
);
return resp.pipe(
switchMap(v => {
if (isAction(v)) {
return of(v);
}
if (!v.ok) {
return of(
actions.connectNotificationPipeline.failure({
hubId: action.payload.hubId,
error: v.error
})
);
}
const webSocketOpen$ = new Subject();
const webSocketClose$ = new Subject();
const webSocket$ = webSocket<AdminHubs.HubNotification>({
url: v.value,
openObserver: webSocketOpen$,
closeObserver: webSocketClose$
});
const message$ = webSocket$.pipe(
map(message => actions.receiveNotification({ message })),
takeUntil(action$.ofType(HubActionConsts.NOTIFICATION_PIPE_CLOSED))
);
const ping$ = interval(1000).pipe(
map(_ => webSocket$.next("ping" as any)),
ignoreElements()
);
const open$ = webSocketOpen$.pipe(
take(1),
map(_ =>
actions.connectNotificationPipeline.success({
hubId: action.payload.hubId
})
)
);
const close$ = webSocketClose$.pipe(
// called when a network drop happens. handle reconnect?
); // also happens on net error
return merge(message$, open$, ping$, close$);
})
);
}),
mergeMap(v => v)
);
When the WebSocket connection closes, just dispatch actions.connectNotificationPipeline.request again. That will re-run this code and create a new WebSocket connection.

Do something if RxJs subject's refCount drops to zero

I'm working on a service layer that manages subscriptions.
I provide subject-backed observables to consumers like this:
const subject = new Subject();
_trackedSubjects.push(subject);
return subject.asObservable();
Different consumers may monitor the channel, so there may be several observables attached to each subject.
I'd like to monitor the count of subject.observers and if it ever drops back to 0, do some cleanup in my library.
I have looked at refCount, but this only is available on Observable.
I'd love to find something like:
subject.onObserverCountChange((cur, prev) =>
if(cur === 0 && prev !== 0) { cleanUp(subject) }
)
Is there a way to automatic cleanup like this on a subject?
Instead of using Subject - you should probably describe setup/cleanup logic when creating observable. See the example:
const { Observable } = rxjs; // = require("rxjs")
const { share } = rxjs.operators; // = require("rxjs/operators")
const eventSource$ = Observable.create(o => {
console.log('setup');
let i = 0
const interval = setInterval(
() => o.next(i++),
1000
);
return () => {
console.log('cleanup');
clearInterval(interval);
}
});
const events$ = eventSource$.pipe(share());
const first = events$.subscribe(e => console.log('first: ', e));
const second = events$.subscribe(e => console.log('second: ', e));
setTimeout(() => first.unsubscribe(), 3000);
setTimeout(() => second.unsubscribe(), 5000);
<script src="https://unpkg.com/rxjs#6.2.2/bundles/rxjs.umd.min.js"></script>

Bot framework in node set sequence message

Developed my bot and now I need all the messages trafficked to be sent to my API, however I have a problem: the order of the messages are not arriving sequentially, how could I solve this?
Every message sent could have an accountant, how could I do this? Or does the bot framework provide this?
Example code
https://gist.github.com/odirleiborgert/8227ff46ca8693307a5373186b9e486c
Or
"use strict"
// ----------------------------------------------------------------------
require('dotenv-extended').load()
// Import packages
const restify = require('restify')
const builder = require('botbuilder')
const api = require('./helpers/api')
// ----------------------------------------------------------------------
/**
* Bot Setup
*/
const port = process.env.port || process.env.PORT || 3978
const server = restify.createServer()
server.listen(port, () => {
console.log(`${server.name} listening to ${server.url}`)
})
const connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
})
const bot = new builder.UniversalBot(connector)
bot.use({
// Usuário envia para o bot
receive: async (event, next) => {
if (event.type == 'message' || event.type == 'conversationUpdate') {
if (process.env.API) {
await api.post.receive(event)
}
}
next()
},
// Bot envia para usuário
send: async (event, next) => {
if (event.type == 'message') {
if (process.env.API) {
await api.post.send(event)
}
}
next()
}
})
bot.use(builder.Middleware.firstRun({
version: 1.0,
dialogId: 'firstRun'
}))
bot.set('storage', new builder.MemoryBotStorage())
// ----------------------------------------------------------------------
// Provider api messages
server.post('/api/messages', connector.listen())
// ----------------------------------------------------------------------
bot.on('conversationUpdate', (session) => {
if (session.membersAdded) {
session.membersAdded.forEach((identity) => {
if (identity.id === session.address.bot.id) {
bot.beginDialog(session.address, 'firstRun')
}
})
}
})
// Add first run dialog
bot.dialog('firstRun', async (session) => {
session.userData.firstRun = true
session.delay(1000)
session.replaceDialog('start')
}).triggerAction({
onFindAction: (context, callback) => {
// Only trigger if we've never seen user before
if (!context.userData.firstRun) {
// Return a score of 1.1 to ensure the first run dialog wins
callback(null, 1.1)
} else {
callback(null, 0.0)
}
},
matches: [
/^Começar|Comecar$/i
]
})
// ----------------------------------------------------------------------
// Start
bot.dialog('start', require('./dialogs/start'))
.triggerAction({
matches: [
/^start|restart$/i
]
})
// ----------------------------------------------------------------------
// Hello
bot.dialog('hello', require('./dialogs/hello'))
// ----------------------------------------------------------------------
/**
* Dialogs with Intents
*/
const recognizer = new builder.LuisRecognizer(process.env.LUIS_MODEL_URL)
const intents = new builder.IntentDialog({
recognizers: [recognizer]
})
intents.onDefault(require('./dialogs/default'))
// Others
intents.matches('hello', require('./dialogs/hello'))
bot.dialog('/', intents)
// --------------------------------------------------------------------
I created a solution for the moment by creating a counter and date variable and sending the other information along to my API.
let count = 1
bot.use({
receive: async (event, next) => {
count++
if (event.type == 'message' || event.type == 'conversationUpdate') {
event.order_at = new Date()
event.sequence_at = count
await api.post.receive(event)
}
next()
},
send: async (event, next) => {
count++
if (event.type == 'message') {
event.order_at = new Date()
event.sequence_at = count
await api.post.send(event)
}
next()
}
})

Resources