Cannot create menu handler from Discord.NET Guide for Menus - discord.net

So I am trying to get a menu set up for a discord bot I am working on. I am following the example provided in Discord.Net's documentation, but I am having trouble getting it to actually work.
//Command to test the menu functionality found in Discord.NET
[Command("MenuTest")]
public async Task Spawn()
{
var menuBuilder = new SelectMenuBuilder()
.WithPlaceholder("Please select a manufacturer...")
.WithCustomId("menu-1")
.WithMinValues(1)
.WithMaxValues(1)
.AddOption("Alas!", "Alas!", "Increased Damage")
.AddOption("Skuldugger", "Skuldugger", "Overheat + Increased Damage")
.AddOption("Dahlia", "Dahlia", "Additional hit each attack + Increased ACC")
.AddOption("Blackpowder", "Blackpowder", "Increased ACC + Highly Increased Crit Damage")
.AddOption("Malefactor", "Malefactor", "Garunteed Elemental Roll + Reduced Damage at lower rarites")
.AddOption("Hyperius", "Hyperius", "Increased Accuracy + Reduced Overall Damage")
.AddOption("Feriore", "Feriore", "Less Accuracy + Trown/Explosive Reload")
.AddOption("Torgue", "Torgue", "Less Accuracy + Splash Damage")
.AddOption("Stoker", "Stoker", "Less Accuracy + Extra Attack Action");
var builder = new ComponentBuilder()
.WithSelectMenu(menuBuilder);
await ReplyAsync("You rolled high! You get to pick your manufacturer!", components: builder.Build());
client.SelectMenuExecuted += MyMenuHandler;
}
public async Task MyMenuHandler(SocketMessageComponent arg)
{
var text = string.Join(", ", arg.Data.Values);
await arg.RespondAsync($"You have selected {text}");
}
I know that it has something to do with this line specifically
client.SelectMenuExecuted += MyMenuHandler;
I am unsure of what to substitute for client. If someone could help me figure that out, that would be greatly appreciated.

Related

WorkManger doesn't trigger after manually stopped- Kotlin

I want to use workMager to do some work every 15min,at the same time I want to stop workManger when I clicked on the button "StopThread" below is my Code:
val workManager = WorkManager.getInstance(applicationContext)
val workRequest = PeriodicWorkRequest.Builder(
RandomNumberGeneratorWorker::class.java,
15,
TimeUnit.MINUTES
).addTag("API_Worker")
.build()
binding.buttonThreadStarter.setOnClickListener {
workManager.enqueue(workRequest)
}
binding.buttonStopthread.setOnClickListener {
workManager.cancelAllWorkByTag("API_Worker")
}
And this is the RandomNumberGeneratorWorker
class RandomNumberGeneratorWorker(
context: Context,
params: WorkerParameters
) :
Worker(context, params) {
private val MIN = 0
private val MAX = 100
private var mRandomNumber = 0
override fun doWork(): Result {
Log.d("worker_info","Job Started")
startRandomNumberGenerator();
return Result.success();
}
override fun onStopped() {
super.onStopped()
Log.i("worker_info", "Worker has been cancelled")
}
private fun startRandomNumberGenerator() {
Log.d("worker_info","startRandomNumberGenerator triggered")
var i = 0
while (i < 100 && !isStopped) {
try {
Thread.sleep(1000)
mRandomNumber = (Math.random() * (MAX - MIN + 1)).toInt() + MIN
Log.i(
"worker_info",
"Thread id: " + Thread.currentThread().id + ", Random Number: " + mRandomNumber
)
i++
} catch (e: InterruptedException) {
Log.i("worker_info", "Thread Interrupted")
}
}
}
}
The issue that I'm facing is when I stopped the workManger it didn't work again when I clicked on buttonThreadStarter
I did a little research and I found that I can start-stop-start..etc workManger with the code below :
val workRequest = OneTimeWorkRequest.from(RandomNumberGeneratorWorker::class.java)
binding.buttonThreadStarter.setOnClickListener {
workManager.beginUniqueWork("WorkerName",ExistingWorkPolicy.REPLACE,workRequest)
}
binding.buttonStopthread.setOnClickListener {
workManager.cancelAllWork()
}
but as you can see it's working when I used OneTimeWorkRequest and with that, I can't repeat the work every 15 mins , Any suggestion in how to resolve this issue
WorkManager is not designed for periodic works with exact timing. In reality, the works "are not even periodic".
As you can see here from the logs:
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/debugging#use-alb-shell0dumpsys-jobscheduler
WorkManager delegates to the JobScheduler. JS jobs work in a way that you have a number of explicit(you set them) and implicit(set by the system) constraints and after all of them are satisfied - the job starts.
When you have a period there is an extra constraint - TIMING_DELAY. So if your 15min pass - this doesn't mean in no way that the job will be executed. There might be, and be sure that there will be other constraints. That is the case because WM is designed for resource optimization and it will ensure that the work will finish at some point, even on device restart. But it is not designed to be exact. It is quite the opposite.
And after all the constraints are satisfied - it might take a day, the job is no longer needed and a new job is created with again your 15min constraint - TIMING_DELAY. And the process starts again.
Also - when you say "doesn't trigger" - please, check why. Try to check the debug output from the JS and see if there is work at all. If there is - check what constraints are not satisfied.
But long story short - "every 15min" is not something for WorkManager. Normally you should use AlaramManager for exact timing, but with such a short interval you should try to consider using a Service.
Also, it is dangerous to call: cancelAllWork(). You might break the code of some library in your app. You should better use tags and cancel by tag.

PLC4X:Exception during scraping of Job

I'm actually developing a project that read data from 19 PLCs Siemens S1500 and 1 modicon. I have used the scraper tool following this tutorial:
PLC4x scraper tutorial
but when the scraper is working for a little amount of time I get the following exception:
I have changed the scheduled time between 1 to 100 and I always get the same exception when the scraper reach the same number of received messages.
I have tested if using PlcDriverManager instead of PooledPlcDriverManager could be a solution but the same problem persists.
In my pom.xml I use the following dependency:
<dependency>
<groupId>org.apache.plc4x</groupId>
<artifactId>plc4j-scraper</artifactId>
<version>0.7.0</version>
</dependency>
I have tried to change the version to an older one like 0.6.0 or 0.5.0 but the problem still persists.
If I use the modicon (Modbus TCP) I also get this exception after a little amount of time.
Anyone knows why is happening this error? Thanks in advance.
Edit: With the scraper version 0.8.0-SNAPSHOT I continue having this problem.
Edit2: This is my code, I think the problem can be that in my scraper I am opening a lot of connections and when it reaches 65526 messages it fails. But since all the processing is happenning inside the lambda function and I'm using a PooledPlcDriverManager, I think the scraper is using only one connection so I dont know where is the mistake.
try {
// Create a new PooledPlcDriverManager
PlcDriverManager S7_plcDriverManager = new PooledPlcDriverManager();
// Trigger Collector
TriggerCollector S7_triggerCollector = new TriggerCollectorImpl(S7_plcDriverManager);
// Messages counter
AtomicInteger messagesCounter = new AtomicInteger();
// Configure the scraper, by binding a Scraper Configuration, a ResultHandler and a TriggerCollector together
TriggeredScraperImpl S7_scraper = new TriggeredScraperImpl(S7_scraperConfig, (jobName, sourceName, results) -> {
LinkedList<Object> S7_results = new LinkedList<>();
messagesCounter.getAndIncrement();
S7_results.add(jobName);
S7_results.add(sourceName);
S7_results.add(results);
logger.info("Array: " + String.valueOf(S7_results));
logger.info("MESSAGE number: " + messagesCounter);
// Producer topics routing
String topic = "s7" + S7_results.get(1).toString().substring(S7_results.get(1).toString().indexOf("S7_SourcePLC") + 9 , S7_results.get(1).toString().length());
String key = parseKey_S7("s7");
String value = parseValue_S7(S7_results.getLast().toString(),S7_results.get(1).toString());
logger.info("------- PARSED VALUE -------------------------------- " + value);
// Create my own Kafka Producer
ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, key, value);
// Send Data to Kafka - asynchronous
producer.send(record, new Callback() {
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
// executes every time a record is successfully sent or an exception is thrown
if (e == null) {
// the record was successfully sent
logger.info("Received new metadata. \n" +
"Topic:" + recordMetadata.topic() + "\n" +
"Partition: " + recordMetadata.partition() + "\n" +
"Offset: " + recordMetadata.offset() + "\n" +
"Timestamp: " + recordMetadata.timestamp());
} else {
logger.error("Error while producing", e);
}
}
});
}, S7_triggerCollector);
S7_scraper.start();
S7_triggerCollector.start();
} catch (ScraperException e) {
logger.error("Error starting the scraper (S7_scrapper)", e);
}
So in the end indeed it was the PLC that was simply hanging up the connection randomly. However the NiFi integration should have handled this situation more gracefully. I implemented a fix for this particular error ... could you please give version 0.8.0-SNAPSHOT a try (or use 0.8.0 if we happen to have released it already)

"Parsing error: Unexpected token )" with bot

I'm making a discord bot and I'm trying to make a timer that every second it edits the message to time + 1 second like a real clock (Like 0:00). I'm a noob at this. This is my script:
const Discord = require("discord.js");
exports.run = async(bot, message, args) => {
let timerMessage = await message.channel.send('0');
for (i = 0, 10000000000) {
setTimeout(function() {
timerMessage.edit(timerMessage + 1);
}, 1000);
}
}
module.exports.help = {
name: "timer"
}
I have an error and it says: "Parsing error: Unexpected token )"
I would really appreciate it if you would help me with my problem, Thanks!
(Btw I'm using it in Glitch on Google Chrome)
It says that there's an unexpected token ) because you wrote your loop like this:
for (i = 0, 10000000000) {...}
You forgot to add the third argument (usually i++). Also, if you want it to run 10000000000 times you should write a comparison:
for (let i = 0; i < 10000000000; i++) {...}
I see what you're trying to achieve, but I would do it in a simpler way, using setInterval() instead of setTimeout().
setInterval(() => {
timerMessage.edit(timerMessage + 1);
}, 1000);
You seem to be missing a right parenthesis after the setTimeout function. I am not entirely familiar with what you are doing, but I would try something like this :
const Discord = require("discord.js");
exports.run = async (bot, message, args) => {
let timerMessage = await message.channel.send('0');
for (i = 0, 10000000000) {
setTimeout(function()) {
timerMessage.edit(timerMessage + 1);
}, 1000);
}
}
module.exports.help = {
name: "timer";
}
Although this should (maybe) replace the missing parenthesis in your code, it seems to have many other issues. For example, your for loop does not make much sense. Normally a for loop would look something like this (to repeat a certain number of times in java) :
for (int i = 0; i < 10; i++) {
System.out.println(i);
} // will print numbers 0-9, repeat 10 times
The whole chunk of code with the setTimeout bit seems to be messed up... It would help to have a little more context on what you are trying to do / some commenting in your code.
If you are trying to get into coding, I'd recommend something much more basic or some tutorials. CodingTrain has great coding videos on youtube and you will learn a ton no matter what language you go with. Hope this helped...

Need help understanding how Eclipse IProgressMonitor works

I am using Eclipse IProgressMonitor to monitor the progress of a task. There are four steps, and I write the following code.
int totalWork = 100;
String message = "Compiling " + inputFile.getName();
monitor.beginTask(message, totalWork);
monitor.subTask(message + " - first pass");
...// Work
monitor.worked(25);
if (monitor.isCanceled())
return;
monitor.subTask(message + " - invoking");
...// work
monitor.worked(25);
if (monitor.isCanceled())
return;
monitor.subTask(message + " - second pass");
...// Work
monitor.worked(25);
if (monitor.isCanceled())
return;
monitor.subTask(message + " - final pass");
...// Work
monitor.worked(25);
if (monitor.isCanceled())
return;
monitor.done();
As I have total work 100, and each step increase it by 25, I am hoping to see the progress bar show 25% 50% etc. and increase. However the progress bar stops at some number (33%, 38%, 20%, kind of random on different machines) and does not change until the entire job is done. The task name changes though. I read the JavaDoc for this API and follow the way it suggests (I think). Can anyone help tell me where I went wrong?

How to obtain the Hardware information of the computer using Test Complete

Right now I am working on the performance tests and I have come across the situation, where i need to obtain the hardware information of the computer on which tests are been performed. Is there any way to obtain the hardware information using JScript.
Thanks and Regards,
Guru...
** I have got the answer .....posting this as this might be useful for someone else ......**
function RAM_Information()
{
var SystemAttributes = GetObject("winmgmts:");
var RAMSize = 0;
var MemoryPackets = SystemAttributes.ExecQuery("SELECT Capacity FROM Win32_PhysicalMemory");
var enumItems = new Enumerator(MemoryPackets);
for ( ; !enumItems.atEnd(); enumItems.moveNext())
{
RAMSize += aqConvert.StrToFloat(enumItems.item().Capacity);
}
Log.Message("Total physical memory: " + VarToStr(RAMSize*0.000000001) + " GB");
return RAMSize*0.000000001;
}
function ProcessorInformation()
{
return Sys.CPU;
}