Discord.js Bot Status - discord

No, I am not asking how to set my bot's status. I am asking how to make my bot's status change every 5-7 seconds to another status. How would I make this:
client.user.setActivity(`dsc.gg/ultraa | ?help | ${client.guilds.cache.size} servers`, { type: 'WATCHING' });
change every few seconds to be like "It's frosty out there", and "420 servers", and "?help | dsc.gg/ultraa". How would I make those statuses rotate between each other?

Note: This code is for Discord.js V13.3.1
For a rotating status, as you would describe, you would do this by placing some code in the ready event that changes the status after a set period of time. This will require the util package which can be installed using:
npm: npm install util
yarn: yarn install util
Once you have the package installed, you will create a function called wait. It's a simple way to wait without blocking the rest of the script.
const wait = require('util').promisify(setTimeout);
This function will serve our primary purpose, making the delay between switching the statuses. Then, we will use setInterval to continuously loop between the statuses.
<Client>.on('ready', async () => {
// ...
setInterval(async () => {
client.user.setPresence({ activities: [{ name: `Status1`, type: `PLAYING` }] });
await wait(5000); // Wait 5 seconds
client.user.setPresence({ activities: [{ name: `Status2`, type: `PLAYING` }] });
await wait(5000); // Wait 5 seconds
});
});
As you can see, there are two line that repeat themselves. That is: <Client>.user.setPresence(...) and await wait(5000). The wait function will block the status from updating itself too early. You can edit the amount of time set by converting the seconds to milliseconds (5 seconds becomes 5000). The other portion sets the bot's status. The type shows what the bot is doing. The valid values for this are found in the docs. You can simply copy and paste the two lines and add more statuses as needed.

client.user.setPresence({ activities: [{ name: `Status`, type: `PLAYING` }] });
For Simple Status

Related

NPM react-native-custom-timer-notification

Hello friends, I'm in doubt, I was wondering if you guys can help me. I'm doing a project in React Native where I need push notifications to contain a timer/countdown and that they can pause/start tasks and that countdown. It's been a challenge for me. I would like to do as the notifications of the app Pomodoro, which pause tasks through them and warn you how much time is left to finish a task. I found nothing about on the internet
I just found the dependency react-native-custom-timer-notification in the NPM website, if you know any other dependency that you can do that, please pass me
Usage
payload sent will be received when click or canceled
title Title of the notification
body Body of the notification
id unique number
date Time at which zero comes
import { TimerNotification, onEvent } from "react-native-custom-timer-notification";
// ...
// onclick and cancel listner
onEvent(event=>{
console.log(event)
});
// Remove timer
RemoveTimer(160211114);
//Trigger notification
TimerNotification({
payload: JSON.stringify('notificationOpen?.data'),
title: 'My notification',
body: 'Much longer text that cannot fit one line... ',
id: 160211114,
remove: false, // optional
foreground: false,
date: new Date(Date.now() + 20000),
isCountDown: true, // false for positive timer
setCustomContentView:true // optional
});
now react-native-custom-timer-notification v0.8 supports full scale custom notification. i think this might help you in this case. https://www.npmjs.com/package/react-native-custom-timer-notification

Prevent angular http post request timeout

I am created a AngularJs Post request.The request contain a long process take more than 2 minutes for perform that.But my angular request return null error after 15 seconds.request perfectly working and no error.But angular request time out with in 15 seconds
$http.post('/api/evaluateOmrExamination',{exam_id:$scope.curExam.id})
.success(function(data,status,headers,config){
$scope.showProgress=false;
ngNotify.config({
theme: 'pure',
position: 'top',
duration: 3000,
type: 'info',
sticky: false,
button: true,
html: false
});
ngNotify.set('Evaluate Examination Completed Successfully');
$scope.errorLists=data;
}).error(function(data,status,headers,config){
console.log(data);
//$scope.showProgress=false;
});
I am also set time out in angular but no use.
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 10000000;
}]);
I need your suggestions
Short term fix is to increase your server's timeout (this is not a client / Angular issue). You say you're using LAMP, so you must configure PHP's max_execution_time property in php.ini to a larger value. You may also need to configure Apache's timeout in httpd.conf.
Long term fix, the request could return immediately (i.e. not 2 minutes or even 15 seconds later). This doesn't mean the job is done, just that the request to perform the job is done. Then you can ping your server every X seconds to see if the job is complete, and then get the data to display to the user. It seems like more work, and it may take a little more time, but I've found that it can be easier to develop and debug this way instead of having single monolithic requests that do a lot of work. In addition to being a better user experience :)
There are some good recommendations here.
app.factory('timeoutHttpIntercept', function ($rootScope, $q) {
return {
'request': function(config) {
config.timeout = 10000000;
return config;
}
};
});
And in your config:
$httpProvider.interceptors.push('timeoutHttpIntercept');

Background Geolocation Plugin: Track location and update database every 5 minutes

I'm currently developing a mobile app using AngularJS / Ionic 3.
I need to track at all time, if my users are within a radius of 100m of a certain geolocation (let's call it "Home Location". I need to know at all time which user is at his home location, and who is not (even when the app is running in background or is closed/ terminated).
I thought to realize this, using the Ionic Native Background-Geolocation plugin and the cordova-plugin-background-geolocation. My plan was, to check the users geolocation every 5 minutes and compare it to the home.
Case 1) If the distance between the two locations is < 100m I know the user is "at home". I would then update the user node in my database (Firebase) to mark the user as isAtHome: true and add a current timestamp.
Case 2) If the user is not within 100m of his home location I would mark him as isAtHome: false and add a current timestamp.
I need to update my database even in case the user didn't move, because I need to know that I received a current signal. Otherwise I don't know if he didn't move or turned off his smartphone, for example.
If I want to know, who of my users is at his home location, I would check the isAtHome-attributes and if they are set to true, I would check the timestamp to be sure that I have up-to-date data and the data was written within the last 15 minutes.
I tried many different things, but I'm not sure how to realize this with the Cordova Background Geolocation Plugin and if it's even possible.
My question is:
Is it possible to check the users geolocation every 5 minutes (even in background / terminated state) and call a function that updates my firebase DB accordingly? As described, I need to receive the location even if the user didn't move within the last 5 minutes.
If it isn't possible: Does anybody have an idea, of how to approach the requirements on another way?
Thank you very much for your help!
As described in the cordova-plugin-background-geolocation says, you can configure an interval in milliseconds for the plugin to get the location, see this example from the plugin github page:
backgroundGeolocation.configure(callbackFn, failureFn, {
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
url: 'http://192.168.81.15:3000/locations',
httpHeaders: { 'X-FOO': 'bar' },
maxLocations: 1000,
// Android only section
locationProvider: backgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
interval: 60000, // <-- here
fastestInterval: 5000,
activitiesInterval: 10000,
notificationTitle: 'Background tracking',
notificationText: 'enabled',
notificationIconColor: '#FEDD1E',
notificationIconLarge: 'mappointer_large',
notificationIconSmall: 'mappointer_small'
});
The case is this interval property works only for Android. I would sugest a workaround like this:
public getLocation: boolean = true; // CREATE A BOOLEAN TO KNOW IF YOU CAN GET LOCATION
backgroundGeolocation.start( // i've never used this plugin, so i'm assuming this is what starts de background watcher
() => {
if(getLocation == true){
this.getLocation = false; // SET TO FALSE SO IT DON'T DO YOUR FUNCTION THE NEXT TIME IT GETS THE LOCATION
// DO YOUR CODE TO SAVE AND CHECK YOUR DATA
// IT'S BETTER IF YOU USE A PROMISE, ASYNC/AWAIT FOR THE SAVING CODE
yourSavingCodeFunction().then(() => {
setTimeout(()=>{
// AFTER 5 MINUTES, SET THE GETLOCATION TO TRUE SO IT CAN DO YOUR FUNCTION AGAIN
this.getLocation = true;
}, 500000);
});
}
},
(error) => {
// Tracking has not started because of error
// you should adjust your app UI for example change switch element to indicate
// that service is not running
}
);
If you haven't thought about your cases 1 and 2 we can work on this too. Hope this helps or can give you some ideas :D

Long running script that polls external server with variable backoff timer?

I am writing a long running script based on Amphp library, that will poll a external server for a list of tasks to run and then execute those tasks.
In the response from the server would be the backoff timer that would control when the script makes it's next request.
Since I am very new to async programming what I am trying is not working.
I tried to create a \Amp\repeat() that had an \Amp\Pause(1000) so that each repeat would pause for 1 second.
Here's my test code:
function test() {
// http request goes here...
echo 'server request '.microtime(true).PHP_EOL;
// based on the server request, change the pause time
yield new \Amp\Pause(1000);
}
Amp\execute(function () {
\Amp\onSignal(SIGINT, function () {
\Amp\stop();
});
\Amp\repeat(100, function () {
yield from test();
});
});
What I expected to happen was that on each repeat, the test() function would pause for 1 second after the echo but instead the echo was run every 100ms (the repeat time).
In the past I would accomplish this with a while loop and usleep() but since usleep() is blocking this defeats the purpose.
I'm using PHP 7.0 and Amphp from github master branch.
\Amp\repeat calls the callback every 100 milliseconds, regardless of when the callback terminates.
\Amp\execute(function () {
/* onSignal handler here for example */
new \Amp\Coroutine(function () {
while (1) {
/* dispatch request */
echo 'server request '.microtime(true).PHP_EOL;
yield new \Amp\Pause(100);
}
});
});
This is using a normal loop which only continues 100 ms after the last action.
[If I misunderstood what exactly you want, please note in comments.]

Can protractor be made to run slowly?

Is there a way to run a Angular E2E test written using protractor slowly so that I can watch what is happening?
Below is my solution to do that. So basically I created a decorator for current control flow execute function, which now additionaly queues a delay of 100ms before each queued action.
This needs to be run before any tests are invoked (outside describe block)
var origFn = browser.driver.controlFlow().execute;
browser.driver.controlFlow().execute = function() {
var args = arguments;
// queue 100ms wait
origFn.call(browser.driver.controlFlow(), function() {
return protractor.promise.delayed(100);
});
return origFn.apply(browser.driver.controlFlow(), args);
};
Just like George Stocker said in the comment, I don't know why you would want to do this...but you can always add a sleep wherever you want in your test.
browser.sleep(6000);
Previous answers look more like workaround. Another way is to add param to Protractor config:
highlightDelay: 1000
And change to:
directConnect: false
It will delay Protractor actions like clicking or typing for 1 second and will highlight in light blue.
You can enter in 'debug mode' by placing in your code the command:
browser.pause();
In the debug mode, you would see the following output in your terminal:
------- WebDriver Debugger -------
ready
press c to continue to the next webdriver command
press d to continue to the next debugger statement
type "repl" to enter interactive mode
type "exit" to break out of interactive mode
press ^C to exit
You could then:
Run command by command by entering c
Continue to the next debugger statement (next browser.pause()) by entering d
Enter in interactive mode where you could interact with all the elements by entering repl
2 ways for doing this
1. First is very childish way, but I'll leave it here
you can highlight the elements you're interacting with!
highlightElement: async ($elementObject, time = 1000) => {
async function setStyle(element, style) {
const previous = await element.getAttribute('style');
await element.setAttribute('style', style);
await setTimeout(() => {
element.setAttribute('style', previous);
}, time);
}
await browser.sleep(time)
return await browser.executeScript(await setStyle, $elementObject.getWebElement(), 'color: red; background-color: yellow; z-index: 9999;');
},
This will highlight the element for a second
And then wrap your actions using this element
let click = async function ($elem) {
await highlightElement($elem);
await $elem.click();
}
let sendKeys = async function ($elem, text) {
await highlightElement($elem);
await $elem.sendKeys(text);
}
And then use it to try some scripts
await sendKeys($login, username);
await sendKeys($password, password);
await click($submit);
This shouldn't really be used in the real script, only when you're playing with it
2. Setup debugging configuration in your code editor
Example for vs code https://medium.com/#ganeshsirsi/how-to-debug-protractor-tests-in-visual-studio-code-e945fc971a74, but the same thing can be achieved in webstorm
This will allow you to execute the code line by line and interact with the variables in the real time. MUST HAVE for everyone who works with protractor. I'm serious

Resources