I want my bot sends and receives messages in parallel threads. I also want my bot sends message back to user when receives any message from user. But now he sends it back to user every 5 seconds. I understand that it's because i used "loop do" but without infinity loop i cant use callbacks.
So how to send and receive messages in parallel threads? And how to overcome my "loop problem" when receiving messages?
require 'xmpp4r'
class Bot
include Jabber
def initialize jid,jpassword
#jid = jid
#jpassword = jpassword
#client = Client.new(JID::new(#jid))
#client.connect
#client.auth(#jpassword)
#client.send(Presence.new.set_type(:available))
end
def wait4msg
loop do
#client.add_message_callback do |msg|
send_message(msg.from,msg.body)
sleep 5
end
end
end
def send_message to,message
msg = Message::new(to,message)
msg.type = :chat
#client.send(msg)
end
def add_user jid
adding = Presence.new.set_type(:subscribe).set_to(jid)
#client.send(adding)
end
end
bot = Bot.new('from#example.xmpp','123456')
t1 = Thread.new do
bot.wait4msg
end
t2 = Thread.new do
bot.send_message('to#example.xmpp',Random.new.rand(100).to_s)
end
Thread.list.each { |t| t.join if t != Thread.main }
Good day. You can use callbacks without loop, see an examples. For example: in initialize add
#client.add_message_callback do |m|
if m.type != :error
m2 = Message.new(m.from, "You sent: #{m.body}")
m2.type = m.type
#client.send(m2)
end
end
Related
i am running rails 3 thread to improve the performance of the rake task. sometimes i am getting uninitialized constant when i am trying to access outside class from my current class. as an example when i am trying to access NotificationService class from NotificationApp as shown below then getting error as uninitialized constant NotificationService. This error is not coming every time. sometimes rake task is running fine without the error and sometimes same rake is failing with uninitialized constant. what could be the reason for this and how can i fix this issue?
class NotificationApp < ActiveRecord::Base
def signal_event
NotificationService.notify
end
end
Edit
This is how i am creating threadpool
class ThreadPool
def initialize(size)
#size = size
#jobs = Queue.new
#pool = Array.new(#size) do |i|
Thread.new do
Thread.current[:id] = i
catch(:exit) do
loop do
job, args = #jobs.pop
job.call(*args)
end
end
end
end
end
# add a job to queue
def schedule(*args, &block)
#jobs << [block, args]
end
# run threads and perform jobs from queue
def run!
#size.times do
schedule { throw :exit }
end
#pool.map(&:join)
end
# get all threads created
def threads
#pool
end
def complete!
#pool.each{|t| t.kill}
end
end
and this is how i am using threads
def perform
ReadReplicaHelper.read_from_slave do
pool = ThreadPool.new(CONNECTION_POOL_COUNT - 1)
device_ids.in_groups_of(1000, false) do |devices|
devices.each do |device_id|
device = Device.find_by_id(device_id)
if device
ReadReplicaHelper.read_from_master do
Notification.where(device_id: device_id).each do |notification|
pool.schedule do
pool_method notification, last_status, before_last_status
end
end
end
end
end
end
# Run the Thread Pool
pool.run!
# Kill the threads created in the pool
pool.complete!
end
Make sure your NotificationService class is in a file named app/services/notification_service.rb and that you are loading this services directory.
Also as you are using threads, make sure to join all the threads after calling them
I have a test case where I need to spawn 1000 websocket connections and sustain a conversation over them through a Locust task (It has a prefedined send/receive process for the websocket connections). I can successfully do it by the following setup in locust:
Max Number of Users: 1000
Hatch rate: 1000
However, this setup opens up 1000 connection every second. Even if i lower down the hatch rate, it will come to a time where it will continue to spawn 1000 websocket connections per second. Is there a way to spawn 1000 users instantly and halt/delay the swarm in sending new 1000 connections for quite some time?
I am trying to test if a my server can handle 1000 users sending and receiving messages from my server through a websocket connection. I have tried multiprocessing approach in python but I'm having a hard time to spawn connections as fast as I can with Locust.
class UserBehavior(TaskSet):
statements = [
"Do you like coffee?",
"What's your favorite book?",
"Do you invest in crypto?",
"Who will host the Superbowl next year?",
"Have you listened to the new Adele?",
"Coldplay released a new album",
"I watched the premiere of Succession season 3 last night",
"Who is your favorite team in the NBA?",
"I want to buy the new Travis Scott x Jordan shoes",
"I want a Lamborghini Urus",
"Have you been to the Philippines?",
"Did you sign up for a Netflix account?"
]
def on_start(self):
pass
def on_quit(self):
pass
#task
def send_convo(self):
end = False
ws_url = "ws://xx.xx.xx.xx:8080/websocket"
self.ws = create_connection(ws_url)
body = json.dumps({"text": "start blender"})
self.ws.send(body)
while True:
#print("Waiting for response..")
response = self.ws.recv()
if response != None:
if "Sorry, this world closed" in response:
end = True
break
if not end:
body = json.dumps({"text": "begin"})
self.ws.send(body)
while True:
#print("Waiting for response..")
response = self.ws.recv()
if response != None:
# print("[BOT]: ", response)
if "Sorry, this world closed" in response:
end = True
self.ws.close()
break
if not end:
body = json.dumps({"text": random.choice(self.statements)})
start_at = time.time()
self.ws.send(body)
while True:
response = self.ws.recv()
if response != None:
if "Sorry, this world closed" not in response:
response_time = int((time.time() - start_at)*1000)
print(f"[BOT]Response: {response}")
response_length = len(response)
events.request_success.fire(
request_type='Websocker Recv',
name='test/ws/echo',
response_time=response_time,
response_length=response_length,
)
else:
end = True
self.ws.close()
break
if not end:
body = json.dumps({"text": "[DONE]"})
self.ws.send(body)
while True:
response = self.ws.recv()
if response != None:
if "Sorry, this world closed" in response:
end = True
self.ws.close()
break
if not end:
time.sleep(1)
body = json.dumps({"text": "EXIT"})
self.ws.send(body)
time.sleep(1)
self.ws.close()
class WebsiteUser(HttpUser):
tasks = [UserBehavior]
wait_time = constant(2)
host = "ws://xx.xx.xx.xx:8080/websocket"
For this particular test, I set the maximum users to 1 and the hatch rate to 1 and clearly, locust keeps on sending 1 request per second as seen on the following responsees:
[BOT]Response: {"text": "No, I don't have a netflix account. I do have a Hulu account, though.", "quick_replies": null}
enter code here
[BOT]Response: {"text": "I have not, but I would love to go. I have always wanted to visit the Philippines.", "quick_replies": null
[BOT]Response: {"text": "No, I don't have a netflix account. I do have a Hulu account, though.", "quick_replies": null}
[BOT]Response: {"text": "I think it's going to be New Orleans. _POTENTIALLY_UNSAFE__", "quick_replies": null}
My expectation is after I set the maximum user to 1, and a hatch rate of 1, there would instantly be 1 websocket connection sending a random message, and receiving 1 main response from the websocket server. but what's happening is it keeps on repeating the task per second until i explicitly hit the stop button on the locust dashboard.
I would debug your logic. Put more print statements in each if block at various places and between each block. When dealing with a long list of decisions, it's easy to get things tripped up.
In this case, you are only wanting to sleep in a very specific situation but it's not happening. Most likely you're setting end = True when you're not expecting it so you're not sleeping and are immediately going to get a new user.
EDIT:
Reviewing your question and issue description again, it sounds like you expect Locust to send a single request and then never send another one. That's not how Locust works. Locust will run your task code for a user. When it's done, that user goes away and it waits for a certain amount of time (looks like you have it set to 2 seconds) and then it spawns another user and starts the task over again. The idea is it will try to keep a near constant number of users you tell it to. It will not only run 1000 users and then end the test, by default.
If you want to keep all 1000 users running, you need to make them continue to execute code. For example, you could put everything in your task in another while loop with another way to break out and end. That way even after making your socket connection and sending the single message you expect, the user will stay alive in the loop and won't end because it ran out of things to do. Doing it this way requires a lot more work and coordination but is possible. There may be other questions on SO about different approaches if this isn't exactly what you're looking for.
I am trying to set up a bot in discord that works on timers. One of them will work if one person types in the '!challenge' command, in which the bot will wait for 60 seconds to see if anyone types the '!accept' command in response. If it does not, it states 'Challenge was ignored. Resetting.' Or something along those lines.
Another timer actually runs during the game itself, and is an hour long. However, the hour resets after a command has been put in. If the games is idle for an hour (One player DCs or quits) the bot resets the game itself.
I had this working with threading:
# Initiate a challenge to the room. Opponent is whoever uses the !accept command. This command should be
# unavailable for use the moment someone !accepts, to ensure no one trolls during a fight.
if message[:10] == "!challenge":
msg, opponent, pOneInfo, new_game, bTimer, playerOne = message_10_challenge(channel, charFolder, message, unspoiledArena, character, self.game)
if opponent is not "":
self.opponent = opponent
if pOneInfo is not None:
self.pOneInfo = pOneInfo
self.pOneTotalHP = self.pOneInfo['thp']
self.pOneCurrentHP = self.pOneInfo['thp']
self.pOneLevel = self.pOneInfo['level']
if new_game != 0:
self.game = new_game
if bTimer is True:
timeout = 60
self.timer = Timer(timeout, self.challengeTimeOut)
self.timer.start()
if playerOne is not "":
self.playerOne = playerOne
super().MSG(channel, msg)
and:
# Response to use to accept a challenge.
if message == "!accept":
msg, pTwoInfo, new_game, playerTwo, bTimer, bGameTimer, new_oppenent, token = message_accept(channel, charFolder, unspoiledArena, character, self.game, self.opponent, self.pOneInfo)
if not charFile.is_file():
super().MSG(channel, "You don't even have a character made to fight.")
else:
if new_game is not None:
self.game = new_game
if pTwoInfo is not None:
self.pTwoInfo = pTwoInfo
self.pTwoTotalHP = self.pTwoInfo['thp']
self.pTwoCurrentHP = self.pTwoInfo['thp']
self.pTwoLevel = self.pTwoInfo['level']
if bTimer:
self.timer.cancel()
if bGameTimer:
gametimeout = 3600
self.gameTimer = Timer(gametimeout, self.combatTimeOut)
self.gameTimer.start()
if new_oppenent is not None:
self.opponent = new_oppenent
if playerTwo is not None:
self.playerTwo = playerTwo
if token is not None:
self.token = token
for msg_item in msg:
super().MSG(channel, msg_item)
with functions:
def challengeTimeOut(self):
super().MSG(unspoiledArena, "Challenge was not accepted. Challenge reset.")
self.game = 0
def combatTimeOut(self):
super().PRI('Unspoiled Desire', "!reset")
The above is an example of the same game, but on a different chat platform, with threading to handle the timers. But threading and discord.py aren't friends I guess. So I am trying to get the above code to work with discord.py, which seems to use asyncio.
The thought was to use asyncio.sleep() in the
if bTimer is true:
await asyncio.sleep(60)
self.game = 0
await ctx.send("Challenge was not accepted. Challenge reset.")
And this works...but it doesn't stop the timer, so even if someone !accepts, thus changing bTimer to False, which would cancel the timer:
if bTimer:
self.timer.cancel()
it's still going to say "Challenge was not accepted. Challenge reset."
The same problem will occure with bGameTimer if I try:
if bGameTimer:
await asyncio.sleep(3600)
await ctx.send("!reset")
the game will be hardwired to reset after 1 hours time, no matter if the game is done or not. Rather than resetting the 1 hour timer after every turn, and ONLY resetting if a full hour has passed in which no commands are made.
Is there a way to easily cancel or reset sleep cycles?
The asyncio code equivalent to your threading code would be:
...
if bTimer:
self.timer = asyncio.create_task(self.challengeTimeout())
...
async def challengeTimeout(self):
await asyncio.sleep(60)
self.game = 0
await ctx.send("Challenge was not accepted. Challenge reset.")
asyncio.create_task() creates a light-weight "task" object roughly equivalent to a thread. It runs "in parallel" to the your other coroutines, and you can cancel it by invoking its cancel() method:
if bTimer:
self.timer.cancel()
The following queue is not working properly somehow. Is there any obvious mistake I have made? Basically every incoming SMS message is put onto the queue, tries to send it and if it successful deletes from the queue. If its unsuccessful it sleeps for 2 seconds and tries sending it again.
# initialize queue
queue = queue.Queue()
def messagePump():
while True:
item = queue.get()
if item is not None:
status = sendText(item)
if status == 'SUCCEEDED':
queue.task_done()
else:
time.sleep(2)
def sendText(item):
response = getClient().send_message(item)
response = response['messages'][0]
if response['status'] == '0':
return 'SUCCEEDED'
else:
return 'FAILED'
#app.route('/webhooks/inbound-sms', methods=['POST'])
def delivery_receipt():
data = dict(request.form) or dict(request.args)
senderNumber = data['msisdn'][0]
incomingMessage = data['text'][0]
# came from customer service operator
if (senderNumber == customerServiceNumber):
try:
split = incomingMessage.split(';')
# get recipient phone number
recipient = split[0]
# get message content
message = split[1]
# check if target number is 10 digit long and there is a message
if (len(message) > 0):
# for confirmation send beginning string only
successText = 'Message successfully sent to: '+recipient+' with text: '+message[:7]
queue.put({'from': virtualNumber, 'to': recipient, 'text': message})
The above is running on a Flask server. So invoking messagePump:
thread = threading.Thread(target=messagePump)
thread.start()
The common in such cases is that Thread has completed execution before item started to be presented in the queue, please call thread.daemon = True before running thread.start().
Another thing which may happen here is that Thread was terminated due to exception. Make sure the messagePump handle all possible exceptions.
That topic regarding tracing exceptions on threads may be useful for you:
Catch a thread's exception in the caller thread in Python
I am using awesome WM and I want to run a lua function after a client is created/deleted. Specifically, I want to change the name of a tag to the name of one of the clients that are on the tag.
I do this with a timer, but I think the best way to do this would be to register a callback function to awesomeWM that it will invoke when a client is created/removed.
Are there some hooks/callbacks that I can implement to tell awesome to do this for me?
---------------------------------------------UPDATE----------------------------------------
I tried using the signals, but i cant find the correct signal that changes calls my function AFTER the window is created and attached to the tag. I tried this with manage/unmanage tagged/untagged, and tag.new, etc, but no one helps.
Any ideas?
here is the code:
override_name_char = "<"
function tag_name_from_client(c)
if string.match(c.name, "Mozilla Firefox") then
return "Firefox"
end
if string.match(c.name, "Sublime Text") then
return "Sublime"
end
if string.match(c.name, "/bin/bash") then
return "Shell"
end
return ""
end
function tag_name_from_tag(tag)
if tag.name:match(override_name_char) then
return tag.name
end
for _, c in pairs(tag:clients()) do
return " "..tostring(awful.tag.getidx(tag)).." "..tag_name_from_client(c)
end
return tostring(awful.tag.getidx(tag))
end
function refresh_tag_name()
for s = 1, screen.count() do
for _,tag in pairs(awful.tag.gettags(s)) do
tag.name = tag_name_from_tag(tag)
end
end
end
client.connect_signal("tagged", refresh_tag_name)
client.connect_signal("untagged", refresh_tag_name)
--tag_timer = timer({timeout = 0.5})
--tag_timer:connect_signal("timeout", function()
--refresh_tag_name()
--end)
--tag_timer:start()
Thanks in advance for any help regarding this.
One of possible ways for v3.5.6, try this in your rc.lua
local naughty = require("naughty")
client.connect_signal("manage", function (c)
--filter client by class name
if c.class:lower() == "gedit" then
-- do things on client start
naughty.notify({text = "Gedit launched!"})
-- add exit signal for this client
c:connect_signal("unmanage", function() naughty.notify({text = "Gedit closed!"}) end)
end
end)
"A new client is created" is the manage signal.
"A new client was destroyed" is the unmanage signal.
So, something like the following (untested):
local function choose_name_for_tag(t)
for _, c in ipairs(t:clients() do
return "has client: " .. tostring(c.name or "unknown")
end
return "has no clients"
end
local function update_state()
for _, t in pairs(root.tags()) do
t.name = choose_name_for_tag(t)
end
end
client.connect_signal("manage", update_state)
client.connect_signal("unmanage", update_state)
tag.connect_signal("tagged", function(t)
t.name = choose_name_for_tag(t)
end)
tag.connect_signal("untagged", function(t)
t.name = choose_name_for_tag(t)
end)