Wont work as i want - if-statement

Right now they both get executed. What am I doing wrong?
if ismsg("talk", msg) then
Say("I do not want to talk about it.")
topic = 1
end
if ismsg("talk", msg) and topic == 1 then
Say("Ok. Get lost!")
idle()
end
I only want the second if condition to be triggered if talk is sent a second time.

The second if statement is always being triggered because you are setting topic to 1 in the first if statement.
Try this:
if ismsg("talk", msg) and topic == 1 then
Say("Ok. Get lost!")
idle()
elseif ismsg("talk", msg) then
Say("I do not want to talk about it.")
topic = 1
end

Related

Attempting to put a delay in a loop in Postman

I'm trying to put a 1 second delay using setTimeout(()=>{},1000) in the Pre-request Script for a Postman POST call.
var moment = require('moment');
var tap1TimeStr = pm.environment.get("now");
var tap1TimeMoment = moment(tap1TimeStr,"YYYY-MM-DDTHH:mm:ss");
var expTap2Time = tap1TimeMoment.add(2, 'minutes').format("YYYY-MM-DDTHH:mm:ss");
console.log("Tap 2 timestamp should be: " + expTap2Time);
var timestamp;
var timecheck = false;
while(!timecheck)
{
setTimeout(() => {},1000);
timecheck = moment.utc().isSame(expTap2Time);
console.log("timecheck: " + timecheck);
timestamp = moment.utc().format("YYYY-MM-DDTHH:mm:ss");
}
console.log("Timestamp is now: " + timestamp);
pm.environment.set("now", timestamp);
But it doesn't seem to work and I can see that the console.log line is being printed far more frequently than 1sec. And the exercise here is to send the "Tap 2" POST exactly 2mins after the first POST (tracked by the 'now' variable). Also, it seems like Postman takes a fair bit of time before it even starts executing this particular script.
Edit: The main requirement here is to send the "Tap 2" POST request exactly 2mins AFTER the "Tap 1" POST request. HOW best to implement that? Espcially if setTimeout() is non-blocking and thus probably can't be used in a loop.
Anyone has any ideas?
setTimeout() takes a callback function which is executed after the specified delay so only what happens in the callback function will happen after that delay.
setTimeout(() => {
console.log("This will be executed after 1 second");
}, 1000);
console.log("This will immediately be executed");
setTimeout() is asynchronous and non-blocking so JavaScript will call set timeout but not wait for 1 second for it to return and instead immediately move on to the next instruction. Only after that 1 second has passed the callback passed to setTimeout() will be scheduled and executed. Have a look at this YouTube video for a good explanation of what's going on.

Message content checker does not work correctly discord.py

I am trying to make a bad words system for my server's custom bot, but it seems to only
listen for the first condition, ignoring the second one:
#bot.event
async def on_message(message):
###BAD WORDS CHECK
if message.author == bot.user:
pass
else:
if (any(x in message.content.lower() for x in words2)):
if "hack" or "crack" in message.content.lower():
await message.reply("I think you may be asking for illegal services or illegal advice. Please refer to rule #5 in the welcome channel!")
await message.channel.send("If you think this was a mistake please reply with $report!")
global CAN_REPORT
CAN_REPORT = "yes"
return
else:
pass
await bot.process_commands(message)
The bot will for some reason respond to any message containing any word from words2:
words2 = [
"instagram",
"snapchat",
"roblox",
"paypal",
"facebook",
"gmail",
"fortnite",
"minecraft",
"apex",
"youtube",
]
ignoring whether the message contains "hack", which leads to it replying to every message talking about social media or games. The goal is to check if BOTH conditions are true.
Any help is appreciated!
With this line if "hack" or "crack" in message.content.lower(): you are basically checking if either the string "hack" is true or if "crack" in message.content.lower() is true.
Thus the check always returns true, because "hack" will always be true.
The way to fix this would be something like this:
if "hack" in message.content.lower() or "crack" in message.content.lower():
Or, better yet, do it like you do in the first check:
word_list = ["hack", "crack"]
if any(x in message.content.lower() for x in word_list):
Its simple just add :
if words2 in message.content.lower():
await message.delete()
await ctx.send('that word is banned')

If statement inside cypress.io test

I'm new to testing and to cypress.io in particular, and I'm trying to test the registering flow in my app.
I want to check two scenarios -
If the user is trying to register with an existing username, an error message should be popping up
Else if proper inputs are inserted, the username is successfully registered
How can I do so in one test? Is there an option to use if statement with cypress?
Thanks a lot in advance.
You can do something like:
If(Cypress.$(‘error msg locator’).length > 0) {
//error msg displayed.Do something
}
else {
//success login.Do something
}

akka persist function is not handled every time

I use akka's PersistentActor with sharding in a cluster to keep track of my state. I have a 'Room' which i can update via following code:
case UpdateRoom(id, room, userId) => ((ret: ActorRef) => {
(userRegion ? GetRoleForRoom(userId, id)).mapTo[String] map { role =>
if (role == "owner") {
state = Some(room)
ret ! Success(room)
eventRegion ! RoomEventPackage(id, RoomUpdated(room))
println("works")
persist(RoomUpdated(room))(e => println("this doesn't always fire")
} else {
ret ! Failure(InsufficientRights(role, "Update Room"))
}
}
Problem is that persist only works every other time while the rest of the function works as expected. ("works" gets printed every time, "this doesn't always fire" every other but then two times).
I always have to fire the update command two times to store my Event, but then it appears to be stored for both times i fired the command.
Am i missing an important part of akka persist?
I think that you are making a grave mistake in the world of Actor: accessing the actor (mutable) state from outside. In your case, this happens twice from within the callback of the Future returned by ask/?:
when updating state: state = Some(room)
when calling persist
The only safe way to deal with asking from within your Actor and subsequently modifying the actor's state, is to send a message to the same actor from ask's callback, to that end, you can use pipeTo.
Using a simplified version of your code to illustrate:
case UpdateRoom(id, room, userId) =>
val answer = (userRegion ? GetRoleForRoom(userId, id)).mapTo[String] map(role => RoleForRoom(id, room, userId, role))
answer piepTo self
case RoleForRoom(id, room, userId, room) =>
if (role == "owner") {
state = Some(room)
eventRegion ! RoomEventPackage(id, RoomUpdated(room))
persist(RoomUpdated(room))(e => println("this is safe"))
}
see also: https://doc.akka.io/docs/akka/2.5.6/scala/general/jmm.html#actors-and-shared-mutable-state

Stopping an Actor Instance and Waiting for it to Stop

I have the following piece of code in my Actor's (I call this Actor MasterActor) receive method:
override def receive: Receive = {
case StopActor(id, actorConfig) =>
log.info(s"Stopping actor with id = $id and config $actorConfig")
stopActor(id, powerPlantCfg).pipeTo(self)
context.become(waitForStop(sender()))
// Other messages... not shown here for simplicity
}
So what I'm doing above is to stop the actor and pipe the result of that which is a Future[Continue] (where Continue is a Monix Ack type) to the Actor that contains the above Receive method. The stopActor looks like this:
private def stopActor(id: Long, cfg: ActorConfig): Future[Ack] = async {
await(fetchActor(id).materialize) match {
case scala.util.Success(actorRef) =>
log.info(s"Stopping Actor with id = $id")
context.watch(actorRef)
context.stop(actorRef)
Continue
case scala.util.Failure(fail) =>
log.error(s"Could not fetch Actor instance for id = $id because of: $fail")
Continue
}
}
I'm doing the context.watch(actorRef) and this is how my waitForStop looks like:
private def waitForStop(source: ActorRef): Receive = {
case Continue =>
source ! Continue
context.become(receive)
case someShit =>
log.error(s"Unexpected message $someShit received while waiting for an actor to be stopped")
}
So I have 2 questions here:
When doing context.become(waitForStop(sender())), I'm closing in on the sender(), so I assume the sender in this case is the ActorRef that contains all this above code which is the MasterActor. Am I correct?
How do I know explicitly that this ActorRef that I'm trying to stop is actually stopped so that I can do a context.unwatch(actorRef) as soon as it is stopped?
Any suggestions?
You can be notified of the stop of an Actor by watching it. You are already familiar with watch:
val kenny = context.actorOf(Props[Kenny], name = "Kenny")
context.watch(kenny)
and then you can wait for a Terminated message. Once you receive it, you can unwatch what you need.
def receive = {
case Terminated(kenny) => println("OMG, they killed Kenny")
case _ => println("Parent received a message")
}
So my reccomendation would be to simply watch, become waiting for terminated, and issue the stop command. But I'm unsure what you are asking exactly, so this cvould be the wrong ans
Blog post example