-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
80 lines (68 loc) · 2.19 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import os
import sys
import signal
import logging
from optparse import OptionParser
import lockfile
import daemon
import log
import config
from bot import IRCBot
LOG = logging.getLogger('main')
LOCK = lockfile.FileLock('thbotter')
ircbot = IRCBot(config.SERVER, config.CHANNELS, config.NICKNAME, config.REALNAME)
def destroy(*args):
LOG.info("Destroy IRC Bot by signal")
print "Stop bot by os signal"
ircbot.die()
def run_daemonize():
LOG.debug("Start initialize daemon")
bot_path = os.path.realpath(os.path.dirname(__file__))
context = daemon.DaemonContext(
working_directory=bot_path,
pidfile=LOCK
)
LOG.debug("Add signals map")
context.signal_map = {
signal.SIGTERM: destroy
}
LOG.debug("Change stdout/stderr")
context.stdout = open(os.path.join(bot_path, 'stdout.log'), 'wr')
context.stderr = open(os.path.join(bot_path, 'stderr.log'), 'wr')
context.files_preserve = [LOG.parent.handlers[0].stream.fileno()]
LOG.debug("Start bot")
with context:
LOG.info("Run bot loop")
try:
ircbot.start()
except Exception, e:
LOG.error("Bot failed with error: %s" % e)
for p in ircbot._plugins:
if p.is_alive():
p.stop()
p.join()
raise
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-d", "--daemonize", dest="daemonize", help="Daemonize bot or not", action="store_true")
(options, args) = parser.parse_args()
if options.daemonize:
if os.path.isfile(LOCK.lock_file):
print "Please delete lock file: %s" % LOCK.lock_file
sys.exit(1)
LOG.info("Run bot in daemonize mode")
print "Start bot in daemonize mode..."
run_daemonize()
else:
LOG.info("Run bot in standalone mode")
signal.signal(signal.SIGINT, destroy)
try:
print "Start bot..."
ircbot.start()
except Exception, e:
LOG.error("Bot failed with error: %s" % e)
for p in ircbot._plugins:
if p.is_alive():
p.stop()
p.join()
raise