localslackirc/localslackirc0000755000175000017500000000160114122573712015454 0ustar salvosalvo#!/usr/bin/env python3 # localslackirc # Copyright (C) 2021 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 irc import main if __name__ == '__main__': try: main() except KeyboardInterrupt: pass localslackirc/irc.py0000644000175000017500000011503114136567635014066 0ustar salvosalvo# localslackirc # Copyright (C) 2018-2021 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 asyncio import datetime from enum import Enum from pathlib import Path import re import signal import socket import argparse from typing import * import os from os import environ from os.path import expanduser import pwd from socket import gethostname import sys import time try: from emoji import emojize # type: ignore except ModuleNotFoundError: def emojize(string:str, use_aliases:bool=False, delimiters: Tuple[str,str]=(':', ':')) -> str: # type: ignore return string import slack from log import * # How slack expresses mentioning users _MENTIONS_REGEXP = re.compile(r'<@([0-9A-Za-z]+)>') _CHANNEL_MENTIONS_REGEXP = re.compile(r'<#([A-Z0-9]+)\|[_\w-]+>') _URL_REGEXP = re.compile(r'<([a-z0-9\-\.]+)://([^\s\|]+)[\|]{0,1}([^<>]*)>') VERSION = '1.14' _SLACK_SUBSTITUTIONS = [ ('&', '&'), ('>', '>'), ('<', '<'), ] class IrcDisconnectError(Exception): ... class Replies(Enum): RPL_LUSERCLIENT = 251 RPL_USERHOST = 302 RPL_UNAWAY = 305 RPL_NOWAWAY = 306 RPL_WHOISUSER = 311 RPL_WHOISSERVER = 312 RPL_WHOISOPERATOR = 313 RPL_ENDOFWHO = 315 RPL_WHOISIDLE = 317 RPL_ENDOFWHOIS = 318 RPL_WHOISCHANNELS = 319 RPL_LIST = 322 RPL_LISTEND = 323 RPL_CHANNELMODEIS = 324 RPL_TOPIC = 332 RPL_WHOREPLY = 352 RPL_NAMREPLY = 353 RPL_ENDOFNAMES = 366 ERR_NOSUCHNICK = 401 ERR_NOSUCHCHANNEL = 403 ERR_UNKNOWNCOMMAND = 421 ERR_FILEERROR = 424 ERR_ERRONEUSNICKNAME = 432 class Provider(Enum): SLACK = 0 #: Inactivity days to hide a MPIM MPIM_HIDE_DELAY = datetime.timedelta(days=50) class ClientSettings(NamedTuple): nouserlist: bool autojoin: bool provider: Provider ignored_channels: Set[bytes] silenced_yellers: Set[bytes] downloads_directory: Path formatted_max_lines: int = 0 def verify(self) -> Optional[str]: ''' Make sure that the configuration is correct. In that case return None. Otherwise an error string. ''' if not self.downloads_directory.is_dir(): return f'{self.downloads_directory} is not a directory' return None class Client: def __init__( self, s: asyncio.streams.StreamWriter, sl_client: Union[slack.Slack], settings: ClientSettings, ): self.nick = b'' self.username = b'' self.realname = b'' self.parted_channels: Set[bytes] = settings.ignored_channels self.hostname = gethostname().encode('utf8') self.settings = settings self.s = s self.sl_client = sl_client self._usersent = False # Used to hold all events until the IRC client sends the initial USER message self._held_events: List[slack.SlackEvent] = [] self._mentions_regex_cache: Dict[str, Optional[re.Pattern]] = {} # Cache for the regexp to perform mentions. Key is channel id self._annoy_users: Dict[str, int] = {} # Users to annoy pretending to type when they type if self.settings.provider == Provider.SLACK: self.substitutions = _SLACK_SUBSTITUTIONS else: self.substitutions = [] async def _nickhandler(self, cmd: bytes) -> None: if b' ' not in cmd: self.nick = b'localslackirc' else: _, nick = cmd.split(b' ', 1) self.nick = nick.strip() assert self.sl_client.login_info if self.nick != self.sl_client.login_info.self.name.encode('ascii'): await self._sendreply(Replies.ERR_ERRONEUSNICKNAME, 'Incorrect nickname, use %s' % self.sl_client.login_info.self.name) async def _sendreply(self, code: Union[int,Replies], message: Union[str,bytes], extratokens: Iterable[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.write(b':%s %03d %s :%s\r\n' % ( self.hostname, codeint, b' '.join(i if isinstance(i, bytes) else i.encode('utf8') for i in extratokens), bytemsg, )) await self.s.drain() async def _userhandler(self, cmd: bytes) -> None: #TODO USER salvo 8 * :Salvatore Tomaselli assert self.sl_client.login_info await self._sendreply(1, 'Welcome to localslackirc') await self._sendreply(2, 'Your team name is: %s' % self.sl_client.login_info.team.name) await self._sendreply(2, 'Your team domain is: %s' % self.sl_client.login_info.team.domain) await self._sendreply(2, 'Your nickname must be: %s' % self.sl_client.login_info.self.name) await self._sendreply(Replies.RPL_LUSERCLIENT, 'There are 1 users and 0 services on 1 server') if self.settings.autojoin and not self.settings.nouserlist: # We're about to load many users for each chan; instead of requesting each # profile on its own, batch load the full directory. await self.sl_client.prefetch_users() if self.settings.autojoin: mpim_cutoff = datetime.datetime.utcnow() - MPIM_HIDE_DELAY for sl_chan in await 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 channel_name_b = channel_name.encode('ascii') if channel_name_b in self.parted_channels: log(f'Not joining {channel_name} on IRC, marked as parted') continue await self._send_chan_info(channel_name_b, sl_chan) else: for sl_chan in await self.sl_client.channels(): channel_name = '#%s' % sl_chan.name_normalized self.parted_channels.add(channel_name.encode('utf-8')) # Eventual channel joining done, sending the held events self._usersent = True for ev in self._held_events: await self.slack_event(ev) self._held_events = [] async def _pinghandler(self, cmd: bytes) -> None: _, lbl = cmd.split(b' ', 1) self.s.write(b':%s PONG %s %s\r\n' % (self.hostname, self.hostname, lbl)) await self.s.drain() async def _joinhandler(self, cmd: bytes) -> None: _, channel_name_b = cmd.split(b' ', 1) if channel_name_b in self.parted_channels: self.parted_channels.remove(channel_name_b) channel_name = channel_name_b[1:].decode() try: slchan = await self.sl_client.get_channel_by_name(channel_name) except Exception: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find channel: {channel_name}') return if not slchan.is_member: try: await self.sl_client.join(slchan) except Exception: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to join server channel: {channel_name}') try: await self._send_chan_info(channel_name_b, slchan) except Exception: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to join channel: {channel_name}') async def _send_chan_info(self, channel_name: bytes, slchan: slack.Channel): if not self.settings.nouserlist: userlist: List[bytes] = [] for i in await self.sl_client.get_members(slchan.id): try: u = await self.sl_client.get_user(i) except Exception: 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.write(b':%s!%s@127.0.0.1 JOIN %s\r\n' % (self.nick, self.nick, channel_name)) await self.s.drain() await self._sendreply(Replies.RPL_TOPIC, slchan.real_topic, [channel_name]) await self._sendreply(Replies.RPL_NAMREPLY, b'' if self.settings.nouserlist else users, ['=', channel_name]) await self._sendreply(Replies.RPL_ENDOFNAMES, 'End of NAMES list', [channel_name]) async 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 if dest.startswith(b'#'): to_channel = True dest_object: Union[slack.User, slack.Channel] = await self.sl_client.get_channel_by_name(dest[1:].decode()) else: to_channel = False dest_object = await self.sl_client.get_user_by_name(dest.decode()) message = await self._addmagic(msg.decode('utf8'), dest_object) if to_channel: await self.sl_client.send_message( dest_object.id, message, action, ) else: await self.sl_client.send_message_to_user( dest_object.id, message, action, ) async def _listhandler(self, cmd: bytes) -> None: for c in await self.sl_client.channels(refresh=True): await self._sendreply(Replies.RPL_LIST, c.real_topic, ['#' + c.name, str(c.num_members)]) await self._sendreply(Replies.RPL_LISTEND, 'End of LIST') async def _modehandler(self, cmd: bytes) -> None: params = cmd.split(b' ', 2) await self._sendreply(Replies.RPL_CHANNELMODEIS, '', [params[1], '+']) async def _annoyhandler(self, cmd: bytes) -> None: params = cmd.split(b' ') params.pop(0) try: user = params.pop(0).decode('utf8') if params: duration = abs(int(params.pop())) else: duration = 10 # 10 minutes default except Exception: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /annoy user [duration]') return try: user_id = (await self.sl_client.get_user_by_name(user)).id except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find user: {user}') return self._annoy_users[user_id] = int(time.time()) + (duration * 60) await self._sendreply(0, f'Will annoy {user} for {duration} minutes') async 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: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /sendfile #channel filename') return try: if channel_name.startswith('#'): dest = (await self.sl_client.get_channel_by_name(channel_name[1:])).id else: dest = (await self.sl_client.get_user_by_name(channel_name)).id except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find destination: {channel_name}') return try: await self.sl_client.send_file(dest, filename) await self._sendreply(0, 'Upload of %s completed' % filename) except Exception as e: await self._sendreply(Replies.ERR_FILEERROR, f'Unable to send file {e}') async def _parthandler(self, cmd: bytes) -> None: _, name = cmd.split(b' ', 1) self.parted_channels.add(name) async def _awayhandler(self, cmd: bytes) -> None: is_away = b' ' in cmd await self.sl_client.away(is_away) response = Replies.RPL_NOWAWAY if is_away else Replies.RPL_UNAWAY await self._sendreply(response, 'Away status changed') async def _topichandler(self, cmd: bytes) -> None: try: _, channel_b, topic_b = cmd.split(b' ', 2) channel_name = channel_b.decode()[1:] topic = topic_b.decode()[1:] except Exception as e: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e) return try: channel = await self.sl_client.get_channel_by_name(channel_name) except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unknown channel: {channel_name}') return try: await self.sl_client.topic(channel, topic) except Exception: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, f'Unable to set topic to {topic}') async def _whoishandler(self, cmd: bytes) -> None: users = cmd.split(b' ') del users[0] if len(users) != 1: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /whois nickname') return # Seems that oftc only responds to the last one username = users.pop() if b'*' in username: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Wildcards are not supported') return uusername = username.decode() try: user = await self.sl_client.get_user_by_name(uusername) except KeyError: await self._sendreply(Replies.ERR_NOSUCHNICK, f'Unknown user {uusername}') return await self._sendreply(Replies.RPL_WHOISUSER, user.real_name, [username, '', 'localhost']) if user.profile.email: await self._sendreply(Replies.RPL_WHOISUSER, f'email: {user.profile.email}', [username, '', 'localhost']) if user.is_admin: await self._sendreply(Replies.RPL_WHOISOPERATOR, f'{uusername} is an IRC operator', [username]) await self._sendreply(Replies.RPL_ENDOFWHOIS, '', extratokens=[username]) async def _kickhandler(self, cmd: bytes) -> None: try: _, channel_b, username_b, message = cmd.split(b' ', 3) channel_name = channel_b.decode()[1:] username = username_b.decode() except Exception as e: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e) return try: channel = await self.sl_client.get_channel_by_name(channel_name) except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unknown channel: {channel_name}') return try: user = await self.sl_client.get_user_by_name(username) except KeyError: await self._sendreply(Replies.ERR_NOSUCHNICK, f'Unknown user: {username}') return try: await self.sl_client.kick(channel, user) except Exception as e: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e) async def _quithandler(self, cmd: bytes) -> None: raise IrcDisconnectError() async def _userhosthandler(self, cmd: bytes) -> None: nicknames = cmd.split(b' ') del nicknames[0] # Remove the command itself #TODO replace + with - in case of away #TODO append a * to the nickname for OP replies = (b'%s=+unknown' % i for i in nicknames) await self._sendreply(Replies.RPL_USERHOST, '', replies) async def _invitehandler(self, cmd: bytes) -> None: try: _, username_b, channel_b = cmd.split(b' ', 2) username = username_b.decode() channel_name = channel_b.decode()[1:] except Exception as e: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e) return try: channel = await self.sl_client.get_channel_by_name(channel_name) except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unknown channel: {channel_name}') return try: user = await self.sl_client.get_user_by_name(username) except KeyError: await self._sendreply(Replies.ERR_NOSUCHNICK, f'Unknown user: {username}') return try: await self.sl_client.invite(channel, user) except Exception as e: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e) async def _whohandler(self, cmd: bytes) -> None: _, name = cmd.split(b' ', 1) if not name.startswith(b'#'): try: user = await self.sl_client.get_user_by_name(name.decode()) except KeyError: return await self._sendreply(Replies.RPL_WHOREPLY, '0 %s' % user.real_name, [name, user.name, '127.0.0.1', self.hostname, user.name, 'H']) return try: channel = await self.sl_client.get_channel_by_name(name.decode()[1:]) except KeyError: return for i in await self.sl_client.get_members(channel.id): try: user = await self.sl_client.get_user(i) await self._sendreply(Replies.RPL_WHOREPLY, '0 %s' % user.real_name, [name, user.name, '127.0.0.1', self.hostname, user.name, 'H']) except Exception: pass await self._sendreply(Replies.RPL_ENDOFWHO, 'End of WHO list', [name]) async def sendmsg(self, from_: bytes, to: bytes, message: bytes) -> None: self.s.write(b':%s!%s@127.0.0.1 PRIVMSG %s :%s\r\n' % ( from_, from_, to, #private message, or a channel message, )) await self.s.drain() async def _get_regexp(self, dest: Union[slack.User, slack.Channel]) -> Optional[re.Pattern]: #del self._mentions_regex_cache[sl_ev.channel] # No nick substitutions for private chats if isinstance(dest, slack.User): return None dest_id = dest.id # Return from cache if dest_id in self._mentions_regex_cache: return self._mentions_regex_cache[dest_id] usernames = [] for j in await self.sl_client.get_members(dest): u = await self.sl_client.get_user(j) usernames.append(u.name) if len(usernames) == 0: self._mentions_regex_cache[dest_id] = None return None # Extremely inefficient code to generate mentions # Just doing them client-side on the receiving end is too mainstream regexs = (r'((://\S*){0,1}\b%s\b)' % username for username in usernames) regex = re.compile('|'.join(regexs)) self._mentions_regex_cache[dest_id] = regex return regex async def _addmagic(self, msg: str, dest: Union[slack.User, slack.Channel]) -> str: """ Adds magic codes and various things to outgoing messages """ for i in self.substitutions: msg = msg.replace(i[1], i[0]) if self.settings.provider == Provider.SLACK: msg = msg.replace('@here', '') msg = msg.replace('@channel', '') msg = msg.replace('@everyone', '') regex = await self._get_regexp(dest) if regex is None: return msg matches = list(re.finditer(regex, msg)) matches.reverse() # I want to replace from end to start or the positions get broken for m in matches: username = m.string[m.start():m.end()] if username.startswith('://'): continue # Match inside a url elif self.settings.provider == Provider.SLACK: msg = msg[0:m.start()] + '<@%s>' % (await self.sl_client.get_user_by_name(username)).id + msg[m.end():] return msg async def parse_message(self, i: str, source: bytes) -> bytes: # Replace all mentions with @user while mention := _MENTIONS_REGEXP.search(i): i = ( i[0:mention.span()[0]] + (await self.sl_client.get_user(mention.groups()[0])).name + i[mention.span()[1]:] ) # Replace all channel mentions while mention := _CHANNEL_MENTIONS_REGEXP.search(i): i = ( i[0:mention.span()[0]] + '#' + (await self.sl_client.get_channel(mention.groups()[0])).name_normalized + i[mention.span()[1]:] ) #Replace URL with bottom links bottom = "" refs = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹") refn = 1 while url := _URL_REGEXP.search(i): schema, path, label = url.groups() if label and (label != f"{schema}://{path}"): if '://' in label: label = 'LINK' ref = str(refn).translate(refs) refn += 1 i = ( i[0:url.span()[0]] + f'{label}{ref}' + i[url.span()[1]:] ) bottom += f'\n {ref} {schema}://{path}' else: i = ( i[0:url.span()[0]] + f'{schema}://{path}' + i[url.span()[1]:] ) i += bottom for s in self.substitutions: i = i.replace(s[0], s[1]) # Replace emoji codes (e.g. :thumbsup:) i = emojize(i, use_aliases=True) # Store long formatted text into txt files if self.settings.formatted_max_lines: begin = 0 while True: try: fmtstart = i.index('```', begin) fmtend = i.index('```', fmtstart + 1) formatted = i[fmtstart + 3:fmtend] prefix = i[0:fmtstart] suffix = i[fmtend + 3:] if formatted.count('\n') > self.settings.formatted_max_lines: import tempfile with tempfile.NamedTemporaryFile( mode='wt', dir=self.settings.downloads_directory, suffix='.txt', prefix='localslackirc-attachment-', delete=False) as tmpfile: tmpfile.write(formatted) i = prefix + f'\n === PREFORMATTED TEXT AT file://{tmpfile.name}\n' + suffix else: i = '```'.join((prefix, formatted, suffix)) begin = fmtend + 1 except ValueError: break encoded = i.encode('utf8') if self.settings.provider == Provider.SLACK: yell = b' [%s]:' % self.nick if source not in self.settings.silenced_yellers else b':' encoded = encoded.replace(b'', b'yelling%s' % yell) encoded = encoded.replace(b'', b'YELLING LOUDER%s' % yell) encoded = encoded.replace(b'', b'DEAFENING YELL%s' % yell) return encoded async def _message(self, sl_ev: Union[slack.Message, slack.MessageDelete, slack.MessageBot, slack.ActionMessage], prefix: str=''): """ Sends a message to the irc client """ if not isinstance(sl_ev, slack.MessageBot): source = (await self.sl_client.get_user(sl_ev.user)).name.encode('utf8') else: source = b'bot' try: dest = b'#' + (await self.sl_client.get_channel(sl_ev.channel)).name.encode('utf8') except KeyError: dest = self.nick except Exception as e: log('Error: ', str(e)) return if dest in self.parted_channels: # Ignoring messages, channel was left on IRC return text = sl_ev.text lines = await self.parse_message(prefix + text, source) for i in lines.split(b'\n'): if not i: continue if isinstance(sl_ev, slack.ActionMessage): i = b'\x01ACTION ' + i + b'\x01' await self.sendmsg( source, dest, i ) async 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. """ #Invalidate cache since the users in the channel changed if sl_ev.channel in self._mentions_regex_cache: del self._mentions_regex_cache[sl_ev.channel] user = await self.sl_client.get_user(sl_ev.user) if user.deleted: return channel = await 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.write(b':%s!%s@127.0.0.1 JOIN :%s\r\n' % (name, rname, dest)) else: self.s.write(b':%s!%s@127.0.0.1 PART %s\r\n' % (name, rname, dest)) await self.s.drain() async def slack_event(self, sl_ev: slack.SlackEvent) -> None: if not self._usersent: self._held_events.append(sl_ev) return if isinstance(sl_ev, slack.MessageDelete): await self._message(sl_ev, '[deleted] ') elif isinstance(sl_ev, slack.Message): await self._message(sl_ev) elif isinstance(sl_ev, slack.ActionMessage): await self._message(sl_ev) elif isinstance(sl_ev, slack.MessageEdit): if sl_ev.is_changed: await self._message(sl_ev.diffmsg) elif isinstance(sl_ev, slack.MessageBot): await self._message(sl_ev, '[%s] ' % sl_ev.username) elif isinstance(sl_ev, slack.FileShared): f = await self.sl_client.get_file(sl_ev) await self._message(f.announce()) elif isinstance(sl_ev, slack.Join): await self._joined_parted(sl_ev, True) elif isinstance(sl_ev, slack.Leave): await self._joined_parted(sl_ev, False) elif isinstance(sl_ev, slack.TopicChange): await self._sendreply(Replies.RPL_TOPIC, sl_ev.topic, ['#' + (await self.sl_client.get_channel(sl_ev.channel)).name]) elif isinstance(sl_ev, slack.GroupJoined): channel_name = '#%s' % sl_ev.channel.name_normalized await self._send_chan_info(channel_name.encode('utf-8'), sl_ev.channel) elif isinstance(sl_ev, slack.UserTyping): if sl_ev.user not in self._annoy_users: return if time.time() > self._annoy_users[sl_ev.user]: del self._annoy_users[sl_ev.user] await self._sendreply(0, f'No longer annoying {(await self.sl_client.get_user(sl_ev.user)).name}') return await self.sl_client.typing(sl_ev.channel) async 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, b'annoy': self._annoyhandler, b'QUIT': self._quithandler, #CAP LS b'USERHOST': self._userhosthandler, b'whois': self._whoishandler, } if cmdid in handlers: await handlers[cmdid](cmd) else: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Unknown command', [cmdid]) log('Unknown command: ', cmd) def su() -> None: """ switch user. Useful when starting localslackirc as a service as root user. """ if sys.platform.startswith('win'): return # Nothing to do, already not root if os.getuid() != 0: return username = environ.get('PROCESS_OWNER', 'nobody') userdata = pwd.getpwnam(username) os.setgid(userdata.pw_gid) os.setegid(userdata.pw_gid) os.setuid(userdata.pw_uid) os.seteuid(userdata.pw_uid) def main() -> None: su() parser = argparse.ArgumentParser() parser.add_argument('-v', '--version', action='version', version=f'''localslackirc {VERSION}''') parser.add_argument('-p', '--port', type=int, action='store', dest='port', default=9007, required=False, help='set port number. Defaults to 9007') 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('-c', '--cookiefile', type=str, action='store', dest='cookiefile', default=None, required=False, help='set the cookie file (for slack only, for xoxc tokens)') 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('-f', '--status-file', type=str, action='store', dest='status_file', required=False, default=None, help='Path to the file to keep the internal status.') parser.add_argument('-d', '--debug', action='store_true', dest='debug', required=False, default=False, help='Enables debugging logs.') parser.add_argument('--log-suffix', type=str, action='store', dest='log_suffix', default='', help='Set a suffix for the syslog identifier') parser.add_argument('--ignored-channels', type=str, action='store', dest='ignored_channels', default='', help='Comma separated list of channels to not join when autojoin is enabled') parser.add_argument('--downloads-directory', type=str, action='store', dest='downloads_directory', default='/tmp', help='Where to create files for automatic downloads') parser.add_argument('--formatted-max-lines', type=int, action='store', dest='formatted_max_lines', default=0, help='Maximum amount of lines in a formatted text to send to the client rather than store in a file.\n' 'Setting to 0 (the default) will send everything to the client') parser.add_argument('--silenced-yellers', type=str, action='store', dest='silenced_yellers', default='', help='Comma separated list of nicknames that won\'t generate notifications when using @channel and @here') args = parser.parse_args() openlog(environ.get('LOG_SUFFIX', args.log_suffix)) set_debug(environ.get('DEBUG', args.debug)) status_file_str: Optional[str] = environ.get('STATUS_FILE', args.status_file) status_file = None if status_file_str is not None: log('Status file at:', status_file_str) status_file = Path(status_file_str) ip: str = environ.get('IP_ADDRESS', args.ip) overridelocalip: bool = environ['OVERRIDE_LOCAL_IP'].lower() == 'true' if 'OVERRIDE_LOCAL_IP' in environ else args.overridelocalip # Exit if their chosden ip isn't local. User can override with -o if they so dare if not ip.startswith('127') and not 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') port = int(environ.get('PORT', args.port)) autojoin: bool = environ['AUTOJOIN'].lower() == 'true' if 'AUTOJOIN' in environ else args.autojoin nouserlist: bool = environ['NOUSERLIST'].lower() == 'true' if 'NOUSERLIST' in environ else args.nouserlist # Splitting ignored channels ignored_channels_str = environ.get('IGNORED_CHANNELS', args.ignored_channels) if autojoin and len(ignored_channels_str): ignored_channels: Set[bytes] = { (b'' if i.startswith('#') else b'#') + i.encode('ascii') for i in ignored_channels_str.split(',') } else: ignored_channels = set() if 'DOWNLOADS_DIRECTORY' in environ: downloads_directory = Path(environ['DOWNLOADS_DIRECTORY']) else: downloads_directory = Path(args.downloads_directory) try: formatted_max_lines = int(environ.get('FORMATTED_MAX_LINES', args.formatted_max_lines)) except: exit('FORMATTED_MAX_LINES is not a valid int') yellers_str = environ.get('SILENCED_YELLERS', args.silenced_yellers) if yellers_str: silenced_yellers = {i.strip().encode('utf8') for i in yellers_str.split(',')} else: silenced_yellers = set() if 'TOKEN' in environ: token = environ['TOKEN'] else: try: with open(args.tokenfile) as f: token = f.readline().strip() except IsADirectoryError: exit(f'Not a file {args.tokenfile}') except (FileNotFoundError, PermissionError): exit(f'Unable to open the token file {args.tokenfile}') if 'COOKIE' in environ: cookie: Optional[str] = environ['COOKIE'] else: try: if args.cookiefile: with open(args.cookiefile) as f: cookie = f.readline().strip() else: cookie = None except (FileNotFoundError, PermissionError): exit(f'Unable to open the cookie file {args.cookiefile}') except IsADirectoryError: exit(f'Not a file {args.cookiefile}') if token.startswith('xoxc-') and not cookie: exit('The cookie is needed for this kind of slack token') provider = Provider.SLACK # Parameters are dealt with async def irc_listener() -> None: serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind((ip, port)) serversocket.listen(1) s, _ = serversocket.accept() serversocket.close() asyncio.get_running_loop().add_signal_handler(signal.SIGHUP, term_f) asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, term_f) asyncio.get_running_loop().add_signal_handler(signal.SIGINT, term_f) reader, writer = await asyncio.open_connection(sock=s) previous_status = None if status_file is not None and status_file.exists(): previous_status = status_file.read_bytes() sl_client = slack.Slack(token, cookie, previous_status) await sl_client.login() clientsettings = ClientSettings( nouserlist=nouserlist, autojoin=autojoin, provider=provider, ignored_channels=ignored_channels, downloads_directory=downloads_directory, formatted_max_lines=formatted_max_lines, silenced_yellers=silenced_yellers, ) verify = clientsettings.verify() if verify is not None: exit(verify) ircclient = Client(writer, sl_client, clientsettings) try: from_irc_task = asyncio.create_task(from_irc(reader, ircclient)) to_irc_task = asyncio.create_task(to_irc(sl_client, ircclient)) await asyncio.gather( from_irc_task, to_irc_task, ) finally: log('Closing connections') sl_client.close() if status_file: log(f'Writing status to {status_file}') status_file.write_bytes(sl_client.get_status()) writer.close() log('Cancelling running tasks') from_irc_task.cancel() to_irc_task.cancel() while True: signal.signal(signal.SIGHUP, term_f) signal.signal(signal.SIGTERM, term_f) signal.signal(signal.SIGINT, term_f) try: asyncio.run(irc_listener()) except IrcDisconnectError: log('IRC disconnected') async def from_irc(reader, ircclient: Client): while True: try: cmd = await reader.readline() except Exception: raise IrcDisconnectError() await ircclient.command(cmd.strip()) async def to_irc(sl_client: Union[slack.Slack], ircclient: Client): while True: ev = await sl_client.event() if ev: log(ev) await ircclient.slack_event(ev) def term_f(*args): sys.exit(0) if __name__ == '__main__': try: main() except KeyboardInterrupt: pass localslackirc/diff.py0000644000175000017500000000362114033164120014174 0ustar salvosalvo# localslackirc # Copyright (C) 2018-2021 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 typing import Iterable from itertools import count __all__ = [ 'seddiff', ] _SEPARATORS = set(' .,:;\t\n()[]{}') def wordsplit(word: str) -> Iterable[str]: bucket = '' for i in word: if i in _SEPARATORS: yield bucket bucket = '' bucket += i if bucket: yield bucket 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. """ if a == b: return '' l1 = list(wordsplit(a)) l2 = list(wordsplit(b)) for prefix in count(): try: if l1[prefix] != l2[prefix]: break except: break for postfix in count(1): try: if l1[-postfix] != l2[-postfix]: break except Exception: break postfix -= 1 if prefix and postfix and len(l1) != len(l2): prefix -= 1 postfix -= 1 px = None if postfix == 0 else -postfix return 's/%s/%s/' % (''.join(l1[prefix:px]).strip() or '$', ''.join(l2[prefix:px]).strip()) localslackirc/log.py0000644000175000017500000000331514033156437014061 0ustar salvosalvo# localslackirc # Copyright (C) 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 from os import isatty from syslog import LOG_INFO, LOG_DEBUG, syslog from syslog import openlog as _openlog from typing import Union __all__ = [ 'log', 'openlog', 'set_debug', 'debug', ] tty = isatty(1) and isatty(2) debug_enabled = False def openlog(suffix: str) -> None: """ Opens the syslog connection if needed otherwise does nothing. """ if tty: return if suffix: suffix = f'-{suffix}' _openlog(f'localslackirc{suffix}') def log(*args) -> None: """ Logs to stdout or to syslog depending on if running with a terminal attached. """ if tty: print(*args) return syslog(LOG_INFO, ' '.join(str(i) for i in args)) def set_debug(state: Union[str, bool]) -> None: global debug_enabled debug_enabled = bool(state) def debug(*args) -> None: if not debug_enabled: return if tty: print(*args) syslog(LOG_DEBUG, ' '.join(str(i) for i in args)) localslackirc/slack.py0000644000175000017500000006665514136564671014424 0ustar salvosalvo# localslackirc # Copyright (C) 2018-2021 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 asyncio import datetime from dataclasses import dataclass, field import json from time import time from typing import * from typedload import load, dump from diff import seddiff from slackclient import SlackClient from slackclient.client import LoginInfo from log import * USELESS_EVENTS = { 'draft_create', 'draft_delete', 'accounts_changed', 'channel_marked', 'group_marked', 'mpim_marked', 'hello', 'dnd_updated_user', 'reaction_added', 'file_deleted', 'file_public', 'file_created', 'desktop_notification', } 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 error: Optional[str] = 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 NoChanMessage(NamedTuple): user: str text: str class ActionMessage(Message): pass @dataclass class GroupJoined: type: Literal['group_joined'] channel: Channel @dataclass class MessageEdit: type: Literal['message'] subtype: Literal['message_changed'] channel: str previous: NoChanMessage = field(metadata={'name': 'previous_message'}) current: NoChanMessage = field(metadata={'name': 'message'}) @property def is_changed(self) -> bool: return self.previous.text != self.current.text @property def diffmsg(self) -> Message: return Message( text=seddiff(self.previous.text, self.current.text), channel=self.channel, user=self.current.user, ) @dataclass class MessageDelete: type: Literal['message'] subtype: Literal['message_deleted'] channel: str previous_message: NoChanMessage @property def user(self) -> str: return self.previous_message.user @property def text(self) -> str: return self.previous_message.text class UserTyping(NamedTuple): type: Literal['user_typing'] user: str channel: str class Profile(NamedTuple): real_name: str = 'noname' email: Optional[str] = None status_text: str = '' is_restricted: bool = False is_ultra_restricted: bool = False @dataclass class File: id: str url_private: str size: int user: str name: Optional[str] = None title: Optional[str] = None mimetype: Optional[str] = None channels: List[str] = field(default_factory=list) groups: List[str] = field(default_factory=list) ims: List[str] = field(default_factory=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 ) ) @dataclass class FileShared: type: Literal['file_shared'] file_id: str user_id: str ts: float @dataclass class MessageBot: type: Literal['message'] subtype: Literal['bot_message'] _text: str = field(metadata={'name': 'text'}) username: str channel: str bot_id: Optional[str] = None attachments: List[Dict[str, Any]] = field(default_factory=list) @property def text(self): r = [self._text] for i in self.attachments: t = "" if 'text' in i: t = i['text'] elif 'fallback' in i: t = i['fallback'] for line in t.split("\n"): r.append("| " + line) return '\n'.join(r) 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): type: Literal['member_joined_channel'] user: str channel: str class Leave(NamedTuple): type: Literal['member_left_channel'] user: str channel: str @dataclass class TopicChange: type: Literal['message'] subtype: Literal['group_topic'] topic: str channel: str user: str @dataclass class HistoryBotMessage: type: Literal['message'] subtype: Literal['bot_message'] text: str bot_id: Optional[str] username: str = 'bot' ts: float = 0 files: List[File] = field(default_factory=list) thread_ts: Optional[str] = None attachments: List[Dict[str, Any]] = field(default_factory=list) @dataclass class HistoryMessage: type: Literal['message'] user: str text: str ts: float files: List[File] = field(default_factory=list) thread_ts: Optional[str] = None class NextCursor(NamedTuple): next_cursor: str class History(NamedTuple): ok: Literal[True] messages: List[Union[HistoryMessage, HistoryBotMessage]] has_more: bool response_metadata: Optional[NextCursor] = None class Conversations(NamedTuple): channels: List[Channel] response_metadata: Optional[NextCursor] = None SlackEvent = Union[ TopicChange, MessageDelete, MessageEdit, Message, ActionMessage, MessageBot, FileShared, Join, Leave, GroupJoined, UserTyping, ] @dataclass class SlackStatus: """ Not related to the slack API. This is a structure used internally by this module to save the status on disk. """ last_timestamp: float = 0.0 class Slack: def __init__(self, token: str, cookie: Optional[str], previous_status: Optional[bytes]) -> None: """ A slack client object. token: The slack token cookie: If the slack instance also uses a cookie, it must be passed here previous_status: Opaque bytestring to restore internal status from a different object. Obtained from get_status() """ self.client = SlackClient(token, cookie) self._usercache: Dict[str, User] = {} self._usermapcache: Dict[str, User] = {} self._usermapcache_keys: List[str] self._imcache: Dict[str, str] = {} self._channelscache: List[Channel] = [] 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() self._wsblock: int = 0 # Semaphore to block the socket and avoid events being received before their API call ended. self.login_info: Optional[LoginInfo] = None if previous_status is None: self._status = SlackStatus() else: self._status = load(json.loads(previous_status), SlackStatus) def close(self): del self.client async def login(self) -> None: """ Set the login_info field """ log('Login in slack') self.login_info = await self.client.login(15) async def _thread_history(self, channel: str, thread_id: str) -> List[Union[HistoryMessage, HistoryBotMessage]]: r: List[Union[HistoryMessage, HistoryBotMessage]] = [] cursor = None log('Thread history', channel, thread_id) while True: log('Cursor') p = await self.client.api_call( 'conversations.replies', channel=channel, ts=thread_id, limit=1000, cursor=cursor, ) try: response = load(p, History) except Exception as e: log('Failed to parse', e) log(p) break r += [i for i in response.messages if i.ts != i.thread_ts] if response.has_more and response.response_metadata: cursor = response.response_metadata.next_cursor else: break log('Thread fetched') r[0].thread_ts = None return r async def _history(self) -> None: ''' Obtain the history from the last known event and inject fake events as if the messages are coming now. ''' log('Fetching history...') if self._status.last_timestamp == 0: log('No last known timestamp. Unable to fetch history') return last_timestamp = self._status.last_timestamp FOUR_DAYS = 60 * 60 * 24 * 4 if time() - last_timestamp > FOUR_DAYS: log('Last timestamp is too old. Defaulting to 4 days.') last_timestamp = time() - FOUR_DAYS dt = datetime.datetime.fromtimestamp(last_timestamp) log(f'Last known timestamp {dt}') chats: Sequence[Union[IM, Channel]] = [] chats += await self.channels() + await self.get_ims() # type: ignore for channel in chats: if isinstance(channel, Channel): if not channel.is_member: continue log(f'Downloading logs from channel {channel.name_normalized}') else: log(f'Downloading logs from IM {channel.user}') cursor = None while True: # Loop to iterate the cursor log('Calling cursor') r = await self.client.api_call( 'conversations.history', channel=channel.id, oldest=last_timestamp, limit=1000, cursor=cursor, ) try: response = load(r, History) except Exception as e: log('Failed to parse', e) log(r) break msg_list = list(response.messages) while msg_list: msg = msg_list.pop(0) # The last seen message is sent again, skip it if msg.ts == last_timestamp: continue # Update the last seen timestamp if self._status.last_timestamp < msg.ts: self._status.last_timestamp = msg.ts # The attached files for f in msg.files: f.channels.append(channel.id) self._internalevents.append(f.announce()) # History for the thread if msg.thread_ts and float(msg.thread_ts) == msg.ts: l = await self._thread_history(channel.id, msg.thread_ts) l.reverse() msg_list = l + msg_list continue # Inject the events if isinstance(msg, HistoryMessage): self._internalevents.append(Message( channel=channel.id, text=msg.text, user=msg.user )) elif isinstance(msg, HistoryBotMessage): self._internalevents.append(MessageBot( type='message', subtype='bot_message', _text=msg.text, attachments=msg.attachments, username=msg.username, channel=channel.id, bot_id=msg.bot_id, )) if response.has_more and response.response_metadata: cursor = response.response_metadata.next_cursor else: break def get_status(self) -> bytes: ''' A status string that will be passed back when this is started again ''' return json.dumps(dump(self._status), ensure_ascii=True).encode('ascii') async def away(self, is_away: bool) -> None: """ Forces the aways status or lets slack decide """ status = 'away' if is_away else 'auto' r = await self.client.api_call('users.setPresence', presence=status) response = load(r, Response) if not response.ok: raise ResponseException(response.error) async def typing(self, channel: Union[Channel, str]) -> None: """ Sends a typing event to slack """ if isinstance(channel, Channel): ch_id = channel.id else: ch_id = channel await self.client.wspacket(type='typing', channel=ch_id) async def topic(self, channel: Channel, topic: str) -> None: r = await self.client.api_call('conversations.setTopic', channel=channel.id, topic=topic) response = load(r, Response) if not response.ok: raise ResponseException(response.error) async def kick(self, channel: Channel, user: User) -> None: r = await self.client.api_call('conversations.kick', channel=channel.id, user=user.id) response = load(r, Response) if not response.ok: raise ResponseException(response.error) async def join(self, channel: Channel) -> None: r = await self.client.api_call('conversations.join', channel=channel.id) response = load(r, Response) if not response.ok: raise ResponseException(response.error) async 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 = await self.client.api_call('conversations.invite', channel=channel.id, users=ids) response = load(r, Response) if not response.ok: raise ResponseException(response.error) async def get_members(self, channel: Union[str, Channel]) -> 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. """ if isinstance(channel, Channel): id_ = channel.id else: id_ = channel 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 = await self.client.api_call('conversations.members', channel=id_, limit=5000, **kwargs) # type: ignore response = load(r, Response) if not response.ok: raise ResponseException(response.error) 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('member_joined_channel', 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_] async def channels(self, refresh: bool = False) -> List[Channel]: """ Returns the list of slack channels if refresh is set, the local cache is cleared """ if refresh: self._channelscache.clear() if self._channelscache: return self._channelscache cursor = None while True: r = await self.client.api_call( 'conversations.list', cursor=cursor, exclude_archived=True, types='public_channel,private_channel,mpim', limit=1000, # In vain hope that slack would not ignore this ) response = load(r, Response) if response.ok: conv = load(r, Conversations) self._channelscache += conv.channels # For this API, slack sends an empty string as next cursor, just to show off their programming "skillz" if not conv.response_metadata or not conv.response_metadata.next_cursor: break cursor = conv.response_metadata.next_cursor else: raise ResponseException(response.error) return self._channelscache async def get_channel(self, id_: str) -> Channel: """ Returns a channel object from a slack channel id raises KeyError if it doesn't exist. """ for i in range(2): for c in await self.channels(refresh=bool(i)): if c.id == id_: return c raise KeyError() async 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 i in range(2): for c in await self.channels(refresh=bool(i)): if c.name == name: return c raise KeyError() async 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 await self.get_ims(): self._imcache[im.user] = im.id if im.id == im_id: return im; return None async 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 = await 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.error) async def get_user_by_name(self, name: str) -> User: return self._usermapcache[name] async def prefetch_users(self) -> None: """ Prefetch all team members for the slack team. """ r = await 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 self._usermapcache_keys = list() async 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 = await self.client.api_call("users.info", user=id_) response = load(r, Response) if response.ok: u = load(r['user'], User) self._usercache[id_] = u if u.name not in self._usermapcache: self._usermapcache_keys = list() self._usermapcache[u.name] = u return u else: raise KeyError(response) async def get_file(self, f: Union[FileShared, str]) -> File: """ Returns a file object """ fileid = f if isinstance(f, str) else f.file_id r = await self.client.api_call("files.info", file=fileid) response = load(r, Response) if response.ok: return load(r['file'], File) else: raise KeyError(response) async 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: r = await self.client.api_call( 'files.upload', channels=channel_id, file=f, ) response = load(r, Response) if response.ok: return raise ResponseException(response.error) 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) async 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' try: self._wsblock += 1 r = await 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.error) finally: self._wsblock -= 1 async 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 await 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 = await self.client.api_call( "im.open", return_im=True, user=user_id, ) response = load(r, Response) if not response.ok: raise ResponseException(response.error) channel_id = r['channel']['id'] self._imcache[user_id] = channel_id await self.send_message(channel_id, msg, action) async def event(self) -> Optional[SlackEvent]: """ This returns the events from the slack websocket """ if self._internalevents: return self._internalevents.pop() try: events = await self.client.rtm_read() except Exception: events = [] log('Connecting to slack...') self.login_info = await self.client.rtm_connect(5) await self._history() log('Connected to slack') return None while self._wsblock: # Retry until the semaphore is free await asyncio.sleep(0.01) for event in events: t = event.get('type') ts = float(event.get('ts', 0)) if ts > self._status.last_timestamp: self._status.last_timestamp = ts if ts in self._sent_by_self: self._sent_by_self.remove(ts) continue if t in USELESS_EVENTS: continue debug(event) loadable_events = Union[TopicChange, FileShared, MessageBot, MessageEdit, MessageDelete, GroupJoined, Join, Leave, UserTyping] try: ev: Optional[loadable_events] = load( event, loadable_events # type: ignore ) except Exception: ev = None if isinstance(ev, (Join, Leave)) and ev.channel in self._get_members_cache: if isinstance(ev, Join): self._get_members_cache[ev.channel].add(ev.user) else: self._get_members_cache[ev.channel].remove(ev.user) if ev: return ev subt = event.get('subtype') try: if t == 'message' and (not subt or subt == 'me_message'): msg = load(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 = await 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': return ActionMessage(*msg) else: return msg elif t == 'message' and subt == 'slackbot_response': return load(event, Message) 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 else: log(event) except Exception as e: log('Exception: %s' % e) self._triage_sent_by_self() return None localslackirc/slackclient/__init__.py0000644000175000017500000000004013637443613017327 0ustar salvosalvofrom .client import SlackClient localslackirc/slackclient/http.py0000644000175000017500000001576413746050654016572 0ustar salvosalvo# localslackirc # Copyright (C) 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 asyncio import gzip import json from typing import Dict, Optional, NamedTuple, Tuple, Any from uuid import uuid1 from urllib import parse def multipart_form(form_fields: Dict[str, Any]) -> Tuple[str, bytes]: """ Convert a dictionary to post data and returns relevant headers. The dictionary can contain values as open files, or anything else. None values are skipped. Anything that is not an open file is cast to str """ data = {} has_files = False for k, v in form_fields.items(): if v is not None: data[k] = v if hasattr(v, 'read') and hasattr(v, 'name'): has_files = True if not has_files: return ( 'Content-Type: application/x-www-form-urlencoded\r\n', parse.urlencode(data).encode('ascii') ) boundary = str(uuid1()).encode('ascii') form_data = b'' for k, v in data.items(): form_data += b'--' + boundary + b'\r\n' if hasattr(v, 'read') and hasattr(v, 'name'): form_data += f'Content-Disposition: form-data; name="{k}"; filename="{v.name}"\r\n'.encode('ascii') form_data += b'\r\n' + v.read() + b'\r\n' else: strv = str(v) form_data += f'Content-Disposition: form-data; name="{k}"\r\n'.encode('ascii') form_data += b'\r\n' + strv.encode('ascii') + b'\r\n' form_data += b'--' + boundary + b'\r\n' header = f'Content-Type: multipart/form-data; boundary={boundary.decode("ascii")}\r\n' return header, form_data class Response(NamedTuple): status: int headers: Dict[str, str] data: bytes def json(self): return json.loads(self.data) class Request: def __init__(self, base_url: str) -> None: """https://slack.com/api/ In my case, base_url is "https://slack.com/api/" """ self.base_url = parse.urlsplit(base_url) if self.base_url.scheme == 'https': self.ssl = True self.port = 443 else: self.ssl = False self.port = 80 # Override port if explicitly defined if self.base_url.port: self.port = self.base_url.port self.hostname = self.base_url.hostname self.path = self.base_url.path self._connections: Dict[str, Tuple[asyncio.streams.StreamReader, asyncio.streams.StreamWriter]] = {} def __del__(self): for i in self._connections.values(): i[1].close() async def _connect(self) -> Tuple[asyncio.streams.StreamReader, asyncio.streams.StreamWriter]: """ Get a connection. It can be an already cached one or a new one. """ task = asyncio.tasks.current_task() assert task is not None # Mypy doesn't notice this is in an async key = task.get_name() r = self._connections.get(key) if r is None: r = await asyncio.open_connection(self.hostname, self.port, ssl=self.ssl) self._connections[key] = r return r async def post(self, path: str, headers: Dict[str, str], data: Dict[str, Any], timeout: float=0) -> Response: """ post a request. data will be sent as a form. Fields are converted to str, except for open files, which are read and sent. Open files must be opened in binary mode. Due to the possibility that the cached connection got closed, it will do one retry before raising the exception """ try: return await self._post(path, headers, data, timeout) except (BrokenPipeError, ConnectionResetError, asyncio.IncompleteReadError): # Clear connection from pool task = asyncio.tasks.current_task() assert task is not None # Mypy doesn't notice this is in an async key = task.get_name() r, w = self._connections.pop(key) w.close() return await self._post(path, headers, data, timeout) async def _post(self, path: str, headers: Dict[str, str], data: Dict[str, Any], timeout: float=0) -> Response: # Prepare request req = f'POST {self.path + path} HTTP/1.1\r\n' req += f'Host: {self.hostname}\r\n' req += 'Connection: keep-alive\r\n' req += 'Accept-Encoding: gzip\r\n' for k, v in headers.items(): req += f'{k}: {v}\r\n' header, post_data = multipart_form(data) req += header req += f'Content-Length: {len(post_data)}\r\n' req += '\r\n' # Send request # 1 retry in case the keep alive connection was closed reader, writer = await self._connect() writer.write(req.encode('ascii')) writer.write(post_data) await writer.drain() # Read response line = await reader.readline() if len(line) == 0: raise BrokenPipeError() try: status = int(line.split(b' ')[1]) except Exception as e: raise Exception(f'Invalid data {line!r} {e}') # Read headers headers = {} while True: line = await reader.readline() if line == b'\r\n': break elif len(line) == 0: raise BrokenPipeError() k, v = line.decode('ascii').split(':', 1) headers[k.lower()] = v.strip() # Read data read_data = b'' if headers.get('transfer-encoding') == 'chunked': while True: line = await reader.readline() if len(line) == 0: raise BrokenPipeError() if not line.endswith(b'\r\n'): raise Exception('Unexpected end of chunked data') size = int(line, 16) read_data += (await reader.readexactly(size + 2))[:-2] if size == 0: break elif 'content-length' in headers: size = int(headers['content-length']) read_data = await reader.readexactly(size) else: raise NotImplementedError('Can only handle chunked or content length' + repr(headers)) # decompress if needed if headers.get('content-encoding') == 'gzip': read_data = gzip.decompress(read_data) return Response(status, headers, read_data) localslackirc/slackclient/client.py0000644000175000017500000001260314131755774017062 0ustar salvosalvo# localslackirc # Copyright (C) 2018-2021 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. import asyncio import json from typing import Any, Dict, List, NamedTuple, Optional from typedload import load import websockets from websockets.client import connect as wsconnect from .exceptions import * from .http import Request class Team(NamedTuple): id: str name: str domain: str class Self(NamedTuple): id: str name: str class LoginInfo(NamedTuple): team: Team self: Self url: str class SlackClient: """ The SlackClient object owns the websocket connection and all attached channel information. """ def __init__(self, token: str, cookie: Optional[str]) -> None: # Slack client configs self._token = token self._cookie = cookie # RTM configs self._websocket: Optional[websockets.client.WebSocketClientProtocol] = None self._request = Request('https://slack.com/api/') self._wsid = 0 async def wspacket(self, **kwargs) -> None: """ Send data over websocket """ if self._websocket is None: raise Exception('No websocket at this point') kwargs['id'] = self._wsid self._wsid += 1 await self._websocket.send(json.dumps(kwargs)) def __del__(self): if self._websocket: asyncio.create_task(self._websocket.close()) del self._request async def _do(self, request: str, post_data: Dict[str, Any], timeout: float): """ Perform a POST request to the Slack Web API Args: 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'} """ # Set user-agent and auth headers headers = { 'user-agent': 'localslackirc', 'Authorization': f'Bearer {self._token}' } if self._cookie: headers['cookie'] = self._cookie return await self._request.post(request, headers, post_data, timeout) async def login(self, timeout: float = 0.0) -> LoginInfo: """ Performs a login to slack. """ reply = await self._do('rtm.connect', {}, timeout=timeout) if reply.status != 200: raise SlackConnectionError("RTM connection attempt failed") login_data = reply.json() if not login_data["ok"]: raise SlackLoginError(reply=login_data) return load(login_data, LoginInfo) async def rtm_connect(self, timeout: Optional[int] = None) -> LoginInfo: """ Connects to the RTM API - https://api.slack.com/rtm :Args: timeout: in seconds """ r = await self.login() self._websocket = await wsconnect(r.url) return r async def api_call(self, method: str, timeout: float = 0.0, **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 """ response = await self._do(method, kwargs, timeout) response_json = response.json() response_json["headers"] = dict(response.headers) return response_json async def rtm_read(self) -> List[Dict[str, Any]]: assert self._websocket json_data: str = await self._websocket.recv() # type: ignore data = [] if json_data != '': for d in json_data.split('\n'): data.append(json.loads(d)) return data localslackirc/slackclient/exceptions.py0000644000175000017500000000327513637443613017766 0ustar salvosalvo# 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 # # 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) def __str__(self) -> str: reply = getattr(self, 'reply', None) msg = getattr(self, 'msg', None) return f'message={msg} reply={reply}' 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/Makefile0000644000175000017500000000561614131764355014377 0ustar salvosalvoall: @echo Nothing to do .PHONY: lint lint: mypy --config-file mypy.conf *.py slackclient localslackirc .PHONY: test test: lint python3 -m tests .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/http.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 log.py $${DESTDIR:-/}/usr/share/localslackirc/ install -m644 slack.py $${DESTDIR:-/}/usr/share/localslackirc/ install -m644 irc.py $${DESTDIR:-/}/usr/share/localslackirc/ install localslackirc $${DESTDIR:-/}/usr/share/localslackirc/ # Install command install -d $${DESTDIR:-/}/usr/bin/ ln -s ../share/localslackirc/localslackirc $${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 SECURITY.md $${DESTDIR:-/}/usr/share/doc/localslackirc/SECURITY.md install -m644 -D man/localslackirc.1 $${DESTDIR:-/}/usr/share/man/man1/localslackirc.1 install -m644 -D localslackirc.d/example $${DESTDIR:-/}/etc/localslackirc.d/example install -m644 -D systemd/localslackirc@.service $${DESTDIR:-/}/lib/systemd/system/localslackirc@.service install -m644 -D systemd/localslackirc.service $${DESTDIR:-/}/lib/systemd/system/localslackirc.service .PHONY: dist dist: cd ..; tar -czvvf localslackirc.tar.gz \ localslackirc/localslackirc \ localslackirc/irc.py \ localslackirc/diff.py \ localslackirc/log.py \ localslackirc/slack.py \ localslackirc/slackclient/__init__.py \ localslackirc/slackclient/http.py \ localslackirc/slackclient/client.py \ localslackirc/slackclient/exceptions.py \ localslackirc/Makefile \ localslackirc/CHANGELOG \ localslackirc/LICENSE \ localslackirc/README.md \ localslackirc/SECURITY.md \ localslackirc/requirements.txt \ localslackirc/docker/Dockerfile \ localslackirc/man \ localslackirc/tests/*.py \ localslackirc/localslackirc.d \ localslackirc/systemd \ localslackirc/mypy.conf 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 $(RM) -r tests/__pycache__ $(RM) -r __pycache__ localslackirc/CHANGELOG0000644000175000017500000000405214136567635014151 0ustar salvosalvo1.14 * Write "LINK" instead of the URL when slack labels a URL with another URL 1.13 * New /annoy command to annoy people, showing self as typing when they are. * Make mypy happy 1.12 * Option to save long formatted text as .txt files * Download history for direct messages too * Unicode emoji! * Improved diff * Improved compatibility with IRC * Able to prevent selected users from abusing general mentions 1.11 * Greatly reduced CPU usage * Remove support for RocketChat. I have no way of testing it and it requires severe changes. * Only tag users that are in the same channel * Handle more exceptions with non existing users/channels or malformed commands * Handle cursor over conversations list * New setting to not join channels when autojoin is set * Diff of edit shows the entire word being edited 1.10 * Do not insert mentions inside URLs * Support /whois 1.9 * Chat history is held and injected when the IRC client is ready * Remove attr dependency 1.8 * Chat and thread history is retrieved and injected * Aware of new channels the user is added to * Parse URLs sent from slack with a label * Requires at least python3.8 * Improved documentation * Improved logging * Various crashes fixed * Better handling of signals * Can join slack channels without doing so from the app * Support @everyone 1.7 * Logs are more useful * Ship with systemd service to run instances from configuration files * Support for xoxc tokens in slack 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/LICENSE0000644000175000017500000010451313637443613013741 0ustar salvosalvo 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.md0000644000175000017500000001417714131755774014225 0ustar salvosalvolocalslackirc ============= 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. Why? Peace of mind! ------------------- Using slack from IRC instead of web app offers several advantages: * You do not see all the gifs other people post. * You can `/ignore` users who bother you (can't do that on slack). * Leaving channels on slack is hard, normally I get invited back continuously on the off topic channels. With *localslackirc* you can leave them on the IRC client without people knowing that you won't be reading any of that. * IRC clients allow to customise notifications. For example I have set mine to just blink in the tray area and do no sounds or popups. * Any IRC client is faster than the web ui slack has, and it will respect your colour and style settings. * Power savings. Because that's a logical consequence of not doing something in the browser. Running localslackirc ===================== The preferred way is to have Debian Testing and install from the repository. You can grab the latest .deb and sources from: https://github.com/ltworf/localslackirc/releases All the options are documented in the man page. Execute ```bash man man/localslackirc.1 ``` To read the page without installing localslackirc on the system. There is a`localslackirc` binary but the preferred way is to run it using systemd. Systemd ------- When installed from the .deb you will find a configuration template file in `/etc/localslackirc.d/example`. Create a copy of it in the same directory and edit the copy. You can create several copies to use several slack workspaces. Tell systemd to start localslackirc and make sure the ports do not collide. `instancename` is the name of the file. ```bash # To start the instance sudo systemctl start localslackirc@instancename.service # To start the instance at every boot sudo systemctl enable localslackirc@instancename.service ``` Docker ------ Create a configuration file basing it on `localslackirc.d/example` ```bash # Create the container docker build -t localslackirc -f docker/Dockerfile . # Run localslackirc docker run -d -p 9007:9007 --name=mylocalslackirc --env-file configfile localslackirc ``` Sources ------- ### Requirements * At least Python 3.8 * The modules indicated in `requirements.txt` Check the manpage for the parameters. ```bash ./localslackirc ``` Obtain a token ============== Before localslackirc can do anything useful, you need to obtain a token. Your token should be placed inside the configuration file. Obtain a token from slack ------------------------- * 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 and Firefox * In your browser, login to slack and then open the web console. * Run this javascript code: `q=JSON.parse(localStorage.localConfig_v2)["teams"]; q[Object.keys(q)[0]]["token"]` * Copy the result, without quotes. * **Note**: If you are signed in to multiple teams this will not work, run in a private window for the team you want to set up. Obtain a Slack cookie --------------------- This step is only needed if your token starts with `xoxc-`. This option is available since release 1.7. * Run this javascript code: ```js q=JSON.parse(localStorage.localConfig_v2)["teams"]; var authToken=q[Object.keys(q)[0]]["token"]; // setup request var formData = new FormData(); formData.append('token', authToken); // make request (async () => { const rawResponse = await fetch('/api/emoji.list', { method: 'POST', body: formData }); const emojisApi = await rawResponse.json(); // dump to console })(); ``` * In the network tab inspect the request for "emoji.list". * From that request, copy the "Cookie" header. * The values in the field look like `key1=value1; key2=value2; key3=value3;` * Get the string `d=XXXXXX;` (where XXX is the secret) and that is your cookie value. It is important to copy the `d=` part and the final `;`. * Save the string in its own file (different than the token file). Using localslackirc =================== After installing localslackirc and obtaining the token, it is the time to connect to localslackirc with the IRC client. * Connect to the IRC server created by localslackirc (by default 127.0.0.1:9007) * Use your Slack username as your nickname * If you left autojoin on, your client will automatically join your slack channels. ## Sending files You can use `/sendfile #destination filepath` to send files. Destination can be a channel or a user. ## Annoying people You can use `/annoy user` to send typing notifications whenever the specified user sends a typing notification. ## 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 `./localslackirc`). 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 ... ``` IRC Channel =========== #localslackirc on oftc localslackirc/SECURITY.md0000644000175000017500000000036113700102066014502 0ustar salvosalvo# Security Policy ## Supported Versions Only the latest release is supported. I will not backport fixes. ## Reporting a Vulnerability Contact me at tiposchi@tiscali.it My PGP key is on this file, on git. debian/upstream/signing-key.asc localslackirc/requirements.txt0000644000175000017500000000005414122573712016205 0ustar salvosalvotypedload>=2.6 emoji types-emoji websockets localslackirc/docker/Dockerfile0000644000175000017500000000065114122573712016165 0ustar salvosalvoFROM python:3.8-slim RUN mkdir -p /localslackirc/slackclient RUN adduser --group --system localslackirc COPY requirements.txt /localslackirc RUN python3 -m pip install -r /localslackirc/requirements.txt a COPY *.py /localslackirc/ COPY localslackirc /localslackirc/ COPY slackclient/*.py /localslackirc/slackclient/ USER localslackirc ENTRYPOINT PYTHONPATH=/localslackirc python3 /localslackirc/localslackirc -o -i "0.0.0.0" localslackirc/man/0000755000175000017500000000000014131755774013507 5ustar salvosalvolocalslackirc/man/localslackirc.10000644000175000017500000001327514131755774016407 0ustar salvosalvo.TH localslackirc 1 "Sep 23, 2021" "IRC gateway for slack" .SH NAME localslackirc \- Creates an IRC server running locally, which acts as a gateway to slack 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 for one user. .br To connect to multiple instances it is necessary to run multiple instances of this software. .TP .SS .SS Options: .TP .B -h, --help Show the help message and exit. .TP .B -v, --version Show the version and exit. .TP .B -p PORT, --port PORT Set the port number. The default is 9007. .br .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 -c TOKENFILE, --cookiefile TOKENFILE Set the cookie file. This is only used on slack, and is only useful if your token starts with "xoxc". .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 --downloads-directory Where to create files for automatic downloads. It defaults to /tmp. .br The directory must exist and be writeable. Files will automatically be downloaded in it. .br No cleaning is automatically performed on it by localslackirc. .TP .B --formatted-max-lines Maximum amount of lines in a formatted text to send to the client rather than store in a file. .br When people send logs or otherwise long text content as formatted text, the end result is usually hardly readable in IRC, having the username of the sender and the time in each line. .br This option sets a limit for formatted content to be sent as text. .br When the limit is exceeded, the formatted text will be stored as a .txt file instead and its URL will be shown in the IRC client. .br The files will be saved in the path specified by "downloads directory". .br The files are not automatically removed. .br Setting to 0 (the default) will send everything to the client and create no text files. .TP .B -f --status-file Path to the file keeping the status. When this is set, it allows for the history to be loaded on start. .TP .B --silenced-yellers Comma separated list of nicknames that are prevented from using general mentions (@here, @channel, @everyone, and the likes). .br Since some people are greatly abusing the feature, this is to make them less annoying. .br Their messages aren't blocked and are shown as "yelling MESSAGE", but the nickname of the user won't be injected in the message, so the IRC client won't create a notification. .TP .B -d --debug Enables debugging logs. .TP .B --log-suffix Instead of using localslackirc as ident for syslog, this appends a custom string, separated by a -. .br This is useful when running several instances, to be able to distinguish the logs. .br The default .service file uses this. Of course journald keeps track of the services but this makes it easier to have the information on text dumps or other logging daemons such as rsyslog. .TP .B --ignored-channels Comma separated list of channels to ignore and not automatically join on IRC. .br It is ignored unless autojoin is set. .br If a channel is in this list, the IRC client will not automatically join it, but on slack you will still be inside the channel .br This is useful to avoid off topic channels in which coworkers who can't take a hint keep re-inviting. .br The ignored channels can be joined again if needed, with a /join #channel command. However the conversation history will not be fetched. .br For channel names containing non ascii characters, their ascii representation needs to be used. Use /list to see which that is. .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 ENVIRONMENT The following environment variables are used. They override command line settings. The alternatives to switches must contain "true" to work. .TP .B COOKIE Alternative to --cookiefile .TP .B DOWNLOADS_DIRECTORY Alternative to --downloads-directory .TP .B FORMATTED_MAX_LINES Alternative to --formatted-max-lines .TP .B PORT Alternative to --port .TP .B TOKEN Alternative to --tokenfile .TP .B PROCESS_OWNER If running as root, this is the name of the user to switch to. If this is not specified, "nobody" will be used. .br This is very useful to start localslackirc as a service and configure which user to use in the configuration file. .TP .B IP_ADDRESS Alternative to --ip .TP .B OVERRIDE_LOCAL_IP Alternative to --override .TP .B STATUS_FILE Path to the status file .TP .B AUTOJOIN Alternative to --autojoin .TP .B NOUSERLIST Alternative to --nouserlist .TP .B DEBUG Alternative to --debug .TP .B LOG_SUFFIX Alternative to --log-suffix .TP .B IGNORED_CHANNELS Alternative to --ignored-channels .TP .B SILENCED_YELLERS Alternative to --silenced-yellers .SH Additional IRC commands Some commands are added, to use some additional features that are present in slack but not IRC. .SS .TP .B /sendfile destination /path/to/file Sends the specified file to destination. .br The destination can be a user or a channel, in which case it must begin with #. .TP .B /annoy user [duration] The indicated user will be annoyed. .br This means that whenever a typing event is received from that user, on any channel, a type event on the same channel will be sent back, making the user think you are about to write something too. .br duration is the duration of the annoyance in minutes. It defaults to 10. .SS .SH WEB .BR https://github.com/ltworf/localslackirc .SH AUTHOR .nf Salvo "LtWorf" Tomaselli localslackirc/tests/__init__.py0000644000175000017500000000000014031401123016144 0ustar salvosalvolocalslackirc/tests/__main__.py0000644000175000017500000000167614040764225016170 0ustar salvosalvo# localslackirc # Copyright (C) 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 unittest from .test_re import * from .test_diff import * from .test_executable import * from .test_message_bot import * from .test_irc import * if __name__ == '__main__': unittest.main() localslackirc/tests/test_diff.py0000644000175000017500000000465114033164120016401 0ustar salvosalvo# localslackirc # Copyright (C) 2020-2021 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 unittest from diff import seddiff class TestDiff(unittest.TestCase): def test_no_crash(self): seddiff('', 'lalala') seddiff('lalala', 'lalala') seddiff('lalala', '') seddiff('lalala', 'lalala allelolela') seddiff('lalala allelolela', 'allelolela') seddiff('lalala allelolela', 'lalala') def test_no_diff(self): assert seddiff('ciao', 'ciao') == '' assert seddiff('', '') == '' assert seddiff('la la', 'la la') == '' def test_full_replace(self): assert seddiff('vado al mare', 'dormo la sera') == 's/vado al mare/dormo la sera/' assert seddiff('ciae å tuttï', 'ciao a tutti') == 's/ciae å tuttï/ciao a tutti/' def test_partials(self): assert seddiff('vado a dormire al mare', 'vado a nuotare al mare') == 's/dormire/nuotare/' assert seddiff('ciae a tutti', 'ciao a tutti') == 's/ciae/ciao/' assert seddiff('ciae å tutti', 'ciao a tutti') == 's/ciae å/ciao a/' def test_insertion(self): assert seddiff('il numero dei fili', 'il numero massimo dei fili') == 's/numero dei/numero massimo dei/' assert seddiff('mangio del formaggio e pere', 'mangio del formaggio con le pere') == 's/formaggio e pere/formaggio con le pere/' assert seddiff('mangio del formaggio e pere per cena', 'mangio del formaggio con le pere per cena') == 's/formaggio e pere/formaggio con le pere/' assert seddiff('mare blu', 'il mare blu') == 's/mare/il mare/' assert seddiff('mare, blu', 'il mare, blu') == 's/mare/il mare/' def test_append(self): assert seddiff('XYZ', 'XYZ (meaning "bla bla bla")') == 's/$/(meaning "bla bla bla")/' localslackirc/tests/test_executable.py0000644000175000017500000000166714122573712017630 0ustar salvosalvo# localslackirc # Copyright (C) 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 unittest import subprocess class TestStart(unittest.TestCase): def test_print_help(self): subprocess.check_call(['./localslackirc', '--help'], stdout=subprocess.DEVNULL) localslackirc/tests/test_irc.py0000644000175000017500000001013014136567635016261 0ustar salvosalvo# localslackirc # Copyright (C) 2021 Antonio Terceiro # # 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 . from unittest import IsolatedAsyncioTestCase, mock from irc import Client, Provider class TestIRC(IsolatedAsyncioTestCase): def setUp(self): stream_writer = mock.AsyncMock() slack_client = mock.AsyncMock() settings = mock.MagicMock() settings.silenced_yellers = set() settings.provider = Provider.SLACK self.client = Client(stream_writer, slack_client, settings) def b(s: str) -> bytes: return bytes(s, encoding="utf-8") class TestAnnoyanceAvoidance(TestIRC): async def test_yelling_prevention(self): self.client.nick = b'aldo' # Mention generated msg = await self.client.parse_message(" watch this!", b'rose.adams') assert msg == b'yelling [aldo]: watch this!' # Add rose.adams to silenced yellers self.client.settings.silenced_yellers.add(b'rose.adams') # Mention no longer generated msg = await self.client.parse_message(" watch this!", b'rose.adams') assert msg == b'yelling: watch this!' # No effect on regular messages msg = await self.client.parse_message("hello world", b'rose.adams') assert msg == b'hello world' class TestParseMessage(TestIRC): async def test_simple_message(self): msg = await self.client.parse_message("hello world", b'ciccio') self.assertEqual(msg, b"hello world") async def test_url(self): msg = await self.client.parse_message("See ", b'ciccio') self.assertEqual(msg, b("See the documentation¹\n ¹ https://example.com/docs/")) async def test_url_aggressive_shortening(self): msg = await self.client.parse_message("See ", b'ciccio') self.assertEqual(msg, b("See LINK¹\n ¹ https://example.com/docs/iqjweoijsodijijaoij?oiwje")) async def test_multiple_urls(self): msg = await self.client.parse_message("See . Try also the ", b'ciccio') self.assertEqual(msg, b("See the documentation¹. Try also the FAQ²\n ¹ https://example.com/docs/\n ² https://example.com/faq/")) async def test_a_lot_of_urls(self): input_msg = " " * 10 output = "\n".join([ "url¹ url² url³ url⁴ url⁵ url⁶ url⁷ url⁸ url⁹ url¹⁰ ", " ¹ https://example.com/", " ² https://example.com/", " ³ https://example.com/", " ⁴ https://example.com/", " ⁵ https://example.com/", " ⁶ https://example.com/", " ⁷ https://example.com/", " ⁸ https://example.com/", " ⁹ https://example.com/", " ¹⁰ https://example.com/", ]) msg = await self.client.parse_message(input_msg, b'ciccio') self.assertEqual(msg, b(output)) async def test_url_with_no_label_just_goes_inline(self): msg = await self.client.parse_message("Please look at ", b'ciccio') self.assertEqual(msg, b("Please look at https://example.com/")) async def test_dont_expand_urls_with_no_different_text(self): msg = await self.client.parse_message("", b'ciccio') self.assertEqual(msg, b"https://example.com/") localslackirc/tests/test_message_bot.py0000644000175000017500000000505214040764225017767 0ustar salvosalvo# localslackirc # Copyright (C) 2021 Antonio Terceiro # # 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 . import unittest from typedload import load from slack import MessageBot template = { "type": "message", "subtype": "bot_message", "text": "This is a message with attachments", "username": "BotExample", "channel": "XYZ123456", "bot_id": "ABC123456", } class TestMessageBot(unittest.TestCase): def test_without_attachments(self): event = template.copy() event.update({"text": "Message without attachments"}) msg = load(event, MessageBot) self.assertEqual(msg.text, "Message without attachments") def test_message_with_attachments(self): event = template.copy() event.update({ "attachments": [ {"text": "First attachment"}, {"text": "Second attachment"}, ] }) msg = load(event, MessageBot) assert ( msg.text == "This is a message with attachments\n| First attachment\n| Second attachment" ) def test_attachment_with_fallback(self): event = template.copy() event.update({ "attachments": [ {"fallback": "First attachment"}, {"fallback": "Second attachment"}, ], }) msg = load(event, MessageBot) assert ( msg.text == "This is a message with attachments\n| First attachment\n| Second attachment" ) def test_multiline_attachment_text(self): event = template.copy() event.update({ "attachments": [ {"text": "code example:\n```\nprint('Hello world')\n```"}, ] }) msg = load(event, MessageBot) self.assertEqual(msg.text.split("\n"), [ "This is a message with attachments", "| code example:", "| ```", "| print('Hello world')", "| ```" ]) localslackirc/tests/test_re.py0000644000175000017500000001103514040766752016112 0ustar salvosalvo# localslackirc # Copyright (C) 2020-2021 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 asyncio import unittest from pathlib import Path from irc import _MENTIONS_REGEXP, _CHANNEL_MENTIONS_REGEXP, _URL_REGEXP, Client, Provider, ClientSettings from slack import Channel, User class TestRegexp(unittest.TestCase): def test_channel_re(self): cases = [ ('lalala', None), ('#lalala', None), ('#lalala-lala', None), ('la #lalala la', None), ('la <#AAA|la lala> la', None), ('la <#AAA|lalala> la', ('AAA',)), ('la <#AAA|la-lala> la', ('AAA',)), ('la <#AAA|la_lala> la', ('AAA',)), ('la <#AAA|lå114-lala> la', ('AAA',)), ('la <#ABC91|lå114-lala> la', ('ABC91',)), ('la <#abC91|lå114-lala> la', None), ('la <#abC91|#alala> la', None), ] for url, expected in cases: m = _CHANNEL_MENTIONS_REGEXP.search(url) assert m is None if expected is None else m.groups() == expected def test_url_re(self): cases = [ # String, matched groups ('q1://p1|p', None), ('Pinnello ', ('q1', 'p1', 'p')), ('Pinnello asd asd', ('q1', 'p1', 'p')), (' asd asd', ('q1', 'p1', 'p')), (' asd asd', ('q1', 'p1', 'p a|')), (' asd asd', ('q1', 'p1', '')), ] for url, expected in cases: m = _URL_REGEXP.search(url) assert m is None if expected is None else m.groups() == expected class TestMagic(unittest.TestCase): def setUp(self): class MockClient: def __init__(self): self.members = set(('0', )) async def get_members(self, channels): return self.members async def get_user_by_name(self, username): return User(username, username, None) async def get_user(self, id_): return User('0', 'LtWorf', None) self.mock_client = MockClient() settings = ClientSettings( False, True, Provider.SLACK, set(), set(), Path('/tmp'), ) self.client = Client(None, self.mock_client, settings) def test_no_replace(self): ''' Check that no substitutions are done on regular strings and nickname in url ''' cases = [ 'ciao', 'http://LtWorf/', 'ciao https://link.com/LtWorf', 'ciao https://link.com/LtWorf?param', ] dest = Channel('0', '0', None, None) for i in cases: assert asyncio.run(self.client._addmagic(i, dest)) == i def test_escapes(self): dest = User('0', 'LtWorf', None) assert asyncio.run(self.client._addmagic('<', dest)) == '<' assert asyncio.run(self.client._addmagic('>ciao', dest)) == '>ciao' def test_annoyiances(self): dest = User('0', 'LtWorf', None) asyncio.run(self.client._addmagic('ciao @here', dest)) == 'ciao ' asyncio.run(self.client._addmagic('ciao @channel', dest)) == 'ciao ' asyncio.run(self.client._addmagic('ciao @everyone </' def test_mentions(self): dest = Channel('0', '0', None, None) assert asyncio.run(self.client._addmagic('ciao LtWorf', dest)) == 'ciao <@LtWorf>' assert asyncio.run(self.client._addmagic('LtWorf: ciao', dest)) == '<@LtWorf>: ciao' assert asyncio.run(self.client._addmagic('LtWorf: ciao LtWorf', dest)) == '<@LtWorf>: ciao <@LtWorf>' assert asyncio.run(self.client._addmagic('_LtWorf', dest)) == '_LtWorf' assert asyncio.run(self.client._addmagic('LtWorf: http://link/user=LtWorf', dest)) == '<@LtWorf>: http://link/user=LtWorf' localslackirc/localslackirc.d/0000755000175000017500000000000014040766752015761 5ustar salvosalvolocalslackirc/localslackirc.d/example0000644000175000017500000000331114040766752017335 0ustar salvosalvo# Example configuration file for localslackirc. # # The instances are to be launched with: # # systemctl start localslackirc@filename.service # # filename must be replaced with the filename of the # configuration file in /etc/localslackirc.d # # Make sure that the file is not world readable, since # it contains the access token. # # To start the instance at every boot # sudo systemctl enable localslackirc@filename.service # The port to listen to, for the IRC client to connect to #PORT=9007 # The token string #TOKEN=xxxx # The cookie string (Not always needed) #COOKIE=xxxx # The user that will be used to run this process. # Using nobody is fine, but it might be desirable to # change this to be able to send files which might not # be readable otherwise #PROCESS_OWNER=nobody # Auto join channels AUTOJOIN=true # Networking #IP_ADDRESS=127.0.0.1 # Do not enable this unless you know what you are doing! #OVERRIDE_LOCAL_IP=false # Do not fetch the user list (for huge instances) #NOUSERLIST=true # Comma separated list of channels to ignore and not automatically # join on IRC. # Ignored unless autojoin is set # They can be joined again later on with a /join #channel command #IGNORED_CHANNELS=#general,#chat # Where to create files for automatic downloads. # Make sure it is writable and has space #DOWNLOADS_DIRECTORY=/tmp/ # Maximum amount of lines for formatted messages # (the ones with ```) to be # allowed within IRC. # Messages exceeding the limit will be stored as # text files in # DOWNLOADS_DIRECTORY. # 0 means no limit #FORMATTED_MAX_LINES=0 # Comma separated list of nicknames not allowed to use general mentions #SILENCED_YELLERS=rose.adams,alfio.cuttigghiu # Debugging (disabled by default) # DEBUG=1 localslackirc/systemd/0000755000175000017500000000000013646103163014411 5ustar salvosalvolocalslackirc/systemd/localslackirc@.service0000644000175000017500000000253313646103163020704 0ustar salvosalvo# localslackirc # Copyright (C) 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 [Install] WantedBy=multi-user.target [Unit] Description=Localslackirc Documentation=man:localslackirc(1) AssertPathExists=/etc/localslackirc.d/%i PartOf=localslackirc.service ReloadPropagatedFrom=localslackirc.service Before=localslackirc.service [Service] Type=simple Restart=always ExecStart=/usr/bin/localslackirc --status-file /var/tmp/localslackirc-status-%i --log-suffix %i # Log StandardOutput=journal StandardError=journal SyslogIdentifier=localslackirc-%i # Config EnvironmentFile=/etc/localslackirc.d/%i # Security ProtectSystem=strict ReadWritePaths=/var/tmp PrivateDevices=true LockPersonality=true localslackirc/systemd/localslackirc.service0000644000175000017500000000215313637443613020611 0ustar salvosalvo# localslackirc # Copyright (C) 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 # systemd service for managing all localslackirc instances on the system. This # service is actually a systemd target, but we are using a service since # targets cannot be reloaded. [Unit] Description=Localslackirc Documentation=man:localslackirc(1) [Service] Type=oneshot ExecStart=/bin/true ExecReload=/bin/true RemainAfterExit=on [Install] WantedBy=multi-user.target localslackirc/mypy.conf0000644000175000017500000000022414122573712014565 0ustar salvosalvo[mypy] python_version=3.8 warn_unused_ignores=False warn_redundant_casts=True strict_optional=True scripts_are_modules=True check_untyped_defs=True