pyircbot/pyircbot/modules/PingResponder.py

65 lines
1.9 KiB
Python
Raw Normal View History

2013-12-28 09:58:20 -08:00
#!/usr/bin/env python
2014-10-02 18:14:42 -07:00
"""
.. module:: PingResponder
2015-11-01 18:03:11 -08:00
:synopsis: Module to repsond to irc server PING requests
2014-10-02 18:14:42 -07:00
.. moduleauthor:: Dave Pedu <dave@davepedu.com>
"""
2017-01-01 14:59:01 -08:00
from time import time, sleep
from threading import Thread
2017-01-01 14:59:01 -08:00
from pyircbot.modulebase import ModuleBase, ModuleHook
2013-12-28 09:58:20 -08:00
class PingResponder(ModuleBase):
2015-11-01 18:03:11 -08:00
def __init__(self, bot, moduleName):
2017-01-01 14:59:01 -08:00
ModuleBase.__init__(self, bot, moduleName)
self.timer = PingRespondTimer(self)
2017-01-01 14:59:01 -08:00
self.hooks = [
2015-12-13 13:40:53 -08:00
ModuleHook("PING", self.pingrespond),
ModuleHook("_RECV", self.resettimer),
ModuleHook("_SEND", self.resettimer)
2015-12-13 13:40:53 -08:00
]
2015-11-01 18:03:11 -08:00
def pingrespond(self, args, prefix, trailing):
"""Respond to the PING command"""
# got a ping? send it right back
self.bot.act_PONG(trailing)
self.log.info("%s Responded to a ping: %s" % (self.bot.get_nick(), trailing))
2015-12-13 13:40:53 -08:00
def resettimer(self, msg):
"""Resets the connection failure timer"""
self.timer.reset()
2015-12-13 13:40:53 -08:00
def ondisable(self):
self.timer.disable()
2015-12-13 13:40:53 -08:00
class PingRespondTimer(Thread):
"Tracks last ping from server, and reconnects if over a threshold"
def __init__(self, master):
Thread.__init__(self)
self.daemon = True
self.alive = True
self.master = master
self.reset()
self.start()
2017-01-01 14:59:01 -08:00
def reset(self):
"Reset the internal ping timeout counter"
self.lastping = time()
2017-01-01 14:59:01 -08:00
def disable(self):
"Allow the thread to die"
self.alive = False
2017-01-01 14:59:01 -08:00
def run(self):
while self.alive:
sleep(5)
2017-05-14 12:42:57 -07:00
if time() - self.lastping > self.master.config.get("activity_timeout", 300):
self.master.log.info("No activity in %s seconds. Reconnecting" % str(time() - self.lastping))
self.master.bot.kill("Ping timeout", forever=False)
self.reset()
2017-01-01 14:59:01 -08:00