irc: Hide threading hacks inside the class

This commit is contained in:
Alexei Sorokin 2017-06-06 19:44:03 +03:00
parent aa67de2acc
commit 2349db325d

View File

@ -20,6 +20,7 @@ class IRCBot:
self.pure_nick = self.nick
self.chan = opts['chan']
self.inter = inter
self.loop = None
def register_handlers(self):
self.conn.add_global_handler('welcome', self.on_session_start)
@ -47,7 +48,7 @@ class IRCBot:
if typ == 'action':
body = '/me ' + body
self.inter.relay_message('irc', nick, body)
self.call_outside(self.inter.relay_message, 'irc', nick, body)
def on_presence(self, conn, event):
try:
@ -57,19 +58,19 @@ class IRCBot:
if typ == 'part':
if nick != self.nick:
if nick in self.inter.get_irc_users():
self.inter.remove_irc_user(nick)
self.call_outside(self.inter.remove_irc_user, nick)
else:
if nick != self.nick:
if nick not in self.inter.get_irc_users():
self.inter.append_irc_user(nick)
self.call_outside(self.inter.append_irc_user, nick)
except Exception as e:
print(str(e), file=sys.stderr)
def on_namreply(self, conn, event):
for nick in event.arguments[2].split():
if nick != conn.get_nickname():
self.inter.append_irc_user(nick)
self.call_outside(self.inter.append_irc_user, nick)
def on_kick(self, conn, event):
self.nick = self.pure_nick
@ -99,9 +100,15 @@ class IRCBot:
except Exception as e:
print(str(e), file=sys.stderr)
def call_outside(self, func, *args):
assert self.loop
self.loop.call_soon_threadsafe(func, *args)
@asyncio.coroutine
def run(self):
self.loop = asyncio.get_event_loop()
self.register_handlers()
self.client.start()
yield from self.loop.run_in_executor(None, self.client.start)
class XMPPBot:
@ -205,8 +212,7 @@ class XMPPBot:
class Intermedia:
def __init__(self, loop, shared_opts, irc_chan, xmpp_muc):
self.loop = loop
def __init__(self, shared_opts, irc_chan, xmpp_muc):
self.irc_chan = irc_chan
self.xmpp_muc = xmpp_muc
self.ircbot = None
@ -227,7 +233,7 @@ class Intermedia:
def to_xmpp(self, msg, prefix=''):
if self.xmppbot:
loop.call_soon_threadsafe(self.xmppbot.send_message, msg, prefix)
self.xmppbot.send_message(msg, prefix)
def relay_message(self, from_net, nick, body):
if not self.ircbot or not self.xmppbot:
@ -342,12 +348,11 @@ if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL)
loop = asyncio.get_event_loop()
inter = Intermedia(loop, shared_opts, irc_opts['chan'], xmpp_opts['muc'])
inter = Intermedia(shared_opts, irc_opts['chan'], xmpp_opts['muc'])
ircbot = IRCBot(irc_opts, inter)
xmppbot = XMPPBot(xmpp_opts, inter)
inter.set_bots(ircbot, xmppbot)
asyncio.async(xmppbot.run())
asyncio.async(loop.run_in_executor(None, ircbot.run))
asyncio.async(ircbot.run())
loop.run_forever()
loop.close()