localslackirc/irc.py 0000755 0001750 0001750 00000053005 13624451272 014061 0 ustar salvo salvo #!/usr/bin/env python3
# localslackirc
# Copyright (C) 2018-2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import datetime
from enum import Enum
import re
import select
import socket
import argparse
from typing import *
from os import environ
from os.path import expanduser
from socket import gethostname
import traceback
import slack
import rocket
# How slack expresses mentioning users
_MENTIONS_REGEXP = re.compile(r'<@([0-9A-Za-z]+)>')
_CHANNEL_MENTIONS_REGEXP = re.compile(r'<#[A-Z0-9]+\|([A-Z0-9\-a-z]+)>')
_SLACK_SUBSTITUTIONS = [
('&', '&'),
('>', '>'),
('<', '<'),
]
class Replies(Enum):
RPL_LUSERCLIENT = 251
RPL_UNAWAY = 305
RPL_NOWAWAY = 306
RPL_ENDOFWHO = 315
RPL_LIST = 322
RPL_LISTEND = 323
RPL_CHANNELMODEIS = 324
RPL_TOPIC = 332
RPL_WHOREPLY = 352
RPL_NAMREPLY = 353
RPL_ENDOFNAMES = 366
ERR_NOSUCHCHANNEL = 403
ERR_UNKNOWNCOMMAND = 421
ERR_FILEERROR = 424
ERR_ERRONEUSNICKNAME = 432
class Provider(Enum):
SLACK = 0
ROCKETCHAT = 1
#: Inactivity days to hide a MPIM
MPIM_HIDE_DELAY = datetime.timedelta(days=50)
class Client:
def __init__(self, s, sl_client, nouserlist: bool, autojoin: bool, provider: Provider):
self.nick = b''
self.username = b''
self.realname = b''
self.parted_channels: Set[bytes] = set()
self.hostname = gethostname().encode('utf8')
self.provider = provider
self.s = s
self.sl_client = sl_client
self.nouserlist = nouserlist
self.autojoin = autojoin
if self.provider == Provider.SLACK:
self.substitutions = _SLACK_SUBSTITUTIONS
else:
self.substitutions = []
def _nickhandler(self, cmd: bytes) -> None:
_, nick = cmd.split(b' ', 1)
self.nick = nick.strip()
if self.nick != self.sl_client.login_info.self.name.encode('ascii'):
self._sendreply(Replies.ERR_ERRONEUSNICKNAME, 'Incorrect nickname, use %s' % self.sl_client.login_info.self.name)
def _sendreply(self, code: Union[int,Replies], message: Union[str,bytes], extratokens: List[Union[str,bytes]] = []) -> None:
codeint = code if isinstance(code, int) else code.value
bytemsg = message if isinstance(message, bytes) else message.encode('utf8')
extratokens = list(extratokens)
extratokens.insert(0, self.nick)
self.s.send(b':%s %03d %s :%s\n' % (
self.hostname,
codeint,
b' '.join(i if isinstance(i, bytes) else i.encode('utf8') for i in extratokens),
bytemsg,
))
def _userhandler(self, cmd: bytes) -> None:
#TODO USER salvo 8 * :Salvatore Tomaselli
self._sendreply(1, 'Welcome to localslackirc')
self._sendreply(2, 'Your team name is: %s' % self.sl_client.login_info.team.name)
self._sendreply(2, 'Your team domain is: %s' % self.sl_client.login_info.team.domain)
self._sendreply(2, 'Your nickname must be: %s' % self.sl_client.login_info.self.name)
self._sendreply(Replies.RPL_LUSERCLIENT, 'There are 1 users and 0 services on 1 server')
if self.autojoin and not self.nouserlist:
# We're about to load many users for each chan; instead of requesting each
# profile on its own, batch load the full directory.
self.sl_client.prefetch_users()
if self.autojoin:
mpim_cutoff = datetime.datetime.utcnow() - MPIM_HIDE_DELAY
for sl_chan in self.sl_client.channels():
if not sl_chan.is_member:
continue
if sl_chan.is_mpim and (sl_chan.latest is None or sl_chan.latest.timestamp < mpim_cutoff):
continue
channel_name = '#%s' % sl_chan.name_normalized
self._send_chan_info(channel_name.encode('utf-8'), sl_chan)
else:
for sl_chan in self.sl_client.channels():
channel_name = '#%s' % sl_chan.name_normalized
self.parted_channels.add(channel_name.encode('utf-8'))
def _pinghandler(self, cmd: bytes) -> None:
_, lbl = cmd.split(b' ', 1)
self.s.send(b':%s PONG %s %s\n' % (self.hostname, self.hostname, lbl))
def _joinhandler(self, cmd: bytes) -> None:
_, channel_name = cmd.split(b' ', 1)
if channel_name in self.parted_channels:
self.parted_channels.remove(channel_name)
try:
slchan = self.sl_client.get_channel_by_name(channel_name[1:].decode())
except:
return
self._send_chan_info(channel_name, slchan)
def _send_chan_info(self, channel_name: bytes, slchan: slack.Channel):
if not self.nouserlist:
userlist = [] # type List[bytes]
for i in self.sl_client.get_members(slchan.id):
try:
u = self.sl_client.get_user(i)
except:
continue
if u.deleted:
# Disabled user, skip it
continue
name = u.name.encode('utf8')
prefix = b'@' if u.is_admin else b''
userlist.append(prefix + name)
users = b' '.join(userlist)
self.s.send(b':%s!salvo@127.0.0.1 JOIN %s\n' % (self.nick, channel_name))
self._sendreply(Replies.RPL_TOPIC, slchan.real_topic, [channel_name])
self._sendreply(Replies.RPL_NAMREPLY, b'' if self.nouserlist else users, ['=', channel_name])
self._sendreply(Replies.RPL_ENDOFNAMES, 'End of NAMES list', [channel_name])
def _privmsghandler(self, cmd: bytes) -> None:
_, dest, msg = cmd.split(b' ', 2)
if msg.startswith(b':'):
msg = msg[1:]
# Handle sending "/me does something"
# b'PRIVMSG #much_private :\x01ACTION saluta tutti\x01'
if msg.startswith(b'\x01ACTION ') and msg.endswith(b'\x01'):
action = True
_, msg = msg.split(b' ', 1)
msg = msg[:-1]
else:
action = False
message = self._addmagic(msg.decode('utf8'))
if dest.startswith(b'#'):
self.sl_client.send_message(
self.sl_client.get_channel_by_name(dest[1:].decode()).id,
message,
action,
)
else:
try:
self.sl_client.send_message_to_user(
self.sl_client.get_user_by_name(dest.decode()).id,
message,
action,
)
except:
print('Impossible to find user ', dest)
def _listhandler(self, cmd: bytes) -> None:
for c in self.sl_client.channels():
self._sendreply(Replies.RPL_LIST, c.real_topic, ['#' + c.name, str(c.num_members)])
self._sendreply(Replies.RPL_LISTEND, 'End of LIST')
def _modehandler(self, cmd: bytes) -> None:
params = cmd.split(b' ', 2)
self._sendreply(Replies.RPL_CHANNELMODEIS, '', [params[1], '+'])
def _sendfilehandler(self, cmd: bytes) -> None:
#/sendfile #destination filename
params = cmd.split(b' ', 2)
try:
channel_name = params[1].decode('utf8')
filename = params[2].decode('utf8')
except IndexError:
self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /sendreply #channel filename')
return
try:
if channel_name.startswith('#'):
dest = self.sl_client.get_channel_by_name(channel_name[1:]).id
else:
dest = self.sl_client.get_user_by_name(channel_name).id
except KeyError:
self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find destination: {channel_name}')
return
try:
self.sl_client.send_file(dest, filename)
self._sendreply(0, 'Upload of %s completed' % filename)
except Exception as e:
self._sendreply(Replies.ERR_FILEERROR, f'Unable to send file {e}')
def _parthandler(self, cmd: bytes) -> None:
_, name = cmd.split(b' ', 1)
self.parted_channels.add(name)
def _awayhandler(self, cmd: bytes) -> None:
is_away = b' ' in cmd
self.sl_client.away(is_away)
response = Replies.RPL_NOWAWAY if is_away else Replies.RPL_UNAWAY
self._sendreply(response, 'Away status changed')
def _topichandler(self, cmd: bytes) -> None:
_, channel, topic = cmd.split(b' ', 2)
channel = self.sl_client.get_channel_by_name(channel.decode()[1:])
self.sl_client.topic(channel, topic.decode()[1:])
def _kickhandler(self, cmd: bytes) -> None:
_, channel, username, message = cmd.split(b' ', 3)
channel = self.sl_client.get_channel_by_name(channel.decode()[1:])
user = self.sl_client.get_user_by_name(username.decode())
try:
self.sl_client.kick(channel, user)
except Exception as e:
self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e)
def _invitehandler(self, cmd: bytes) -> None:
_, username, channel = cmd.split(b' ', 2)
channel = self.sl_client.get_channel_by_name(channel.decode()[1:])
user = self.sl_client.get_user_by_name(username.decode())
try:
self.sl_client.invite(channel, user)
except Exception as e:
self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e)
def _whohandler(self, cmd: bytes) -> None:
_, name = cmd.split(b' ', 1)
if not name.startswith(b'#'):
print('WHO not supported on ', name)
return
try:
channel = self.sl_client.get_channel_by_name(name.decode()[1:])
except KeyError:
return
for i in self.sl_client.get_members(channel.id):
try:
user = self.sl_client.get_user(i)
self._sendreply(Replies.RPL_WHOREPLY, '0 %s' % user.real_name, [name, user.name, '127.0.0.1', self.hostname, user.name, 'H'])
except:
pass
self._sendreply(Replies.RPL_ENDOFWHO, 'End of WHO list', [name])
def sendmsg(self, from_: bytes, to: bytes, message: bytes) -> None:
self.s.send(b':%s!salvo@127.0.0.1 PRIVMSG %s :%s\n' % (
from_,
to, #private message, or a channel
message,
))
def _addmagic(self, msg: str) -> str:
"""
Adds magic codes and various things to
outgoing messages
"""
for i in self.substitutions:
msg = msg.replace(i[1], i[0])
if self.provider == Provider.SLACK:
msg = msg.replace('@here', '')
msg = msg.replace('@channel', '')
msg = msg.replace('@yell', '')
msg = msg.replace('@shout', '')
msg = msg.replace('@attention', '')
elif self.provider == Provider.ROCKETCHAT:
msg = msg.replace('@yell', '@channel')
msg = msg.replace('@shout', '@channel')
msg = msg.replace('@attention', '@channel')
# Extremely inefficient code to generate mentions
# Just doing them client-side on the receiving end is too mainstream
for username in self.sl_client.get_usernames():
if len(username) < 3: continue
m = re.search(r'\b%s\b' % username, msg)
if m:
if self.provider == Provider.SLACK:
msg = msg[0:m.start()] + '<@%s>' % self.sl_client.get_user_by_name(username).id + msg[m.end():]
elif self.provider == Provider.ROCKETCHAT:
msg = msg[0:m.start()] + f'@{username}' + msg[m.end():]
return msg
def parse_message(self, msg: str) -> Iterator[bytes]:
for i in msg.split('\n'):
if not i:
continue
# Replace all mentions with @user
while True:
mention = _MENTIONS_REGEXP.search(i)
if not mention:
break
i = (
i[0:mention.span()[0]] +
self.sl_client.get_user(mention.groups()[0]).name +
i[mention.span()[1]:]
)
# Replace all channel mentions
if self.provider == Provider.SLACK:
while True:
mention = _CHANNEL_MENTIONS_REGEXP.search(i)
if not mention:
break
i = (
i[0:mention.span()[0]] +
'#' +
mention.groups()[0] +
i[mention.span()[1]:]
)
for s in self.substitutions:
i = i.replace(s[0], s[1])
encoded = i.encode('utf8')
if self.provider == Provider.SLACK:
encoded = encoded.replace(b'', b'yelling [%s]' % self.nick)
encoded = encoded.replace(b'', b'YELLING LOUDER [%s]' % self.nick)
elif self.provider == Provider.ROCKETCHAT:
encoded = encoded.replace(b'@here', b'yelling [%s]' % self.nick)
encoded = encoded.replace(b'@channel', b'YELLING LOUDER [%s]' % self.nick)
yield encoded
def _message(self, sl_ev: Union[slack.Message, slack.MessageDelete, slack.MessageBot, slack.ActionMessage], prefix: str=''):
"""
Sends a message to the irc client
"""
if hasattr(sl_ev, 'user'):
source = self.sl_client.get_user(sl_ev.user).name.encode('utf8') # type: ignore
else:
source = b'bot'
try:
dest = b'#' + self.sl_client.get_channel(sl_ev.channel).name.encode('utf8')
except KeyError:
dest = self.nick
except Exception as e:
print('Error: ', str(e))
return
if dest in self.parted_channels:
# Ignoring messages, channel was left on IRC
return
for msg in self.parse_message(prefix + sl_ev.text):
if isinstance(sl_ev, slack.ActionMessage):
msg = b'\x01ACTION ' + msg + b'\x01'
self.sendmsg(
source,
dest,
msg
)
def _joined_parted(self, sl_ev: Union[slack.Join, slack.Leave], joined: bool) -> None:
"""
Handle join events from slack, by sending a JOIN notification
to IRC.
"""
user = self.sl_client.get_user(sl_ev.user)
if user.deleted:
return
channel = self.sl_client.get_channel(sl_ev.channel)
dest = b'#' + channel.name.encode('utf8')
if dest in self.parted_channels:
return
name = user.name.encode('utf8')
rname = user.real_name.replace(' ', '_').encode('utf8')
if joined:
self.s.send(b':%s!%s@127.0.0.1 JOIN :%s\n' % (name, rname, dest))
else:
self.s.send(b':%s!%s@127.0.0.1 PART %s\n' % (name, rname, dest))
def slack_event(self, sl_ev: slack.SlackEvent) -> None:
if isinstance(sl_ev, slack.MessageDelete):
self._message(sl_ev, '[deleted]')
elif isinstance(sl_ev, slack.Message):
self._message(sl_ev)
elif isinstance(sl_ev, slack.ActionMessage):
self._message(sl_ev)
elif isinstance(sl_ev, slack.MessageEdit):
if sl_ev.is_changed:
self._message(sl_ev.diffmsg)
elif isinstance(sl_ev, slack.MessageBot):
self._message(sl_ev, '[%s]' % sl_ev.username)
elif isinstance(sl_ev, slack.FileShared):
f = self.sl_client.get_file(sl_ev)
self._message(f.announce())
elif isinstance(sl_ev, slack.Join):
self._joined_parted(sl_ev, True)
elif isinstance(sl_ev, slack.Leave):
self._joined_parted(sl_ev, False)
elif isinstance(sl_ev, slack.TopicChange):
self._sendreply(Replies.RPL_TOPIC, sl_ev.topic, ['#' + self.sl_client.get_channel(sl_ev.channel).name])
def command(self, cmd: bytes) -> None:
if b' ' in cmd:
cmdid, _ = cmd.split(b' ', 1)
else:
cmdid = cmd
handlers = {
b'NICK': self._nickhandler,
b'USER': self._userhandler,
b'PING': self._pinghandler,
b'JOIN': self._joinhandler,
b'PRIVMSG': self._privmsghandler,
b'LIST': self._listhandler,
b'WHO': self._whohandler,
b'MODE': self._modehandler,
b'PART': self._parthandler,
b'AWAY': self._awayhandler,
b'TOPIC': self._topichandler,
b'KICK': self._kickhandler,
b'INVITE': self._invitehandler,
b'sendfile': self._sendfilehandler,
#QUIT
#CAP LS
#USERHOST
#Unknown command: b'whois TAMARRO'
}
if cmdid in handlers:
handlers[cmdid](cmd)
else:
self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Unknown command', [cmdid])
print('Unknown command: ', cmd)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', type=int, action='store', dest='port',
default=9007, required=False,
help='set port number')
parser.add_argument('-i', '--ip', type=str, action='store', dest='ip',
default='127.0.0.1', required=False,
help='set ip address')
parser.add_argument('-t', '--tokenfile', type=str, action='store', dest='tokenfile',
default=expanduser('~')+'/.localslackirc',
required=False,
help='set the token file')
parser.add_argument('-u', '--nouserlist', action='store_true',
dest='nouserlist', required=False,
help='don\'t display userlist')
parser.add_argument('-j', '--autojoin', action='store_true',
dest='autojoin', required=False,
help="Automatically join all remote channels")
parser.add_argument('-o', '--override', action='store_true',
dest='overridelocalip', required=False,
help='allow non 127. addresses, this is potentially dangerous')
parser.add_argument('--rc-url', type=str, action='store', dest='rc_url', default=None, required=False,
help='The rocketchat URL. Setting this changes the mode from slack to rocketchat')
args = parser.parse_args()
# Exit if their chosden ip isn't local. User can override with -o if they so dare
if not args.ip.startswith('127') and not args.overridelocalip:
exit('supplied ip isn\'t local\nlocalslackirc has no encryption or ' \
'authentication, it\'s recommended to only allow local connections\n' \
'you can override this with -o')
if 'PORT' in environ:
port = int(environ['PORT'])
else:
port = args.port
if 'TOKEN' in environ:
token = environ['TOKEN']
else:
try:
with open(args.tokenfile) as f:
token = f.readline().strip()
except (FileNotFoundError, PermissionError):
exit(f'Unable to open the token file {args.tokenfile}')
if args.rc_url:
sl_client: Union[slack.Slack, rocket.Rocket] = rocket.Rocket(args.rc_url, token)
provider = Provider.ROCKETCHAT
else:
sl_client = slack.Slack(token)
provider = Provider.SLACK
sl_events = sl_client.events_iter()
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind((args.ip, port))
serversocket.listen(1)
poller = select.poll()
while True:
s, _ = serversocket.accept()
ircclient = Client(s, sl_client, args.nouserlist, args.autojoin, provider)
poller.register(s.fileno(), select.POLLIN)
if sl_client.fileno is not None:
poller.register(sl_client.fileno, select.POLLIN)
# Main loop
timeout = 2
while True:
s_event: List[Tuple[int,int]] = poller.poll(timeout)
sl_event = next(sl_events)
if s_event:
text = s.recv(1024)
if len(text) == 0:
break
#FIXME handle the case when there is more to be read
for i in text.split(b'\n')[:-1]:
i = i.strip()
if i:
ircclient.command(i)
while sl_event:
print(sl_event)
ircclient.slack_event(sl_event)
sl_event = next(sl_events)
if __name__ == '__main__':
while True:
try:
main()
except KeyboardInterrupt:
break
except Exception as e:
traceback.print_last()
pass
localslackirc/diff.py 0000644 0001750 0001750 00000002654 13300240243 014176 0 ustar salvo salvo # localslackirc
# Copyright (C) 2018 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
from itertools import count
def seddiff(a: str, b: str) -> str:
"""
Original string, changed string
This is meant to operate on simple word changes
or similar. Returns the IRC style correction
format.
"""
for prefix in count():
try:
if a[prefix] != b[prefix]:
break
except:
break
for postfix in count(1):
try:
if a[-postfix] != b[-postfix]:
break
except:
break
if prefix < 0:
prefix = 0
postfix -= 1
if postfix == 0:
px = None
else:
px = postfix * -1
return 's/%s/%s/' % (a[prefix:px], b[prefix:px])
localslackirc/slack.py 0000644 0001750 0001750 00000044762 13624451272 014410 0 ustar salvo salvo # localslackirc
# Copyright (C) 2018-2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import datetime
from functools import lru_cache
from time import sleep, time
from typing import *
from slackclient import SlackClient
from typedload import load, dump
from diff import seddiff
USELESS_EVENTS = {
'channel_marked',
'group_marked',
'hello',
'dnd_updated_user',
'reaction_added',
'user_typing',
'file_deleted',
'file_public',
}
def _loadwrapper(value, type_):
try:
return load(value, type_)
except Exception as e:
print(e)
pass
class ResponseException(Exception):
pass
class Response(NamedTuple):
"""
Internally used to parse a response from the API.
"""
ok: bool
headers: Dict[str, str]
ts: Optional[float] = None
class Topic(NamedTuple):
"""
In slack, topic is not just a string, but has other fields.
"""
value: str
class LatestMessage(NamedTuple):
ts: float
@property
def timestamp(self):
return datetime.datetime.utcfromtimestamp(self.ts)
class Channel(NamedTuple):
"""
A channel description.
real_topic tries to use the purpose if the topic is missing
"""
id: str
name_normalized: str
purpose: Topic
topic: Topic
num_members: int = 0
#: Membership: present on channels, not on groups - but True there.
is_member: bool = True
#: Object type. groups have is_group=True, channels is_channel=True
is_channel: bool = False
is_group: bool = False
is_mpim: bool = False
latest: Optional[LatestMessage] = None
@property
def name(self):
return self.name_normalized
@property
def real_topic(self) -> str:
if self.topic.value:
t = self.topic.value
else:
t = self.purpose.value
return t.replace('\n', ' | ')
class Message(NamedTuple):
channel: str # The channel id
user: str # The user id
text: str
class ActionMessage(Message):
pass
class MessageEdit(NamedTuple):
previous: Message
current: Message
@property
def is_changed(self) -> bool:
return self.previous.text != self.current.text
@property
def diffmsg(self) -> Message:
m = dump(self.current)
m['text'] = seddiff(self.previous.text, self.current.text)
return load(m, Message)
class MessageDelete(Message):
pass
class Profile(NamedTuple):
real_name: str = 'noname'
email: Optional[str] = None
status_text: str = ''
is_restricted: bool = False
is_ultra_restricted: bool = False
class File(NamedTuple):
id: str
url_private: str
size: int
user: str
name: Optional[str] = None
title: Optional[str] = None
mimetype: Optional[str] = None
channels: List[str] = list()
groups: List[str] = list()
ims: List[str] = list()
def announce(self) -> Message:
"""
Returns a message to announce this file.
"""
return Message(
channel=(self.channels + self.groups + self.ims).pop(),
user=self.user,
text='[file upload] %s\n%s %d bytes\n%s' % (
self.name,
self.mimetype,
self.size,
self.url_private
)
)
class FileShared(NamedTuple):
file_id: str
user_id: str
ts: float
class MessageBot(NamedTuple):
text: str
username: str
channel: str
bot_id: Optional[str] = None
class User(NamedTuple):
id: str
name: str
profile: Profile
is_admin: bool = False
deleted: bool = False
@property
def real_name(self) -> str:
return self.profile.real_name
class IM(NamedTuple):
id: str
user: str
class Join(NamedTuple):
user: str
channel: str
class Leave(NamedTuple):
user: str
channel: str
class TopicChange(NamedTuple):
topic: str
channel: str
user: str
SlackEvent = Union[
TopicChange,
MessageDelete,
MessageEdit,
Message,
ActionMessage,
MessageBot,
FileShared,
Join,
Leave,
]
class Slack:
def __init__(self, token: str) -> None:
self.client = SlackClient(token)
self._usercache: Dict[str, User] = {}
self._usermapcache: Dict[str, User] = {}
self._imcache: Dict[str, str] = {}
self._get_members_cache: Dict[str, Set[str]] = {}
self._get_members_cache_cursor: Dict[str, Optional[str]] = {}
self._internalevents: List[SlackEvent] = []
self._sent_by_self: Set[float] = set()
def away(self, is_away: bool) -> None:
"""
Forces the aways status or lets slack decide
"""
status = 'away' if is_away else 'auto'
r = self.client.api_call('users.setPresence', presence=status)
response = load(r, Response)
if not response.ok:
raise ResponseException(response)
def topic(self, channel: Channel, topic: str) -> None:
r = self.client.api_call('conversations.setTopic', channel=channel.id, topic=topic)
response = load(r, Response)
if not response.ok:
raise ResponseException(response)
def kick(self, channel: Channel, user: User) -> None:
r = self.client.api_call('conversations.kick', channel=channel.id, user=user.id)
response = load(r, Response)
if not response.ok:
raise ResponseException(response)
def invite(self, channel: Channel, user: Union[User, List[User]]) -> None:
if isinstance(user, User):
ids = user.id
else:
if len(user) > 30:
raise ValueError('No more than 30 users allowed')
ids = ','.join(i.id for i in user)
r = self.client.api_call('conversations.invite', channel=channel.id, users=ids)
response = load(r, Response)
if not response.ok:
raise ResponseException(response)
def get_members(self, id_: str) -> Set[str]:
"""
Returns the list (as a set) of users in a channel.
It performs caching. Every time the function is called, a new batch is
requested, until all the users are cached, and then no new requests
are performed, and the same data is returned.
When events happen, the cache needs to be updated or cleared.
"""
cached = self._get_members_cache.get(id_, set())
cursor = self._get_members_cache_cursor.get(id_)
if cursor == '':
# The cursor is fully iterated
return cached
kwargs = {}
if cursor:
kwargs['cursor'] = cursor
r = self.client.api_call('conversations.members', channel=id_, limit=5000, **kwargs) # type: ignore
response = load(r, Response)
if not response.ok:
raise ResponseException(response)
newusers = load(r['members'], Set[str])
# Generate all the Join events, if this is not the 1st iteration
if id_ in self._get_members_cache:
for i in newusers.difference(cached):
self._internalevents.append(Join(user=i, channel=id_))
self._get_members_cache[id_] = cached.union(newusers)
self._get_members_cache_cursor[id_] = r.get('response_metadata', {}).get('next_cursor')
return self._get_members_cache[id_]
@lru_cache()
def channels(self) -> List[Channel]:
"""
Returns the list of slack channels
"""
result: List[Channel] = []
r = self.client.api_call("conversations.list", exclude_archived=True,
types='public_channel,private_channel,mpim', limit=1000)
response = load(r, Response)
if response.ok:
return load(r['channels'], List[Channel])
else:
raise ResponseException(response)
@lru_cache()
def get_channel(self, id_: str) -> Channel:
"""
Returns a channel object from a slack channel id
raises KeyError if it doesn't exist.
"""
for c in self.channels():
if c.id == id_:
return c
raise KeyError()
@lru_cache()
def get_channel_by_name(self, name: str) -> Channel:
"""
Returns a channel object from a slack channel id
raises KeyError if it doesn't exist.
"""
for c in self.channels():
if c.name == name:
return c
raise KeyError()
@property
def fileno(self) -> Optional[int]:
return self.client.fileno
def get_im(self, im_id: str) -> Optional[IM]:
if not im_id.startswith('D'):
return None
for uid, imid in self._imcache.items():
if im_id == imid:
return IM(user=uid, id=imid)
for im in self.get_ims():
self._imcache[im.user] = im.id
if im.id == im_id:
return im;
return None
def get_ims(self) -> List[IM]:
"""
Returns a list of the IMs
Some bullshit slack invented because 1 to 1 conversations
need to have an ID to send to, you can't send directly to
a user.
"""
r = self.client.api_call(
"conversations.list",
exclude_archived=True,
types='im', limit=1000
)
response = load(r, Response)
if response.ok:
return load(r['channels'], List[IM])
raise ResponseException(response)
def get_user_by_name(self, name: str) -> User:
return self._usermapcache[name]
def get_usernames(self) -> List[str]:
return list(self._usermapcache.keys())
def prefetch_users(self) -> None:
"""
Prefetch all team members for the slack team.
"""
r = self.client.api_call("users.list")
response = load(r, Response)
if response.ok:
for user in load(r['members'], List[User]):
self._usercache[user.id] = user
self._usermapcache[user.name] = user
def get_user(self, id_: str) -> User:
"""
Returns a user object from a slack user id
raises KeyError if it does not exist
"""
if id_ in self._usercache:
return self._usercache[id_]
r = self.client.api_call("users.info", user=id_)
response = load(r, Response)
if response.ok:
u = load(r['user'], User)
self._usercache[id_] = u
self._usermapcache[u.name] = u
return u
else:
raise KeyError(response)
def get_file(self, f: Union[FileShared, str]) -> File:
"""
Returns a file object
"""
fileid = f if isinstance(f, str) else f.file_id
r = self.client.api_call("files.info", file=fileid)
response = load(r, Response)
if response.ok:
return load(r['file'], File)
else:
raise KeyError(response)
def send_file(self, channel_id: str, filename: str) -> None:
"""
Send a file to a channel or group or whatever
"""
with open(filename, 'rb') as f:
files = {'file': f}
r = self.client.api_call(
'files.upload',
channels=channel_id,
files=files,
)
response = load(r, Response)
if response.ok:
return
raise ResponseException(response)
def _triage_sent_by_self(self) -> None:
"""
Clear all the old leftovers in
_sent_by_self
"""
r = []
for i in self._sent_by_self:
if time() - i >= 10:
r.append(i)
for i in r:
self._sent_by_self.remove(i)
def send_message(self, channel_id: str, msg: str, action: bool) -> None:
"""
Send a message to a channel or group or whatever
"""
if action:
api = 'chat.meMessage'
else:
api = 'chat.postMessage'
r = self.client.api_call(
api,
channel=channel_id,
text=msg,
as_user=True,
)
response = load(r, Response)
if response.ok and response.ts:
self._sent_by_self.add(response.ts)
return
raise ResponseException(response)
def send_message_to_user(self, user_id: str, msg: str, action: bool):
"""
Send a message to a user, pass the user id
"""
# 1 to 1 chats are like channels, but use a dedicated API,
# so to deliver a message to them, a channel id is required.
# Those are called IM.
if user_id in self._imcache:
# channel id is cached
channel_id = self._imcache[user_id]
else:
# Find the channel id
found = False
# Iterate over all the existing conversations
for i in self.get_ims():
if i.user == user_id:
channel_id = i.id
found = True
break
# A conversation does not exist, create one
if not found:
r = self.client.api_call(
"im.open",
return_im=True,
user=user_id,
)
response = load(r, Response)
if not response.ok:
raise ResponseException(response)
channel_id = r['channel']['id']
self._imcache[user_id] = channel_id
self.send_message(channel_id, msg, action)
def events_iter(self) -> Iterator[Optional[SlackEvent]]:
"""
This yields an event or None. Don't call it without sleeps
"""
sleeptime = 1
while True:
while self._internalevents:
yield self._internalevents.pop()
try:
events = self.client.rtm_read()
except:
print('Connecting to slack...')
try:
self.login_info = self.client.rtm_connect()
sleeptime = 1
except Exception as e:
print(f'Connection to slack failed {e}')
sleep(sleeptime)
if sleeptime <= 120: # max reconnection interval at 2 minutes
sleeptime *= 2
continue
print('Connected to slack')
continue
for event in events:
t = event.get('type')
subt = event.get('subtype')
ts = float(event.get('ts', 0))
if ts in self._sent_by_self:
self._sent_by_self.remove(ts)
continue
try:
if t == 'message' and (not subt or subt == 'me_message'):
msg = _loadwrapper(event, Message)
# In private chats, pretend that my own messages
# sent from another client actually come from
# the other user, and prepend them with "I say: "
im = self.get_im(msg.channel)
if im and im.user != msg.user:
msg = Message(user=im.user, text='I say: ' + msg.text, channel=im.id)
if subt == 'me_message':
yield ActionMessage(*msg)
else:
yield msg
elif t == 'message' and subt == 'slackbot_response':
yield _loadwrapper(event, Message)
elif t == 'message' and subt == 'message_changed':
event['message']['channel'] = event['channel']
event['previous_message']['channel'] = event['channel']
yield MessageEdit(
previous=load(event['previous_message'], Message),
current=load(event['message'], Message)
)
elif t == 'message' and subt == 'group_topic':
yield _loadwrapper(event, TopicChange)
elif t == 'message' and subt == 'message_deleted':
event['previous_message']['channel'] = event['channel']
ev = _loadwrapper(event['previous_message'], MessageDelete)
if ev.text: # deleting files generates empty MessageDelete events
yield ev
elif t == 'message' and subt == 'bot_message':
yield _loadwrapper(event, MessageBot)
elif t == 'member_joined_channel':
j = _loadwrapper(event, Join)
self._get_members_cache[j.channel].add(j.user)
yield j
elif t == 'member_left_channel':
j = _loadwrapper(event, Leave)
self._get_members_cache[j.channel].remove(j.user)
yield j
elif t == 'user_change':
# Changes in the user, drop it from cache
u = load(event['user'], User)
if u.id in self._usercache:
del self._usercache[u.id]
#FIXME don't know if it is wise, maybe it gets lost forever del self._usermapcache[u.name]
#TODO make an event for this
elif t == 'file_shared':
try: # slack idiocy workaround, they send the event twice, one time without the ts field
yield _loadwrapper(event, FileShared)
except ValueError:
pass
elif t in USELESS_EVENTS:
continue
else:
print(event)
except Exception as e:
print('Exception: %s' % e)
self._triage_sent_by_self()
yield None
localslackirc/rocket.py 0000644 0001750 0001750 00000030067 13624451272 014573 0 ustar salvo salvo # localslackirc
# Copyright (C) 2018-2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
import json
from functools import lru_cache
from ssl import SSLWantReadError
from enum import Enum
from time import sleep, monotonic
from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple, Union, Iterator
import uuid
from websocket import create_connection, WebSocket
from websocket._exceptions import WebSocketConnectionClosedException
import typedload.dataloader
from slack import Channel, File, FileShared, IM, Message, MessageEdit, Profile, SlackEvent, Topic, User
from slackclient.client import Team, Self, LoginInfo
CALL_TIMEOUT = 10
class ChannelType(Enum):
CHANNEL = 'p'
QUERY = 'd'
PUBLIC_CHANNEL = 'c'
class ChannelUser(NamedTuple):
id_: str
username: str
name: str = 'noname'
status: str = 'auto'
class ChannelUsers(NamedTuple):
total: int
records: List[ChannelUser]
class DirectChannel(NamedTuple):
rid: str
class Rocket:
def __init__(self, url: str, token: str) -> None:
self.url = url
self.token = token
self._call_id = 100
self._internalevents: List[Dict[str, Any]] = []
self._channels: List[Channel] = []
self._users: Dict[str, User] = {}
self._id_prefix = 'lsi' + str(uuid.uuid1()) + '_'
# WORKAROUND
# The NamedTuple module can't have a field called _id, so I rename it to id_
self.loader = typedload.dataloader.Loader()
index = self.loader.index(ChannelUsers)
_original_handler = self.loader.handlers[index][1]
def _namedtuplehandler(l: typedload.dataloader.Loader, d, t):
if '_id' in d:
d['id_'] = d['_id']
del d['_id']
return _original_handler(l, d, t)
self.loader.handlers[index] = (self.loader.handlers[index][0], _namedtuplehandler)
self._connect()
@property
def login_info(self):
#TODO
return LoginInfo(
team=Team(
id='',
name='',
domain='',
),
self=Self(
id='',
name='LtWorf',
),
)
def _update_channels(self) -> None:
data: Optional[List[Dict[str, Any]]] = self._call('rooms/get', [], True)
if not data:
raise Exception('No channel list was returned')
self._channels.clear()
for i in data:
# Subscribe to it
self._subscribe('stream-room-messages', [
i['_id'],
{
'useCollection': False,
'args':[]
}
]
)
# If it's a real channel
channel_type = ChannelType(i.get('t'))
if channel_type == ChannelType.CHANNEL:
self._channels.append(Channel(
id=i['_id'],
name_normalized=i['fname'],
purpose=Topic(i.get('topic', '')),
topic=Topic(i.get('topic', '')),
))
elif channel_type == ChannelType.PUBLIC_CHANNEL:
self._channels.append(Channel(
id=i['_id'],
name_normalized=i['name'],
purpose=Topic(i.get('topic', '')),
topic=Topic(i.get('topic', '')),
))
elif channel_type == ChannelType.QUERY:
pass
else:
print('Unknown data %s' % repr(i))
def _send_json(self, data: Dict[str, Any]) -> None:
"""
Sends something raw over the websocket (normally a dictionary)
"""
self._websocket.send(json.dumps(data).encode('utf8'))
def _connect(self) -> None:
'''
Create the websocket
login
and update channels
'''
self._websocket = create_connection(self.url)
self._websocket.sock.setblocking(0)
self._send_json(
{
'msg': 'connect',
'version': '1',
'support': ['1']
}
)
self._call('login', [{"resume": self.token}], False)
self._update_channels()
def _subscribe(self, name: str, params: List[Any]) -> bool:
self._call_id += 1
self._send_json(
{
'id': str(self._call_id),
'msg': 'sub',
'name': name,
'params': params,
}
)
initial = monotonic()
while initial + CALL_TIMEOUT > monotonic():
r = self._read(subs_id=str(self._call_id))
if r:
if r.get('msg') == 'ready':
return True
return False
sleep(0.05)
raise TimeoutError()
def _call(self, method: str, params: List[Any], wait_return: bool) -> Optional[Any]:
"""
Does a remote call.
if wait_return is true, it will wait for the response and
return it. Otherwise the response will be ignored.
"""
self._call_id += 1
data = {
'msg':'method',
'method': method,
'params': params,
'id': str(self._call_id),
}
self._send_json(data)
if wait_return:
initial = monotonic()
while initial + CALL_TIMEOUT > monotonic():
r = self._read(str(self._call_id))
if r:
return r
sleep(0.05)
raise TimeoutError()
else:
return None
def topic(self, channel: Channel, topic: str) -> None:
raise NotImplemented()
def kick(self, channel: Channel, user: User) -> None:
raise NotImplemented()
def away(self, is_away: bool) -> None:
raise NotImplemented()
def invite(self, channel: Channel, user: Union[User, List[User]]) -> None:
raise NotImplemented()
@lru_cache()
def get_members(self, id_: str) -> Set[str]:
data = self.loader.load(self._call('getUsersOfRoom', [id_, True], True), ChannelUsers)
for i in data.records:
if i.id_ not in self._users:
self._users[i.id_] = User(
id=i.id_,
name=i.username,
profile=Profile(real_name=i.name),
)
return {i.id_ for i in data.records}
def channels(self) -> List[Channel]:
return self._channels
def get_channel(self, id_: str) -> Channel:
for i in self._channels:
if i.id == id_:
return i
raise KeyError()
def get_channel_by_name(self, name: str) -> Channel:
for i in self._channels:
if i.name == name:
return i
raise KeyError()
def get_ims(self) -> List[IM]:
raise NotImplemented()
def get_user_by_name(self, name: str) -> User:
for i in self._users.values():
if i.name == name:
return i
raise KeyError()
def get_usernames(self) -> List[str]:
names = set()
for i in self._users.values():
names.add(i.name)
return list(names)
def prefetch_users(self) -> None:
pass
def get_user(self, id_: str) -> User:
return self._users[id_]
def get_file(self, f: Union[FileShared, str]) -> File:
raise NotImplemented()
def send_file(self, channel_id: str, filename: str) -> None:
raise NotImplemented()
def send_message(self, channel_id: str, msg: str, action: bool) -> None:
self._call_id += 1
self._call('sendMessage', [
{
'_id': self._id_prefix + str(uuid.uuid1()),
'msg': msg,
'rid': channel_id,
}
], False)
def send_message_to_user(self, user_id: str, msg: str, action: bool):
self._call_id += 1
u = self.get_user(user_id)
data = self.loader.load(self._call('createDirectMessage', [u.name], True), DirectChannel)
self.send_message(data.rid, msg, action)
@property
def fileno(self) -> Optional[int]:
return self._websocket.fileno()
def _read(self, event_id: Optional[str] = None, subs_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
try:
_, raw_data = self._websocket.recv_data()
if raw_data == b'\x03\xe8Normal closure':
print('Server triggered a disconnect. Reaconnecting')
raise Exception('Trigger reconnect')
except SSLWantReadError:
return None
except:
self._connect()
return None
try:
data = json.loads(raw_data)
except:
print(f'Failed to decode json: {repr(raw_data)}')
raise
# Handle the stupid ping thing directly here
if data == {'msg': 'ping'}:
self._send_json({'msg': 'pong'})
return None
# Search for results of function calls
if data is not None and (event_id is not None or subs_id is not None):
if data.get('msg') == 'result' and data.get('id') == event_id:
return data.get('result')
elif data.get('subs') == [subs_id]:
return data
else:
# Not the needed item, append it there so it will be returned by the iterator later
self._internalevents.append(data)
return None
else:
return data
def events_iter(self) -> Iterator[Optional[SlackEvent]]:
while True:
if self._internalevents:
data: Optional[Dict[str, Any]] = self._internalevents.pop()
else:
data = self._read()
if not data:
yield None
continue
r: Optional[SlackEvent] = None
print('Scanning ', data)
if not isinstance(data, dict):
continue
# Skip stuff sent by this client
try:
if data['fields']['args'][0]['_id'].startswith(self._id_prefix):
continue
except:
pass
if data.get('msg') == 'changed' and data.get('collection') == 'stream-room-messages': # New message
try:
# If the sender is unknown, add it
if data['fields']['args'][0]['u']['_id'] not in self._users:
self._users[data['fields']['args'][0]['u']['_id']] = User(
id=data['fields']['args'][0]['u']['_id'],
name=data['fields']['args'][0]['u']['username'],
profile=Profile(real_name='noname'),
)
r = Message(
channel=data['fields']['args'][0]['rid'],
user=data['fields']['args'][0]['u']['_id'],
text=data['fields']['args'][0]['msg'],
)
if 'editedBy' in data['fields']['args'][0]:
r = MessageEdit(
previous=Message(channel=r.channel, user=r.user, text=''),
current=r
)
except:
pass
if r is None:
print('Not handled: ', data)
else:
yield r
localslackirc/slackclient/__init__.py 0000644 0001750 0001750 00000000040 13332572553 017325 0 ustar salvo salvo from .client import SlackClient
localslackirc/slackclient/client.py 0000644 0001750 0001750 00000016657 13562070725 017070 0 ustar salvo salvo # localslackirc
# Copyright (C) 2018 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
# This file was part of python-slackclient
# (https://github.com/slackapi/python-slackclient)
# But has been copied and relicensed under GPL. The copyright applies only
# to the changes made since it was copied.
from .exceptions import *
import json
from typing import Any, Dict, List, NamedTuple, Optional
from requests.packages.urllib3.util.url import parse_url
import requests
from ssl import SSLWantReadError
from typedload import load
from websocket import create_connection, WebSocket
from websocket._exceptions import WebSocketConnectionClosedException
class SlackRequest:
def __init__(self, proxies: Optional[Dict[str,str]] = None) -> None:
self.proxies = proxies
def do(self, token: str, request: str, post_data: Dict[str,str], timeout: Optional[float], files: Optional[Dict]):
"""
Perform a POST request to the Slack Web API
Args:
token (str): your authentication token
request (str): the method to call from the Slack API. For example: 'channels.list'
timeout (float): stop waiting for a response after a given number of seconds
post_data (dict): key/value arguments to pass for the request. For example:
{'channel': 'CABC12345'}
"""
domain = "slack.com"
url = f'https://{domain}/api/{request}'
# Set user-agent and auth headers
headers = {
'user-agent': 'localslackirc',
'Authorization': f'Bearer {token}'
}
# Submit the request
return requests.post(
url,
headers=headers,
data=post_data,
timeout=timeout,
files=files,
proxies=self.proxies
)
class Team(NamedTuple):
id: str
name: str
domain: str
class Self(NamedTuple):
id: str
name: str
class LoginInfo(NamedTuple):
team: Team
self: Self
class SlackClient:
"""
The SlackClient object owns the websocket connection and all attached channel information.
"""
def __init__(self, token: str, proxies: Optional[Dict[str,str]] = None) -> None:
# Slack client configs
self._token = token
self._proxies = proxies
self._api_requester = SlackRequest(proxies=proxies)
# RTM configs
self._websocket: Optional[WebSocket] = None
@property
def fileno(self) -> Optional[int]:
if self._websocket is not None:
return self._websocket.fileno()
return None
def rtm_connect(self, timeout: Optional[int] = None, **kwargs) -> LoginInfo:
"""
Connects to the RTM API - https://api.slack.com/rtm
:Args:
timeout: in seconds
"""
# rtm.start returns user and channel info, rtm.connect does not.
connect_method = "rtm.connect"
reply = self._api_requester.do(self._token, connect_method, timeout=timeout, post_data=kwargs, files=None)
if reply.status_code != 200:
raise SlackConnectionError("RTM connection attempt failed")
login_data = reply.json()
if login_data["ok"]:
self._connect_slack_websocket(login_data['url'])
return load(login_data, LoginInfo)
else:
raise SlackLoginError(reply=reply)
def _connect_slack_websocket(self, ws_url):
"""Uses http proxy if available"""
if self._proxies and 'http' in self._proxies:
parts = parse_url(self._proxies['http'])
proxy_host, proxy_port = parts.host, parts.port
auth = parts.auth
proxy_auth = auth and auth.split(':')
else:
proxy_auth, proxy_port, proxy_host = None, None, None
try:
self._websocket = create_connection(ws_url,
http_proxy_host=proxy_host,
http_proxy_port=proxy_port,
http_proxy_auth=proxy_auth)
self._websocket.sock.setblocking(0) # type: ignore
except Exception as e:
raise SlackConnectionError(message=str(e))
def _websocket_read(self) -> str:
"""
Returns data if available, otherwise ''. Newlines indicate multiple
messages
"""
if self._websocket is None:
raise SlackConnectionError("Unable to send due to closed RTM websocket")
data = ''
while True:
try:
data += "{0}\n".format(self._websocket.recv())
except SSLWantReadError:
# errno 2 occurs when trying to read or write data, but more
# data needs to be received on the underlying TCP transport
# before the request can be fulfilled.
#
# Python 2.7.9+ and Python 3.3+ give this its own exception,
# SSLWantReadError
return ''
except WebSocketConnectionClosedException:
raise SlackConnectionError("Unable to send due to closed RTM websocket")
return data.rstrip()
def api_call(self, method: str, timeout: Optional[float] = None, **kwargs) -> Dict[str, Any]:
"""
Call the Slack Web API as documented here: https://api.slack.com/web
:Args:
method (str): The API Method to call. See here for a list: https://api.slack.com/methods
:Kwargs:
(optional) timeout: stop waiting for a response after a given number of seconds
(optional) kwargs: any arguments passed here will be bundled and sent to the api
requester as post_data
and will be passed along to the API.
Example::
sc.server.api_call(
"channels.setPurpose",
channel="CABC12345",
purpose="Writing some code!"
)
Returns:
str -- returns HTTP response text and headers as JSON.
Examples::
u'{"ok":true,"purpose":"Testing bots"}'
or
u'{"ok":false,"error":"channel_not_found"}'
See here for more information on responses: https://api.slack.com/web
"""
if 'files' in kwargs:
files = kwargs.pop('files')
else:
files = None
response = self._api_requester.do(self._token, method, kwargs, timeout, files)
response_json = json.loads(response.text)
response_json["headers"] = dict(response.headers)
return response_json
def rtm_read(self) -> List[Dict[str, Any]]:
json_data = self._websocket_read()
data = []
if json_data != '':
for d in json_data.split('\n'):
data.append(json.loads(d))
return data
localslackirc/slackclient/exceptions.py 0000644 0001750 0001750 00000003025 13335506000 017740 0 ustar salvo salvo # localslackirc
# Copyright (C) 2018 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
# author Salvo "LtWorf" Tomaselli
#
# This file was part of python-slackclient
# (https://github.com/slackapi/python-slackclient)
# But has been copied and relicensed under GPL. The copyright applies only
# to the changes made since it was copied.
class SlackClientError(Exception):
"""
Base exception for all errors raised by the SlackClient library
"""
def __init__(self, msg: str) -> None:
super(SlackClientError, self).__init__(msg)
class SlackConnectionError(SlackClientError):
def __init__(self, message='', reply=None) -> None:
super(SlackConnectionError, self).__init__(message)
self.reply = reply
class SlackLoginError(SlackClientError):
def __init__(self, message='', reply=None) -> None:
super(SlackLoginError, self).__init__(message)
self.reply = reply
localslackirc/Makefile 0000644 0001750 0001750 00000004204 13537754612 014373 0 ustar salvo salvo all:
@echo Nothing to do
.PHONY: lint
lint:
MYPYPATH=stubs mypy --config-file mypy.conf irc.py
.PHONY: test
test: lint
.PHONY: install
install:
#Install slackclient
install -d $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
install -m644 slackclient/exceptions.py $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
install -m644 slackclient/client.py $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
install -m644 slackclient/__init__.py $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
# Install files from the root dir
install -m644 diff.py $${DESTDIR:-/}/usr/share/localslackirc/
install -m644 slack.py $${DESTDIR:-/}/usr/share/localslackirc/
install -m644 rocket.py $${DESTDIR:-/}/usr/share/localslackirc/
install irc.py $${DESTDIR:-/}/usr/share/localslackirc/
# Install command
install -d $${DESTDIR:-/}/usr/bin/
ln -s ../share/localslackirc/irc.py $${DESTDIR:-/}/usr/bin/localslackirc
# install extras
install -m644 -D CHANGELOG $${DESTDIR:-/}/usr/share/doc/localslackirc/CHANGELOG
install -m644 -D README.md $${DESTDIR:-/}/usr/share/doc/localslackirc/README.md
install -m644 -D man/localslackirc.1 $${DESTDIR:-/}/usr/share/man/man1/localslackirc.1
.PHONY: dist
dist:
cd ..; tar -czvvf localslackirc.tar.gz \
localslackirc/irc.py \
localslackirc/diff.py \
localslackirc/slack.py \
localslackirc/rocket.py \
localslackirc/slackclient/__init__.py \
localslackirc/slackclient/client.py \
localslackirc/slackclient/exceptions.py \
localslackirc/Makefile \
localslackirc/CHANGELOG \
localslackirc/LICENSE \
localslackirc/README.md \
localslackirc/requirements.txt \
localslackirc/docker/Dockerfile \
localslackirc/man \
localslackirc/mypy.conf \
localslackirc/stubs/
mv ../localslackirc.tar.gz localslackirc_`head -1 CHANGELOG`.orig.tar.gz
gpg --detach-sign -a *.orig.tar.gz
deb-pkg: dist
mv localslackirc_`head -1 CHANGELOG`.orig.tar.gz* /tmp
cd /tmp; tar -xf localslackirc*.orig.tar.gz
cp -r debian /tmp/localslackirc/
cd /tmp/localslackirc/; dpkg-buildpackage --changes-option=-S
install -d deb-pkg
mv /tmp/localslackirc_* deb-pkg
$(RM) -r /tmp/localslackirc
.PHONY: clean
clean:
$(RM) -r deb-pkg
localslackirc/CHANGELOG 0000644 0001750 0001750 00000001203 13624451272 014132 0 ustar salvo salvo 1.6
* Useless release because of mypy
1.5
* Useless release because of mypy
1.4
* Support for /kick
* Support for /invite
* Handle people leaving rooms
1.3
* Experimental support for Rocket.Chat added
* Support for /me
* Support for /topic
* Own messages sent from other clients appear in IRC
1.2
* Initial support for rocketchat
* Fixed issue with messages being shown with a delay
* Notifications for user joins
* Pagination for channels with several users
* Do not hide errors in the main loop
1.1
* Added manpage
* Improved debian packaging
* Force correct IRC nickname
* Send files
* Faster query message send
1.0
* Initial release
localslackirc/LICENSE 0000644 0001750 0001750 00000104513 13264340657 013741 0 ustar salvo salvo GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
localslackirc/README.md 0000644 0001750 0001750 00000011216 13537754612 014213 0 ustar salvo salvo localslackirc
=============
The idea of this project is to create a localhost IRC server that functions as
a gateway for one user of slack, that can connect to it with whatever IRC
client they prefer or a bouncer like ZNC and keep using slack from IRC even
after they shut down their IRC gateway.
Since at my workplace they waited for me to implement all this to decide to
switch to Rocket.Chat (or retard chat, as I like to call it), it now has
support for doing the same thing with Rocket.Chat.
Options to Obtain a Slack token
===============================
* Retrieve a slack token from https://api.slack.com/docs/oauth-test-tokens
Alternatively if this method fails you can get one from Slack's web client
1) Instructions for Chromium
* In your browser, go to "Inspect" (developer mode) on an empty page
* Select the "Network" tab.
* Select WS (WebSockets)
* Open your web slack client
* Copy the 'token' parameter from the WebSocket connection URL. [Picture](https://raw.githubusercontent.com/ltworf/localslackirc/master/doc/token-instructions.png)
2) Instructions for firefox
* In your browser, open the Slack web client
* Press F12 to open the developer tools
* Refresh the page (F5)
* Select the 'Network' tab
* Select the 'WS' tab
* Copy the 'token' parameter from the WebSocket connection URL.
Obtain a Rocket.Chat token
==========================
Look for "Personal Access Tokens" in the settings and generate one there.
You will need to pass your URL, like this `--rc-url wss://rchat.com/websocket`.
Using Token
===========
Your Slack token should be placed inside a file named `.localslackirc` inside your home directory.
Any location works, with the '-t' argument to the desired location. eg: ```python3 irc.py -t /home/me/slack/token.txt```
Using localslackirc
===================
* Start localslackirc by running `python3 irc.py` - you should see a connection message similar to the this:
```
{'ok': True, 'url': 'wss://cerberus-xxxx.lb.slack-msgs.com/websocket/jhvbT8578765JHBfrewgsdy7', 'team': {'id': 'ZZZ789012', 'name': 'Some Team', 'domain': 'someteam'}, 'self': {'id': 'XXX123456', 'name': 'your name'}}
```
* Now point your irc client to localslackirc (127.0.0.1:9007)
* login to localslackirc using your Slack username
* after your connected, list the channels in your irc client and select the ones you want to join.
## Automatically joining channels
To automatically connect to the Slack channels you are in open localslackirc with the -j argument
```python3 irc.py -j```
## Sending files
You can use `/sendfile #destination filepath` to send files. Destination can be a channel or a user.
## Instructions for irssi
If you need to refresh your memory about connecting in general, this is a good guide: https://pthree.org/2010/02/02/irssis-channel-network-server-and-connect-what-it-means/
Here's a list of irssi commands to set up a network and a localhost server:
```
/network add -user -realname "" -nick
/server add -auto -port 9007 -network localhost
/save
```
Then, start localslackirc in your terminal if you haven't already. (Just type `python3 irc.py`).
After localslackirc is running, and you have seen the connection
message seen above, you can just connect to the localhost IRC network
in irssi. Like this:
```
/connect
```
And you should see the following message in your irssi:
```
22:15:35 [] -!- Irssi: Looking up localhost
22:15:35 [] -!- Irssi: Connecting to localhost [127.0.0.1] port 9007
22:15:35 [] -!- Irssi: Connection to localhost established
22:15:36 [] -!- Hi, welcome to IRC
22:15:36 [] -!- Your host is serenity, running version miniircd-1.2.1
22:15:36 [] -!- This server was created sometime
22:15:36 [] -!- serenity miniircd-1.2.1 o o
22:15:36 [] -!- There are 1 users and 0 services on 1 server
...
```
Installing localslackirc
========================
It is packaged for Debian (and Ubuntu), alternatively you can install from sources.
Requirements
------------
* At least Python 3.6
* The modules indicated in `requirements.txt`
Using a docker container to run localslackirc
---------------------------------------------
Inside `docker` directory there is a dockerfile to generate a container that runs `localslackirc`.
In order to use it follow the instructions:
```
# docker build -t localslackirc -f docker/Dockerfile .
```
If everything went fine you should have a new container running localslackirc.
To start your new container:
```
docker run -d -p 9007:9007 --name=mylocalslackirc -e 'SLACKTOKEN=MYSLACKTOKEN' localslackirc
```
IRC Channel
===========
#localslackirc on oftc
localslackirc/requirements.txt 0000644 0001750 0001750 00000000044 13503456214 016203 0 ustar salvo salvo requests
typedload
websocket-client
localslackirc/docker/Dockerfile 0000644 0001750 0001750 00000001553 13503456214 016166 0 ustar salvo salvo FROM alpine:3.6
RUN apk add --no-cache python3 && \
python3 -m ensurepip && \
rm -r /usr/lib/python*/ensurepip && \
pip3 install --upgrade pip setuptools && \
if [ ! -e /usr/bin/pip ]; then ln -s pip3 /usr/bin/pip ; fi && \
if [[ ! -e /usr/bin/python ]]; then ln -sf /usr/bin/python3 /usr/bin/python; fi && \
rm -r /root/.cache
RUN apk --no-cache add ca-certificates && update-ca-certificates
RUN mkdir /localslackirc
RUN mkdir /localslackirc/slackclient
RUN addgroup -S localslackirc
RUN adduser -S localslackirc -G localslackirc
COPY requirements.txt /localslackirc
RUN python3 -m pip install -r /localslackirc/requirements.txt a
COPY *.py /localslackirc/
COPY slackclient/*.py /localslackirc/slackclient/
USER localslackirc
ENTRYPOINT echo ${SLACKTOKEN} > ~/.localslackirc && PYTHONPATH=/localslackirc python3 /localslackirc/irc.py -o -i "0.0.0.0"
localslackirc/man/ 0000755 0001750 0001750 00000000000 13537754612 013506 5 ustar salvo salvo localslackirc/man/localslackirc.1 0000644 0001750 0001750 00000003020 13537754612 016371 0 ustar salvo salvo .TH localslackirc 1 "Jul 29, 2019" "IRC gateway for slack and rocket.chat"
.SH NAME
localslackirc
\- Creates an IRC server running locally, which acts as a gateway to slack or rocket.chat for one user.
.SH SYNOPSIS
localslackirc [OPTIONS]
.SH DESCRIPTION
This command starts an IRC server running on 127.0.0.1:9007 which acts as a gateway to slack or rocket.chat for one user.
.br
To connect to multiple instances it is necessary to run multiple instances of this software.
.TP
While basic support for rocket.chat is present, it lacks several features and is not as good as support for slack.
.SH OPTIONS
.SS
.SS Options:
.TP
.B -h, --help
Show the help message and exit.
.TP
.B -p PORT, --port PORT
Set the port number. The default is 9007.
.TP
.B -i IP, --ip IP
Set the IP (Ipv4 only) address to listen to. The default is 127.0.0.1.
.TP
.B -t TOKENFILE, --tokenfile TOKENFILE
Set the token file. The default is ~/.localslackirc.
.TP
.B -u, --nouserlist
Don't display userlist in the IRC client.
.TP
.B -j, --autojoin
Automatically join all remote channels.
.TP
.B -o, --override
Allow listening on addresses that do not start with 127.*
.br
This is potentially dangerous.
.TP
.B --rc-url RC_URL
The rocket.chat URL.
.br
Setting this changes the mode from slack to rocket.chat.
.SH TOKEN
The access token is (unless specified otherwise) located in ~/.localslackirc, for information on how to obtain your token, check the README file.
.SH WEB
.BR https://github.com/ltworf/localslackirc
.SH AUTHOR
.nf
Salvo "LtWorf" Tomaselli
localslackirc/mypy.conf 0000644 0001750 0001750 00000000223 13311170626 014560 0 ustar salvo salvo [mypy]
python_version=3.6
warn_unused_ignores=True
warn_redundant_casts=True
strict_optional=True
scripts_are_modules=True
check_untyped_defs=True
localslackirc/stubs/ 0000755 0001750 0001750 00000000000 13305323365 014061 5 ustar salvo salvo localslackirc/stubs/websocket/ 0000755 0001750 0001750 00000000000 13562070732 016051 5 ustar salvo salvo localslackirc/stubs/websocket/_exceptions.pyi 0000644 0001750 0001750 00000000071 13305323365 021110 0 ustar salvo salvo class WebSocketConnectionClosedException(Exception): ...
localslackirc/stubs/websocket/__init__.pyi 0000644 0001750 0001750 00000000261 13562070732 020332 0 ustar salvo salvo from typing import *
def create_connection(url, timeout: Optional[int] = None, **kwargs): ...
class WebSocket:
def fileno(self) -> int: ...
def recv(self) -> str: ...