Skip to content

Commit

Permalink
bleh
Browse files Browse the repository at this point in the history
  • Loading branch information
pefoley2 committed Jan 10, 2017
1 parent 29830fc commit 5fecf58
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 10 deletions.
19 changes: 14 additions & 5 deletions slack_bridge/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import asyncio
import collections
import os
import logging
import random
import time
import threading
Expand All @@ -33,10 +34,16 @@ def __init__(self, bridge):
def from_irc(self, channel, nick, msg):
# TODO(pefoley): Make this back-and-forth less hacky.
if nick.strip('_slack') == self.bridge.masters[channel[1:]]:
logging.debug(msg)
self.bridge.slack.send(channel, msg.prefix.nick, msg.args[1])

def from_slack(self, msg):
print(msg)
def from_slack(self, channel, nick, msg):
self.bridge.event.wait()
logging.debug(msg)
self.bridge.irc[channel][nick].send(msg)

def schedule(self, func):
asyncio.run_coroutine_threadsafe(func, self.bridge.loop).result()

class Bridge(object):

Expand All @@ -45,8 +52,8 @@ def __init__(self, directory):
self.config = config.get_config(os.path.join(directory, 'config.cfg'))
self.channels = self.config['core']['channels'].split(',')
self.proxy = Proxy(self)
self.slack = slack.SlackBridge(self.config['api']['token'])
self.irc = collections.defaultdict(list)
self.slack = slack.SlackBridge(self.proxy, self.config['api']['token'])
self.irc = collections.defaultdict(dict)
self.masters = {}
self.loop = asyncio.get_event_loop()

Expand All @@ -59,7 +66,7 @@ def slack_connect(self):
# TODO(pefoley): Is this really the best way?
self.masters[channel] = random.choice(members)[0]
for nick, name in members:
self.irc[nick].append(irc.IrcBridge(self.proxy, '#{}'.format(channel), '{}_slack'.format(nick), name))
self.irc[channel][nick]= irc.IrcBridge(self.proxy, '#{}'.format(channel), '{}_slack'.format(nick), name)

def irc_connect(self):
self.loop.set_debug(True)
Expand All @@ -77,5 +84,7 @@ def shutdown(self):
def init(directory: str):
bridge = Bridge(directory)
bridge.slack_connect()
# TODO(pefoley): Port to asyncio?
threading.Thread(target=bridge.slack.message_loop).start()
threading.Thread(target=bridge.shutdown).start()
bridge.irc_connect()
5 changes: 5 additions & 0 deletions slack_bridge/irc.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ def __init__(self, proxy, channel, nick, name) -> None:
self.client = config.configure()
self.client.subscribe(parser.Message(), self.on_message)

def send(self, msg):
import logging
logging.error(msg)
self.proxy.schedule(self.client.say(self.channel, msg))

async def on_message(self, msg):
# ENDOFNAMES, i.e. we've joined successfully.
if msg.verb == 366:
Expand Down
38 changes: 33 additions & 5 deletions slack_bridge/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

import json
import time
import logging
import sys
import slackclient
Expand All @@ -33,11 +34,13 @@ def dump_response(obj: str):

class SlackBridge(object):

def __init__(self, token: str) -> None:
def __init__(self, proxy, token: str) -> None:
self.client = slackclient.SlackClient(token)
self.proxy = proxy
self.users = self.get_usermap()
self.channels = self.get_channels()
self.channels, self.id_map = self.get_channels()
self.membership = {}
self.connect()

def api(self, method, **kwargs):
data = self.client.api_call(method, **kwargs)
Expand All @@ -46,6 +49,29 @@ def api(self, method, **kwargs):
raise SlackException(data)
return data

def message_loop(self):
while True:
msg = self.client.rtm_read()
if not msg:
time.sleep(0.1)
continue
msg = msg[0]
if msg['type'] == 'message':
if 'user' not in msg:
continue
channel = self.id_map[msg['channel']]
nick = self.users[msg['user']][0]
self.proxy.from_slack(channel, nick, msg)

def connect(self):
if not self.client.rtm_connect():
raise SlackException("Couldn't connect to RTM api.")
msg = None
while not msg:
msg = self.client.rtm_read()
if msg[0] != {'type': 'hello'}:
raise SlackException("Invalid first message: {}".format(msg))

def send(self, channel: str, username: str, text: str):
self.api('chat.postMessage', channel=channel, username=username, text=text, as_user=False)

Expand All @@ -57,8 +83,10 @@ def get_usermap(self):
return users

def get_channels(self):
channels = {}
members = {}
id_map = {}
data = self.api('channels.list')
for channel in data['channels']:
channels[channel['name']] = [self.users[member] for member in channel['members']]
return channels
id_map[channel['id']] = channel['name']
members[channel['name']] = [self.users[member] for member in channel['members']]
return members, id_map

0 comments on commit 5fecf58

Please sign in to comment.