My Jabber bot gets stuck -- how to throttle message sending? - python

I have my own jabber bot, and today I made a new plugin, which is to send message for all users. My code was working well, but I have a small problem; when I give my bot the command to send a message, my bot gets stuck and disconnects.
I know why my bot gets stuck and disconnects; I have more than 2000 users, so my bot cannot send a message at the same time for all users. Is there any method in Python to make my code send the message for each user after N seconds? I mean have the bot send MSG for user1, then wait for N seconds and send for user2, etc.
I hope my idea is clear. This is my code:
def send_msg(type, source, parameters):
ADMINFILE = 'modules/xmpp/users.cfg'
fp = open(ADMINFILE, 'r')
users = eval(fp.read())
if parameters:
for z in users:
msg(z, u"MSG from Admin:\n" +parameters)
reply(type, source, u"MSG has been sent!")
else:
reply(type, source, u"Error! please try again.")
register_command_handler(send_msg, 'msg', ['all','amsg'], 0,'Sends a message to all users')

I believe you are looking for time.sleep(secs). From the docs:
Suspend execution for the given number of seconds. The argument may be
a floating point number to indicate a more precise sleep time. The
actual suspension time may be less than that requested because any
caught signal will terminate the sleep() following execution of that
signal’s catching routine. Also, the suspension time may be longer
than requested by an arbitrary amount because of the scheduling of
other activity in the system.
After each send you can delay for time.sleep(seconds) before sending your next message.

Related

TeleBot, How to make bot auto reply message after 10mins

TeleBot, how to set it schedule send after user send message to our bot, i want it auto reply to user after 10mins
If by TeleBot you mean a Telegram-Bot then you have two options:
a) put in a CRON-Job that triggers a response function after given time
or
b) If it is okay that the process is inactive/unavailable for 10 mins then you can just let the programm sleep for 10 minutes (which is probably not what you want by using a chatbot because this would make the bot miss messages in that time if those are not buffered anywhere).
If neither fits your problem, please give us more information on the problem

Redis-py: run_in_thread eventhandler stops getting called after few hours

I'm trying to implement a basic pubsub using redis-py client.
The idea is, the publisher is actually a callback that gets called periodically and will publish some information on channel1 in the callback function.
The subscriber will listen on that channel for this message and do some processing accordingly.
The subscriber is actually a basic bare-bones webserver that is deployed on k8s and it simply should show up the messages that it receives via the event_handler function.
subscriber.py
class Sub(object):
def __init___(self):
redis = Redis(host=...,
port=...,
password=...,
db=0)
ps = redis.pubsub(ignore_subscribe_messages=True)
ps.subscribe(**{'channel1': Sub.event_handler})
ps.run_in_thread(sleep_time=0.01, daemon=True)
#staticmethod
def event_handler(msg):
print("Hello from event handler")
if msg and msg.get('type') == 'message': # interested only in messages, not subscribe/unsubscribe/pmessages
# process the message
publisher.py
redis = Redis(host=...,
port=...,
password=...,
db=0)
def call_back(msg):
global redis
redis.publish('channel1', msg)
At the beginning, the messages are published and the subscriber event handler prints and process it correctly.
The problem is, after few hours, the subscriber stops showing up those messages. I've checked publisher logs and the messages definitely get sent out, but I'm not able to figure out why the event_handler is not getting called after few hours.
The print statement in it stops getting printed which is why I say the handler is not getting fired after few hours.
Initially I suspected the thread must have died, but on exec into the system I see it listed under the list of threads.
I've read through a lot of blogs, documentations but haven't found much help.
All I can deduce is the event handler stops getting called after sometime.
Can anyone help understand what's going on and the best way to reliably consume pubsub messages in a non blocking way?
Really appreciate any insights you guys have! :(
could you post the whole puplisher.py, please? It could be the case that call_back(msg) isn't called anymore.
To check whether a client is still subscribed, you can use the command PUBSUB CHANNELS in reds-cli.
Regards, Martin

How to add a pause between sending messages in python telegram bot?

I'm making a bot with python-telegram-bot that sends you several messages in a row in response to a single command. When all messages arrive at once, it is inconvenient to the user. I want to add a pause between sending and send action=ChatAction.TYPING between them. Is there any convenient way to do this without using something like time.sleep()?
I believe that the framework's JobQueue solves your problem. It allows you to schedule messages to be sent at some point in the future.
Quote:
You can also add a job that will be executed only once, with a delay:
>>> def callback_30(bot, job):
... bot.send_message(chat_id='#examplechannel',
... text='A single message with 30s delay')
...
>>> j.run_once(callback_30, 30)
In thirty seconds you should receive the message from callback_30.

python stomp receive number of messages from activemq

Is it possible to receive only a number of messages from activemq.
Let say I need to receive only 100 messages from queue, is it possible.
I am using message listener method, is there any other method to receive messages.
example code snippet:
queue_messages = []
class SampleListener(object):
def on_message(self, headers, msg):
queue_messages.append(msg)
def read_messages():
queue_connection = stomp.Connection([(activemq_host, int(activemq_port))])
queue_connection.start()
queue_connection.connect('admin', 'admin')
queue_connection.set_listener('SampleListener', SampleListener())
queue_connection.subscribe(destination=activemq_input_q, id=1, ack='auto')
time.sleep(1)
queue_connection.disconnect()
read_messages()
Why don't you share your problem rather than the solution in your mind? Chances are the problem might not be a problem as you think or there can be better solutions.
To answer your question, yes you can. For ActiveMQ case, you can add extra header like {'activemq.prefetchSize':100}, ans set ack='client', when you subscribe the queue. But you do not acknowledge the messages at all. The consequence is you will not receive any more messages than 100.
It is a awkward solution I must say. Your code will end up with consuming the first 100 messages in the queue and that's it. You can apparently disconnect and resubscribe the same queue to receive the next 100 messages.
when ack='client' and i don't acknowledge the message on on_message event, when actually the acknowledgement will be sent to the server, will it send the acknowledgement on successful disconnect.
Also, if i abruptly kill the script, will be acknowledgement be still sent and will i miss the messages

Alarm in pyTelegram Bot

I want to write a simple reminder-bot for telegram. Bot gets from user time (Hours:Minutes) and saves it. When system time equals to users remind time, bot sends message to user.
This is how i track current time:
import time
def timer():
now = time.strftime('%X').split(':')[0:2]
return now
The question is:
How can I make my code wait till time to send message comes without using time.sleep() and checking current time each minute (uses too much memory of raspberrypi)?
If you use python-telegram-bot library, you can use the JobQueue to set up timed jobs.
See here for an example.

Categories