localslackirc/localslackirc0000775000175000017500000000160114634376111015460 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/control.py0000664000175000017500000000372114634376111014763 0ustar salvosalvo# localslackirc # Copyright (C) 2023 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 from typing import TYPE_CHECKING if TYPE_CHECKING: from irc import Client as IrcClient from log import * async def handle_write(ircclient: "IrcClient", reader, writer) -> None: dest = (await reader.readline()).strip() msg = await reader.read() await ircclient.send_slack_message(dest, msg, action=False, re_send_to_irc=True) async def handle_sendfile(ircclient: "IrcClient", reader, writer) -> None: dest = (await reader.readline()).strip() filename = (await reader.readline()).strip().decode('utf8') content = await reader.read() if await ircclient.send_file(dest, content, filename=filename): writer.write(b"ok") else: writer.write(b"fail") async def handle_client(ircclient: "IrcClient", reader, writer) -> None: command = (await reader.readline()).strip() if command == b"sendfile": await handle_sendfile(ircclient, reader, writer) elif command == b"write": await handle_write(ircclient, reader, writer) async def listen(socket_path: str, ircclient: "IrcClient") -> None: server = await asyncio.start_unix_server(lambda r,w: handle_client(ircclient, r, w), socket_path) async with server: await server.serve_forever() localslackirc/diff.py0000664000175000017500000000364115026423607014213 0ustar salvosalvo# localslackirc # Copyright (C) 2018-2022 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 = frozenset(' .,:;\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 Exception: 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/irc.py0000664000175000017500000014076315027356570014074 0ustar salvosalvo# localslackirc # Copyright (C) 2018-2025 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 NamedTuple, Iterable import os from os import environ from os.path import expanduser import pwd from socket import gethostname import sys import time import slack from log import * import msgparsing from diff import seddiff VERSION = '1.35' class IrcDisconnectError(Exception): ... class Replies(Enum): RPL_LUSERCLIENT = 251 RPL_AWAY = 301 RPL_USERHOST = 302 RPL_ISON = 303 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_CANNOTSENDTOCHAN = 404 ERR_UNKNOWNCOMMAND = 421 ERR_FILEERROR = 424 ERR_ERRONEUSNICKNAME = 432 ERR_NEEDMOREPARAMS = 461 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 no_rejoin_on_mention: bool provider: Provider ignored_channels: set[bytes] silenced_yellers: set[bytes] downloads_directory: Path formatted_max_lines: int = 0 def verify(self) -> str | None: ''' Make sure that the configuration is correct. In that case return None. Otherwise an error string. ''' if not self.downloads_directory.exists(): try: self.downloads_directory.mkdir(parents=True) except Exception: return f'Unable to create {self.downloads_directory}' elif not self.downloads_directory.is_dir(): return f'{self.downloads_directory} is not a directory' if self.formatted_max_lines and not os.access(self.downloads_directory, os.W_OK | os.R_OK | os.X_OK): return f'Insufficient permissions on downloads directory: {self.downloads_directory}' return None class Client: def __init__( self, s: asyncio.streams.StreamWriter, sl_client: slack.Slack, settings: ClientSettings, ): self.nick = b'' self.username = b'' self.realname = b'' self.parted_channels: set[bytes] = settings.ignored_channels self.known_threads: dict[bytes, slack.MessageThread] = {} 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, re.Pattern | None] = {} # Cache for the regexp to perform mentions. Key is channel id def get_mention_str(self) -> str: ''' Returns the string that is present in messages when the user is getting mentioned ''' return f'<@{self.sl_client.login_info.self.id if self.sl_client.login_info else ""}>' 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: int|Replies, message: str|bytes, extratokens: Iterable[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(2, f'Version: {VERSION}') await self._sendreply(Replies.RPL_LUSERCLIENT, 'There are 1 users and 0 services on 1 server') await self._sendreply(2, '============= Extra IRC commands supported =============') await self._sendreply(2, '/annoy') await self._sendreply(2, '/dropannoy') await self._sendreply(2, '/listannoy') await self._sendreply(2, '/autoreact') await self._sendreply(2, '/dropautoreact') await self._sendreply(2, '/listautoreact') await self._sendreply(2, '/sendfile') 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.joined_channels(): if not sl_chan.is_member: continue if sl_chan.is_mpim and ((sl_chan.updated / 1000) < mpim_cutoff.timestamp()): 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.joined_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_names_b = cmd.split(b' ', 1) for channel_name_b in channel_names_b.split(b','): 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}') continue 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|slack.MessageThread): if not self.settings.nouserlist: l = await self.sl_client.get_members(slchan.id) userlist: list[bytes] = [] for i in l: 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) try: yelldest = b'#' + (await self.sl_client.get_channel(slchan.id)).name.encode('utf8') except KeyError: yelldest = b'' topic = (await self.parse_message(slchan.real_topic, b'', yelldest)).replace('\n', ' | ') 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, 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 await self.send_slack_message(dest, msg, action, False) async def send_slack_message(self, dest: bytes, msg: bytes, action: bool, re_send_to_irc: bool) -> None: if dest in self.known_threads: dest_object: slack.User|slack.Channel|slack.MessageThread = self.known_threads[dest] elif dest.startswith(b'#'): try: dest_object = await self.sl_client.get_channel_by_name(dest[1:].decode()) except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unknown channel {dest.decode()}') return else: try: dest_object = await self.sl_client.get_user_by_name(dest.decode()) except KeyError: await self._sendreply(Replies.ERR_NOSUCHNICK, f'Unknown user {dest.decode()}') return message = await self._addmagic(msg.decode('utf8'), dest_object) try: if isinstance(dest_object, slack.User): await self.sl_client.send_message_to_user( dest_object, message, action, re_send_to_irc, ) else: await self.sl_client.send_message( dest_object, message, action, re_send_to_irc ) except Exception as e: await self._sendreply(Replies.ERR_CANNOTSENDTOCHAN, f'Message sending failed: {e}') async def _listhandler(self, cmd: bytes) -> None: for c in await self.sl_client.channels(refresh=True): topic = (await self.parse_message(c.real_topic, b'', b'')).replace('\n', ' | ') await self._sendreply(Replies.RPL_LIST, 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 _autoreacthandler(self, cmd: bytes) -> None: params = cmd.split(b' ') params.pop(0) try: username = params.pop(0).decode('utf8') probability = float(params.pop(0)) if params: reaction = msgparsing.get_emoji_code(params.pop(0).decode('utf8')) else: reaction = 'thumbsup' if params: duration = int(params.pop(0)) else: duration = 10 if duration < 1 and duration != -1: raise ValueError('Duration must be >0 or = -1') # async def add_autoreact(self, username: str, reaction: str, probability: float, expiration: int) -> None: await self.sl_client.add_autoreact(username, reaction, probability, time.time() + duration * 60 if duration != -1 else -1) except Exception as e: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /autoreact user probability [reaction] [duration]') await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, f'error: {e}') return await self._sendreply(0, f'Will react to {username} for {duration} minutes') async def _annoyhandler(self, cmd: bytes) -> None: params = cmd.split(b' ') params.pop(0) try: user = params.pop(0).decode('utf8') if params: duration = int(params.pop()) else: duration = 10 # 10 minutes default if duration < 1 and duration != -1: raise ValueError("Duration must be positive or -1") await self.sl_client.add_annoy(user, time.time() + (duration * 60) if duration > 0 else duration) except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find user: {user}') return except Exception: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /annoy user [duration]') return await self._sendreply(0, f'Will annoy {user} for {duration} minutes') async def _dropannoyhandler(self, cmd: bytes) -> None: try: user = cmd.split(b' ', 1)[1].decode('utf8') await self.sl_client.drop_annoy(user) except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find user: {user}') return except Exception: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /dropannoy user') return await self._sendreply(0, f'No longer annoying {user}') async def _dropautoreacthandler(self, cmd: bytes) -> None: try: user = cmd.split(b' ', 1)[1].decode('utf8') await self.sl_client.drop_autoreact(user) except KeyError: await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find user: {user}') return except Exception: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /dropautoreact user') return await self._sendreply(0, f'No longer reacting to {user}') async def _listannoyhandler(self, _: bytes) -> None: for i in await self.sl_client.get_annoy(): await self._sendreply(0, f'Annoying {i}') async def _listautoreacthandler(self, _: bytes) -> None: for k, v in (await self.sl_client.get_autoreact()).items(): await self._sendreply(0, f'Reactions for {k}') for i in v: await self._sendreply(0, str(i)) async def _sendfilehandler(self, cmd: bytes) -> None: #/sendfile #destination filename try: params = cmd.split(b' ', 2) filename = params[2].decode('utf8') except IndexError: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /sendfile #channel filename') return try: with open(filename, 'rb') as f: content = f.read() await self.send_file(params[1], content=content, filename=filename) except Exception as e: await self._sendreply(Replies.ERR_FILEERROR, f'Error: {e}') async def send_file(self, bchannel_name: bytes, content: bytes, filename: str) -> bool: channel_name = bchannel_name.decode('utf8') if bchannel_name in self.known_threads: dest_channel = self.known_threads[bchannel_name] dest = dest_channel.id thread_ts = dest_channel.thread_ts else: thread_ts = None 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 False try: await self.sl_client.send_file(dest, content=content, filename=filename, thread_ts=thread_ts) await self._sendreply(0, 'Upload completed') return True except Exception as e: await self._sendreply(Replies.ERR_FILEERROR, f'Unable to send file {e}') return False async def _parthandler(self, cmd: bytes) -> None: name = cmd.split(b' ')[1] self.parted_channels.add(name) if name in self.known_threads: del self.known_threads[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 _caphandler(self, cmd: bytes) -> None: # Do absolutely nothing # support for capabilities is not implemented # so we just ignore it return async def _isonhandler(self, cmd: bytes) -> None: users = cmd.split(b' ') del users[0] r = [] if len(users) < 1: await self._sendreply(Replies.ERR_NEEDMOREPARAMS, 'Syntax: /ison nickname') return for username in users: if b'*' in username: await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Wildcards are not supported') continue uusername = username.decode() try: user = await self.sl_client.get_user_by_name(uusername) except KeyError: continue if not await self.sl_client.isAway(user): r.append(username) await self._sendreply( Replies.RPL_ISON, b' '.join(r), ) 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]) if await self.sl_client.isAway(user): await self._sendreply(Replies.RPL_AWAY, f'{uusername} is away', extratokens=[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: slack.User|slack.Channel) -> re.Pattern | None: #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: slack.User|slack.Channel) -> str: """ Adds magic codes and various things to outgoing messages """ for i in msgparsing.SLACK_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, destination: bytes) -> str: """ This converts a slack message into a message for IRC. It will replace mentions and shouts with the IRC equivalent. It will save preformatted text into txt files and link them if the settings are such. It will put the links at the end like with emails. """ r = '' # Url replacing links = '' refs = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹") refn = 1 for t in msgparsing.tokenize(i): if isinstance(t, str): # A normal nice string r += t elif isinstance(t, msgparsing.PreBlock): # Preformatted block # Store long formatted text into txt files if self.settings.formatted_max_lines and t.lines > 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(t.txt) r += f'\n === PREFORMATTED TEXT AT file://{tmpfile.name}\n' else: # Do not store to file r += f'```{t.txt}```' elif isinstance(t, msgparsing.SpecialItem): if t.kind == msgparsing.Itemkind.MENTION: # User mention r += (await self.sl_client.get_user(t.val)).name elif t.kind == msgparsing.Itemkind.CHANNEL: # Channel mention try: r += '#' + (await self.sl_client.get_channel(t.val)).name_normalized except KeyError: # Slack might decide to send id of channels that do not exist, yes… r += '#ERROR_MISSING_CHANNEL' elif t.kind == msgparsing.Itemkind.YELL: # Channel shouting if (source not in self.settings.silenced_yellers) and (destination not in self.settings.silenced_yellers): yell = ' [%s]:' % self.nick.decode('utf8') else: yell = ':' if t.val == 'here': r += 'yelling' + yell elif t.val == 'channel': r += 'YELLING LOUDER' + yell else: r += 'DEAFENING YELL' + yell else: # Link label = t.human if label is None: r += t.val else: if '://' in label: label = 'LINK' ref = str(refn).translate(refs) links += f'\n {ref} {t.val}' r += label + ref refn += 1 return r + links async def _messageedit(self, sl_ev: slack.MessageEdit) -> None: if not sl_ev.is_changed: return try: yelldest = b'#' + (await self.sl_client.get_channel(sl_ev.channel)).name.encode('utf8') except KeyError: yelldest = b'' source = (await self.sl_client.get_user(sl_ev.previous.user)).name.encode('utf8') previous = await self.parse_message(sl_ev.previous.text, source, yelldest) current = await self.parse_message(sl_ev.current.text, source, yelldest) diffmsg = slack.Message( text=seddiff(sl_ev.previous.text, sl_ev.current.text), channel=sl_ev.channel, user=sl_ev.previous.user, thread_ts=sl_ev.previous.thread_ts, ts=sl_ev.previous.ts, ) await self._message(diffmsg) async def _message(self, sl_ev: 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: yelldest = dest = b'#' + (await self.sl_client.get_channel(sl_ev.channel)).name.encode('utf8') except KeyError: dest = self.nick yelldest = b'' except Exception as e: log('Error: ', str(e)) return text = sl_ev.text mentioned = (not self.settings.no_rejoin_on_mention) and self.get_mention_str() in text if sl_ev.thread_ts: # Threaded message, rewriting the dest thread = await self.sl_client.get_thread(sl_ev.thread_ts, sl_ev.channel) original_dest = dest dest = b'#' + thread.name.encode('utf8') if dest in self.parted_channels: if mentioned: self.parted_channels.remove(dest) else: # This thread is being ignored return # Join thread channel if needed if dest not in self.known_threads: if original_dest in self.parted_channels and not mentioned: # Ignoring new threads from a parted channel # but keeping the known ones active return await self._send_chan_info(dest, self.known_threads.get(dest, thread)) self.known_threads[dest] = self.known_threads.get(dest, thread) elif dest in self.parted_channels: if mentioned: # rejoin channel slchan = await self.sl_client.get_channel(sl_ev.channel) await self._send_chan_info(dest, slchan) else: # Ignoring messages, channel was left on IRC # This ignores also threads on those channels return if sl_ev.files: for f in sl_ev.files: text+=f'\n[file upload] {f.name}\n{f.mimetype} {f.size} bytes\n{f.url_private}' lines = (await self.parse_message(prefix + text, source, yelldest)).encode('utf-8') 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: 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): await self._messageedit(sl_ev) elif isinstance(sl_ev, slack.MessageBot): await self._message(sl_ev, '[%s] ' % sl_ev.username) 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) or isinstance(sl_ev, slack.MpimJoined): channel_name = '#%s' % sl_ev.channel.name_normalized await self._send_chan_info(channel_name.encode('utf-8'), sl_ev.channel) async def command(self, cmd: bytes) -> None: if b' ' in cmd: cmdid, _ = cmd.split(b' ', 1) else: cmdid = cmd # commands are case insensitive cmdid = cmdid.upper() 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'LISTANNOY': self._listannoyhandler, b'DROPANNOY': self._dropannoyhandler, b'AUTOREACT': self._autoreacthandler, b'LISTAUTOREACT': self._listautoreacthandler, b'DROPAUTOREACT': self._dropautoreacthandler, b'QUIT': self._quithandler, b'USERHOST': self._userhosthandler, b'WHOIS': self._whoishandler, b'ISON': self._isonhandler, b'CAP': self._caphandler, } 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( description='Creates an IRC server running locally, which acts as a gateway to slack for one user.' ) 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('--no-rejoin-on-mention', action='store_true', dest='no_rejoin_on_mention', help='If set, mentions of the username will not cause the channel to be re-joined') 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='.', 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') parser.add_argument('--control-socket', type=str, action='store', dest='control_socket', default=None, help='Path to where the unix control socket will be') args = parser.parse_args() openlog(environ.get('LOG_SUFFIX', args.log_suffix)) set_debug(environ.get('DEBUG', args.debug)) status_file_str: str | None = 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: abort('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 no_rejoin_on_mention: bool = environ['NO_REJOIN_ON_MENTION'].lower() == 'true' if 'NO_REJOIN_ON_MENTION' in environ else args.no_rejoin_on_mention # 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: abort('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() control_socket = environ.get('CONTROL_SOCKET', args.control_socket) if 'TOKEN' in environ: token = environ['TOKEN'] else: try: with open(args.tokenfile) as f: token = f.readline().strip() except IsADirectoryError: abort(f'Not a file {args.tokenfile}') except (FileNotFoundError, PermissionError): abort(f'Unable to open the token file {args.tokenfile}') if 'COOKIE' in environ: cookie: str | None = environ['COOKIE'] else: try: if args.cookiefile: with open(args.cookiefile) as f: cookie = f.readline().strip() else: cookie = None except (FileNotFoundError, PermissionError): abort(f'Unable to open the cookie file {args.cookiefile}') except IsADirectoryError: abort(f'Not a file {args.cookiefile}') if token.startswith('xoxc-') and not cookie: abort('The cookie is needed for this kind of slack token') provider = Provider.SLACK # Parameters are dealt with async def irc_listener() -> None: previous_status = None if status_file is not None: if status_file.exists(): if not os.access(status_file, os.O_RDWR): abort('Status file needs to have read write permissions') previous_status = status_file.read_bytes() else: try: status_file.write_bytes(b'') except Exception as e: abort(f'Failure when creating the status file {e}') clientsettings = ClientSettings( nouserlist=nouserlist, no_rejoin_on_mention=no_rejoin_on_mention, 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: abort(verify) 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) serversocket.setblocking(False) s, _ = await asyncio.get_running_loop().sock_accept(serversocket) serversocket.close() reader, writer = await asyncio.open_connection(sock=s) sl_client = slack.Slack(token, cookie, previous_status) await sl_client.login() 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)) if control_socket: import control control_task = asyncio.create_task(control.listen(control_socket, ircclient)) else: control_task = None if control_task: await asyncio.gather( from_irc_task, to_irc_task, control_task, ) else: 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() if control_task: control_task.cancel() async def restart_listener_loop(): loop = asyncio.get_running_loop() loop.add_signal_handler(signal.SIGHUP, term_f) loop.add_signal_handler(signal.SIGTERM, term_f) loop.add_signal_handler(signal.SIGINT, term_f) while True: try: await irc_listener() except IrcDisconnectError: log('IRC disconnected') asyncio.run(restart_listener_loop()) 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: 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/log.py0000664000175000017500000000362715027356570014075 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 import sys from syslog import LOG_INFO, LOG_DEBUG, syslog, LOG_ERR from syslog import openlog as _openlog __all__ = [ 'log', 'openlog', 'set_debug', 'debug', 'error', 'abort', ] 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, log_level=LOG_INFO) -> None: """ Logs to stdout or to syslog depending on if running with a terminal attached. """ if tty: if log_level in {LOG_DEBUG, LOG_INFO}: f = sys.stdout else: f = sys.stderr print(*args,file=f) return syslog(log_level, ' '.join(str(i) for i in args)) def set_debug(state: str|bool) -> None: global debug_enabled debug_enabled = bool(state) def debug(*args) -> None: log(*args, log_level=LOG_DEBUG) def error(*args) -> None: log(*args, log_level=LOG_ERR) def abort(*args) -> None: log(*args, log_level=LOG_ERR) sys.exit(1) localslackirc/lsi-cli.py0000775000175000017500000001023714634376111014642 0ustar salvosalvo#!/usr/bin/env python3 # localslackirc # Copyright (C) 2023-2024 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 argparse import os import sys import socket def lsi_write(): parser = argparse.ArgumentParser( description='Send a message to a slack user or channel.' ) parser.add_argument('--control-socket', type=str, action='store', dest='control_socket', default=None, help='Path to the localslackirc unix control socket') parser.add_argument(type=str, action='store', dest='destination', help='Destination user or channel') args = parser.parse_args() control_socket = args.control_socket or find_socket() if not control_socket: sys.exit('Please specify the path to the socket') while data := sys.stdin.readline(): s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(control_socket) s.send(b'write\n') s.send(args.destination.encode('utf8') + b'\n') s.send(data.encode('utf8')) s.shutdown(socket.SHUT_WR) def lsi_send(): parser = argparse.ArgumentParser( description='Send a file to a slack user or channel.' ) parser.add_argument('-f', '--filename', type=str, action='store', dest='filename', help='Name to give to the file', default='filename') parser.add_argument('--control-socket', type=str, action='store', dest='control_socket', default=None, help='Path to the localslackirc unix control socket') parser.add_argument('-F', '--file', type=str, action='store', dest='source', help='Path of the file to send. If not specified stdin is used', default=None) parser.add_argument(type=str, action='store', dest='destination', help='Destination user or channel') args = parser.parse_args() if args.source: args.filename = args.source.split('/')[-1] control_socket = args.control_socket or find_socket() if not control_socket: sys.exit('Please specify the path to the socket') s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(control_socket) assert '\n' not in args.destination assert '\n' not in args.filename s.send(b'sendfile\n') s.send(args.destination.encode('utf8') + b'\n') s.send(args.filename.encode('utf8') + b'\n') if args.source: with open(args.source, "rb") as f: while chunk := f.read(4096): s.send(chunk) else: while chunk := sys.stdin.buffer.read(1024): s.send(chunk) s.shutdown(socket.SHUT_WR) response = s.recv(1024).decode('utf8') print(response) if response != 'ok': sys.exit(1) def main() -> None: cmdname = sys.argv[0].split('/')[-1] if cmdname == 'lsi-send': lsi_send() elif cmdname == 'lsi-write': lsi_write() def find_socket() -> None | str: ''' Returns the control socket of localslackirc or raises It looks in the runtime directory used in the .service file and looks for sockets in that directory. ''' RUNDIR = '/run/localslackirc/' candidates = [] try: for s in os.listdir(RUNDIR): if os.access(RUNDIR + s, os.W_OK | os.R_OK | os.X_OK): candidates.append(RUNDIR + s) if len(candidates) == 1: return candidates[0] except Exception: pass return None if __name__ == '__main__': try: main() except KeyboardInterrupt: pass localslackirc/msgparsing.py0000664000175000017500000001312615026423607015454 0ustar salvosalvo# localslackirc # Copyright (C) 2022-2025 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 enum import Enum from typing import Iterable, NamedTuple try: from emoji import emojize, demojize # type: ignore except ModuleNotFoundError: def emojize(string:str, *args, **kwargs) -> str: # type: ignore return string def demojize(string, str, delimiters: tuple[str, str]) -> str: # type: ignore return string SLACK_SUBSTITUTIONS = [ ('&', '&'), ('>', '>'), ('<', '<'), ] __all__ = [ 'SLACK_SUBSTITUTIONS', 'tokenize', 'Itemkind', 'PreBlock', 'SpecialItem', 'get_emoji_code', ] def get_emoji_code(msg: str) -> str: ''' Pass a single emoji and get the code without delimiters. ''' return demojize(msg, ('', '')) def preblocks(msg: str) -> Iterable[tuple[str, bool]]: """ Iterates the preformatted and normal text blocks in the message. The boolean indicates if the block is preformatted. The three ``` ticks are removed by this. """ pre = False while True: try: p = msg.index('```') except ValueError: break yield msg[0:p], pre pre = not pre msg = msg[p+3:] yield msg, pre class Itemkind(Enum): YELL = 0 # HERE, EVERYONE and such MENTION = 1 # @user CHANNEL = 2 # #channel OTHER = 3 # Everything else class PreBlock(NamedTuple): """ Block of preformatted text """ txt: str @property def lines(self) -> int: return self.txt.count('\n') class SpecialItem(NamedTuple): """ A link or a mention """ txt: str @property def kind(self) -> Itemkind: k = self.txt[1] if k == '!': return Itemkind.YELL elif k == '@': return Itemkind.MENTION elif k == '#': return Itemkind.CHANNEL return Itemkind.OTHER @property def val(self) -> str: """ Return the value """ sep = self.txt.find('|') # No human readable, just take the whole thing if sep == -1: sep = len(self.txt) - 1 if self.kind != Itemkind.OTHER: return self.txt[2:sep] return self.txt[1:sep] @property def human(self) -> str | None: """ Return the eventual human readable message """ sep = self.txt.find('|') if sep == -1: return None return self.txt[sep+1:-1] def split_tokens(msg: str) -> Iterable[SpecialItem|str]: """ yields separately the normal text and the special slack items """ while True: try: begin = msg.index('<') except ValueError: break if begin != 0: # There is stuff before yield msg[0:begin] msg = msg[begin:] else: # Tag at the beginning try: # Sometimes the fuckers at slack do not escape # the < string, so if we can't find the matching closing # let's return it as a string and hope for the best end = msg.index('>') except ValueError: break block = msg[0:end + 1] msg = msg[end + 1:] yield SpecialItem(block) if msg: yield msg def convertpre(msg: str) -> str: """ Fixes a preformatted block so that it can be displayed by an irc client. Links can be present in preformatted blocks with the format and MAYBE with but no channel or user mentions are allowed, and emoji substitution should not happen here. """ r = [] for t in split_tokens(msg): if isinstance(t, str): r.append(t) continue if t.kind != Itemkind.OTHER: raise ValueError(f'Unexpected slack item in preformatted block {t}') elif t.human: # For some very strange reason slack converts text like "asd.com" into links r.append(t.human) else: r.append(t.val) l = ''.join(r) for s in SLACK_SUBSTITUTIONS: l = l.replace(s[0], s[1]) return l def tokenize(msg: str) -> Iterable[PreBlock|SpecialItem|str]: """ Yields the various possible tokens Changes the > codes Puts the emoji in place """ try: for txt, pre in preblocks(msg): if pre: yield PreBlock(convertpre(txt)) else: for t in split_tokens(txt): if isinstance(t, str): # Replace emoji codes (e.g. :thumbsup:) t = emojize(t, language='alias') # Usual substitutions for s in SLACK_SUBSTITUTIONS: t = t.replace(s[0], s[1]) # type: ignore yield t except Exception as e: yield f'ERROR: cannot parse: {msg!r}' localslackirc/slack.py0000664000175000017500000010562215026423607014402 0ustar salvosalvo# localslackirc # Copyright (C) 2018-2025 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 Literal, Any, NamedTuple, Sequence, Type, TypeVar from typedload import dataloader from slackclient import SlackClient from slackclient.client import LoginInfo from log import log, debug T = TypeVar('T') USELESS_EVENTS = frozenset(( 'user_interaction_changed', # undocumented event 'clear_mention_notification', # undocumented event 'update_global_thread_state', # undocumented event 'update_thread_state', # undocumented event 'thread_marked', # undocumented event 'im_marked', 'pref_change', 'draft_create', 'draft_delete', 'accounts_changed', 'channel_marked', 'group_marked', 'mpim_marked', 'hello', 'dnd_updated_user', 'reaction_added', 'file_deleted', 'file_public', 'file_created', 'file_shared', 'desktop_notification', 'mobile_in_app_notification', 'goodbye', # Server is disconnecting us )) class ResponseException(Exception): pass class Response(NamedTuple): """ Internally used to parse a response from the API. """ ok: bool headers: dict[str, str] ts: float | None = None error: str | None = None @dataclass class DeletedFile: file_access: Literal['file_not_found'] @dataclass class Presence: presence: Literal["active", "away"] def away(self) -> bool: return self.presence == "away" @dataclass class File: file_access: Literal['visible'] id: str url_private: str size: int user: str name: str | None = None title: str | None = None mimetype: str | None = None @dataclass class TabutuFile: """ 'un sacciu chi minchia è sta cosa. Sacciu sulu ca slack u manna """ id: str mode: Literal['tombstone'] 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) @dataclass(frozen=True) class Channel: """ 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 # Last updated? updated: int = 0 latest: LatestMessage | None = 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 @dataclass(frozen=True) class MessageThread(Channel): thread_ts: str = '' @dataclass(frozen=True) class Message: channel: str # The channel id user: str # The user id text: str ts: float thread_ts: str | None = None files: list[File] = field(default_factory=list) class NoChanMessage(NamedTuple): user: str text: str ts: float thread_ts: str | None = None class ActionMessage(Message): pass @dataclass class GroupJoined: type: Literal['group_joined'] channel: Channel @dataclass class MpimJoined: type: Literal['mpim_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 @dataclass class MessageDelete: type: Literal['message'] subtype: Literal['message_deleted'] channel: str previous_message: NoChanMessage files: list[File] = field(default_factory=list) @property def thread_ts(self) -> str | None: return self.previous_message.thread_ts @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: str | None = None status_text: str = '' is_restricted: bool = False is_ultra_restricted: bool = False @dataclass class MessageBot: type: Literal['message'] subtype: Literal['bot_message'] _text: str = field(metadata={'name': 'text'}) username: str channel: str bot_id: str | None = None attachments: list[dict[str, Any]] = field(default_factory=list) thread_ts: str | None = None files: list[File] = 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 is_user_deleted: bool 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: str | None username: str = 'bot' ts: float = 0 files: list[File | DeletedFile | TabutuFile] = field(default_factory=list) thread_ts: str | None = 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 | DeletedFile | TabutuFile] = field(default_factory=list) thread_ts: str | None = None class NextCursor(NamedTuple): next_cursor: str class History(NamedTuple): ok: Literal[True] messages: list[HistoryMessage|HistoryBotMessage] has_more: bool response_metadata: NextCursor | None = None class Conversations(NamedTuple): channels: list[Channel] response_metadata: NextCursor | None = None SlackEvent = ( TopicChange| MessageDelete| MessageEdit| Message| ActionMessage| MessageBot| Join| Leave| GroupJoined| MpimJoined| UserTyping ) class Autoreaction(NamedTuple): reaction: str probability: float expiration: float @property def expired(self) -> bool: if self.expiration == -1: return False return time() > self.expiration def random_reaction(self) -> bool: import random return random.random() < self.probability def __str__(self): return f'{self.reaction} at {self.probability * 100}%' @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 autoreactions: dict[str, list[Autoreaction]] = field(default_factory=dict) annoy: dict[str, float] = field(default_factory=dict) class Slack: def __init__(self, token: str, cookie: str | None, previous_status: bytes | None) -> 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._imcache: dict[str, str] = {} self._channelscache: list[Channel] = [] self._joinedchannelscache: list[Channel] = [] self._get_members_cache: dict[str, set[str]] = {} self._get_members_cache_cursor: dict[str, str | None] = {} 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: LoginInfo | None = None self.loader = dataloader.Loader() if previous_status is None: self._status = SlackStatus() else: self._status = self.tload(json.loads(previous_status), SlackStatus) def close(self): del self.client def tload(self, data: Any, type_: Type[T]) -> T: return self.loader.load(data, type_) async def login(self) -> None: """ Set the login_info field """ log('Login in slack') self.login_info = await self.client.login(15) async def get_history(self, channel: Channel|IM|str, ts: str, cursor: NextCursor | None=None, limit: int=1000, inclusive: bool=False) -> History: p = await self.client.api_call( 'conversations.history', channel=channel if isinstance(channel, str) else channel.id, oldest=ts, limit=limit, cursor=cursor.next_cursor if cursor else None, inclusive=inclusive, ) return self.tload(p, History) async def _thread_history(self, channel: str, thread_id: str) -> list[HistoryMessage|HistoryBotMessage]: r: list[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 = self.tload(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. ''' if self._status.last_timestamp == 0: log('No last known timestamp. Unable to fetch history') return log('Fetching history...') 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 try: dt = datetime.datetime.fromtimestamp(last_timestamp) except ValueError: log(f'Unable to parse timestamp {last_timestamp}') return log(f'Last known timestamp {dt}') chats: Sequence[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') try: response = await self.get_history(channel, str(last_timestamp)) except Exception as e: log('Failed to parse', e) 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 # 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, thread_ts=msg.thread_ts, files=[i for i in msg.files if isinstance(i, File)], ts=msg.ts, )) 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, thread_ts=msg.thread_ts, )) if response.has_more and response.response_metadata: next_cursor = response.response_metadata.next_cursor if next_cursor == cursor: break cursor = next_cursor else: break def get_status(self) -> bytes: ''' A status string that will be passed back when this is started again ''' from typedload import dump 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 = self.tload(r, Response) if not response.ok: raise ResponseException(response.error) async def typing(self, channel: 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 add_reaction(self, msg: Message, reaction: str) -> None: r = await self.client.api_call( 'reactions.add', channel=msg.channel, timestamp=msg.ts, name=reaction, ) response = self.tload(r, Response) if not response.ok: raise ResponseException(response.error) async def add_annoy(self, username: str, expiration: float) -> None: user_id = (await self.get_user_by_name(username)).id self._status.annoy[user_id] = expiration async def drop_annoy(self, username: str) -> None: user_id = (await self.get_user_by_name(username)).id del self._status.annoy[user_id] async def drop_autoreact(self, username: str) -> None: user_id = (await self.get_user_by_name(username)).id del self._status.autoreactions[user_id] async def get_annoy(self) -> list[str]: r = [] for i in self._status.annoy.keys(): try: u = await self.get_user(i) r.append(u.name) except KeyError: # The user is gone, expire it self._status.annoy[i] = 1 r.sort() return r async def get_autoreact(self) -> dict[str, list[Autoreaction]]: return {(await self.get_user(k)).name: v for k, v in self._status.autoreactions.items()} async def add_autoreact(self, username: str, reaction: str, probability: float, expiration: float) -> None: if probability > 1 or probability < 0: raise ValueError(f'Probability must be comprised between 0 and 1') user_id = (await self.get_user_by_name(username)).id a = Autoreaction( reaction=reaction, probability=probability, expiration=expiration, ) if a.expired: raise ValueError('Expired') if user_id not in self._status.autoreactions: self._status.autoreactions[user_id] = [] self._status.autoreactions[user_id].append(a) async def _annoy(self, typing: UserTyping) -> None: if typing.user not in self._status.annoy: return expiration = self._status.annoy[typing.user] if expiration > 0 and time() > expiration: del self._status.annoy[typing.user] await self.typing(typing.channel) async def _autoreact(self, msg: Message) -> None: for i in (rlist := self._status.autoreactions.get(msg.user, [])): # Clean up if i.expired: rlist.remove(i) return if i.random_reaction(): try: await self.add_reaction(msg, i.reaction) except Exception: # Remove reactions that fail rlist.remove(i) return async def topic(self, channel: Channel, topic: str) -> None: r = await self.client.api_call('conversations.setTopic', channel=channel.id, topic=topic) response: Response = self.tload(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 = self.tload(r, Response) if not response.ok: raise ResponseException(response.error) async def isAway(self, user: User) -> bool: r = await self.client.api_call('users.getPresence', user=user.id) response = self.tload(r, Response) if not response.ok: raise ResponseException(response.error) return self.tload(r, Presence).away() async def join(self, channel: Channel) -> None: r = await self.client.api_call('conversations.join', channel=channel.id) response = self.tload(r, Response) if not response.ok: raise ResponseException(response.error) async def invite(self, channel: Channel, user: 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 = self.tload(r, Response) if not response.ok: raise ResponseException(response.error) async def get_members(self, channel: 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 = self.tload(r, Response) if not response.ok: raise ResponseException(response.error) newusers = self.tload(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 all slack channels if refresh is set, the local cache is cleared This is prone to fail due to being rate limited. """ try: return await self._list_channels('conversations.list', refresh, self._channelscache) except Exception: # Best effort, if it failed due to rate limit, just return what # we have got so far and move on. return self._channelscache async def joined_channels(self, refresh: bool = False) -> list[Channel]: """ Returns the list of joined slack channels if refresh is set, the local cache is cleared """ return await self._list_channels('users.conversations', refresh, self._joinedchannelscache) async def _list_channels(self, method: str, refresh: bool, cacheobj: list[Channel]) -> list[Channel]: if refresh: cacheobj.clear() if cacheobj: return cacheobj cursor = None while True: r = await self.client.api_call( method, cursor=cursor, exclude_archived=True, types='public_channel,private_channel,mpim', limit=1000, # In vain hope that slack would not ignore this ) response = self.tload(r, Response) if response.ok: conv = self.tload(r, Conversations) cacheobj += 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 cacheobj 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.joined_channels(refresh=bool(i)): if c.id == id_: return c # Failed, we try all the channels 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.joined_channels(refresh=bool(i)): if c.name == name: return c # Failed, we try all the channels 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_thread(self, thread_ts: str, original_channel: str) -> MessageThread: """ Creates a fake channel class for a chat thread """ channel = (await self.get_channel(original_channel)).name_normalized # Get head message history = await self.get_history(original_channel, thread_ts, None, 1, True) msg = history.messages.pop() user = (await self.get_user(msg.user)).name if isinstance(msg, HistoryMessage) else 'bot' # Top message is a file if msg.text == '' and msg.files and isinstance(msg.files[0], File): f = msg.files[0] original_txt = f'{f.title} {f.mimetype} {f.url_private}' else: original_txt = msg.text.strip().replace('\n', ' | ') t = Topic(f'{user} in {channel}: {original_txt}') return MessageThread( id=original_channel, name_normalized=f't-{channel}-{thread_ts}', purpose=t, topic=t, thread_ts=thread_ts, ) async def get_im(self, im_id: str) -> IM | None: 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, is_user_deleted=False) 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 = self.tload(r, Response) if response.ok: return [i for i in self.tload(r['channels'], list[IM]) if not i.is_user_deleted] 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 = self.tload(r, Response) if response.ok: for user in self.tload(r['members'], list[User]): self._usercache[user.id] = user self._usermapcache[user.name] = user 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 = self.tload(r, Response) if response.ok: u = self.tload(r['user'], User) self._usercache[id_] = u self._usermapcache[u.name] = u return u else: raise KeyError(response) async def send_file(self, channel_id: str, filename: str, content: bytes, thread_ts: str | None) -> None: """ Send a file to a channel or group or whatever. Otherwise filename is just used to give a name to the file on slack. """ import io f=io.BytesIO(content) f.name = filename r = await self.client.api_call( 'files.upload', channels=channel_id, thread_ts=thread_ts, file=f, ) response = self.tload(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: Channel|MessageThread, msg: str, action: bool, re_send_to_irc: bool) -> None: thread_ts = channel.thread_ts if isinstance(channel, MessageThread) else None return await self._send_message(channel.id, msg, action, thread_ts, re_send_to_irc) async def _send_message(self, channel_id: str, msg: str, action: bool, thread_ts: str | None, re_send_to_irc: bool) -> None: """ Send a message to a channel or group or whatever action must be true for /me messages thread_ts must be set to reply in a thread re_send_to_irc, if true the message will be forwarded to the IRC client as if it was sent via a different client. """ if action: api = 'chat.meMessage' else: api = 'chat.postMessage' try: kwargs = {} if thread_ts: kwargs['thread_ts'] = thread_ts self._wsblock += 1 r = await self.client.api_call( api, channel=channel_id, text=msg, as_user=True, **kwargs, # type: ignore ) response = self.tload(r, Response) if response.ok and response.ts and not re_send_to_irc: self._sent_by_self.add(response.ts) return raise ResponseException(response.error) finally: self._wsblock -= 1 async def send_message_to_user(self, user: User, msg: str, action: bool, re_send_to_irc: 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: # If the conversation is not in cache, reopen it # It is faster than querying the list of conversations # anyway r = await self.client.api_call( "conversations.open", prevent_creation=False, users=user.id, ) response = self.tload(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, None, re_send_to_irc) async def event(self) -> SlackEvent | None: """ This returns the events from the slack websocket """ if self._internalevents: return self._internalevents.pop() try: events = await self.client.rtm_read() except Exception: 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 t in USELESS_EVENTS: continue debug(event) loadable_events = TopicChange|MessageBot|MessageEdit|MessageDelete|GroupJoined|Join|Leave|UserTyping|MpimJoined try: ev: loadable_events | None = self.tload( 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].discard(ev.user) elif isinstance(ev, UserTyping): await self._annoy(ev) continue if ev: return ev subt = event.get('subtype') try: if t == 'message' and (not subt or subt == 'me_message'): msg = self.tload(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, thread_ts=msg.thread_ts, ts=msg.ts) await self._autoreact(msg) if ts in self._sent_by_self: self._sent_by_self.remove(ts) continue if subt == 'me_message': return ActionMessage(*msg) # type: ignore else: return msg elif t == 'message' and subt == 'slackbot_response': return self.tload(event, Message) elif t == 'user_change': # Changes in the user, drop it from cache u = self.tload(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/lsi-getconf0000775000175000017500000000702014634376111015065 0ustar salvosalvo#!/usr/bin/env python3 # localslackirc # Copyright (C) 2024 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 os import sys import sqlite3 import argparse from pathlib import Path HOME = Path(os.environ.get('HOME', '')) MOZILLA_CONF = HOME / '.mozilla' def log(*args): print(*args, file=sys.stderr) def get_mozilla_localstorage_tokens(ls: Path) -> list[str]: ''' Pass the path of a possible local storage file and get slack tokens ''' db = sqlite3.connect(ls) try: s = db.execute('select value from data where key="localConfig_v2";') except Exception: return [] r = [] for i in s: # Some magic crap, it's a readable json polluted with unreadable crap… # No idea if this will work in other cases than on my machine i = i[0] i = i.split(b'"toke', 1)[1].split(b'"', 1)[0] i = i[i.index(b'xox'):] r.append(i.decode('ascii')) return r def get_mozilla_cookies(jar: Path) -> list[str]: ''' Pass the path of a cookie jar and receive a list of slack cookies ''' db = sqlite3.connect(jar) return [i[0] for i in db.execute('select value from moz_cookies WHERE host= ".slack.com" and name="d";')] def mozilla(cfgdir: Path) -> tuple[list[str], list[str]]: ''' returns cookies, tokens ''' log(f'Scanning {cfgdir} as a Mozilla directory') cookiefiles = cfgdir.rglob('cookies.sqlite') other_files = cfgdir.rglob('*.sqlite') cookies = [] tokens = [] for i in cookiefiles: log(f'Scanning possible cookie jar {i}') try: cookies += get_mozilla_cookies(i) except Exception as e: sys.exit(str(e)) for i in other_files: log(f'Scanning possible local storage file {i}') try: tokens += get_mozilla_localstorage_tokens(i) except Exception as e: sys.exit(str(e)) return cookies, tokens def main() -> None: parser = argparse.ArgumentParser( description='Read the browser database to try to find the cookie and token that are necessary to set up localslackirc.' ) parser.add_argument('--mozilla-dir', type=Path, action='store', dest='mozilla_dir', default=MOZILLA_CONF) args = parser.parse_args() cookies = [] tokens = [] c, t = mozilla(args.mozilla_dir) cookies += c tokens += t # TODO chromium if not cookies and not tokens: sys.exit('Fail: Nothing was found') print('# ==============') if tokens: print('# Tokens found:') for i in tokens: print(f'TOKEN={i}') if cookies: print('# Cookies found:') for i in cookies: print(f'COOKIE="d={i};"') if len(tokens) > 1 or len(cookies) > 1: print('# Try deleting all cookies from your browsers and logging into slack again') if __name__ == '__main__': main() localslackirc/slackclient/__init__.py0000664000175000017500000000004014634376111017325 0ustar salvosalvofrom .client import SlackClient localslackirc/slackclient/client.py0000664000175000017500000001332214723036742017055 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, NamedTuple, Optional from typedload import load from websockets.asyncio.client import connect as wsconnect, ClientConnection 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[ClientConnection] = 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): try: asyncio.get_running_loop() loop = True except RuntimeError: loop = False if self._websocket and loop: asyncio.create_task(self._websocket.close()) 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: float = 0.0) -> LoginInfo: """ Connects to the RTM API - https://api.slack.com/rtm :Args: timeout: in seconds """ r = await self.login(timeout=timeout) headers = { 'user-agent': 'localslackirc', 'Authorization': f'Bearer {self._token}', } if self._cookie: headers['cookie'] = self._cookie self._websocket = await wsconnect(r.url, close_timeout=0.2, additional_headers=headers) 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.py0000664000175000017500000000327514634377763020002 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/slackclient/http.py0000664000175000017500000001574714723036742016573 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 Optional, NamedTuple, 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/Makefile0000664000175000017500000000711514634400504014364 0ustar salvosalvoall: @echo Nothing to do .PHONY: lint lint: mypy --config-file mypy.conf *.py slackclient localslackirc lsi-getconf .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 msgparsing.py $${DESTDIR:-/}/usr/share/localslackirc/ install -m644 slack.py $${DESTDIR:-/}/usr/share/localslackirc/ install -m644 irc.py $${DESTDIR:-/}/usr/share/localslackirc/ install -m644 control.py $${DESTDIR:-/}/usr/share/localslackirc/ install -m755 lsi-cli.py $${DESTDIR:-/}/usr/share/localslackirc/ install -m755 lsi-getconf $${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 ln -s ../share/localslackirc/lsi-cli.py $${DESTDIR:-/}/usr/bin/lsi-send ln -s ../share/localslackirc/lsi-cli.py $${DESTDIR:-/}/usr/bin/lsi-write ln -s ../share/localslackirc/lsi-getconf $${DESTDIR:-/}/usr/bin/lsi-getconf # 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 man/lsi-send.1 $${DESTDIR:-/}/usr/share/man/man1/lsi-send.1 install -m644 -D man/lsi-write.1 $${DESTDIR:-/}/usr/share/man/man1/lsi-write.1 install -m644 -D man/lsi-getconf.1 $${DESTDIR:-/}/usr/share/man/man1/lsi-getconf.1 install -m644 -D localslackirc.d/example $${DESTDIR:-/}/etc/localslackirc.d/example install -m644 -D systemd/localslackirc@.service $${DESTDIR:-/}/usr/lib/systemd/system/localslackirc@.service install -m644 -D systemd/localslackirc.service $${DESTDIR:-/}/usr/lib/systemd/system/localslackirc.service .PHONY: dist dist: cd ..; tar -czvvf localslackirc.tar.gz \ localslackirc/localslackirc \ localslackirc/*.py \ localslackirc/lsi-getconf \ localslackirc/slackclient/*.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 lintian --pedantic -E --color auto -i -I deb-pkg/*changes deb-pkg/*deb .PHONY: clean clean: $(RM) -r deb-pkg $(RM) -r tests/__pycache__ $(RM) -r slackclient/__pycache__ $(RM) -r __pycache__ $(RM) -r .mypy_cache localslackirc/CHANGELOG0000664000175000017500000001136715027356570014154 0ustar salvosalvo1.35 * Thanks to jao for reporting and investigating an issue. The check to see if the logs directory was writeable was too aggressive, and failed with default value due to systemd hardening. Now it is less aggressive, the example file suggests storing files in one's home directory, and logging is improved. 1.34 * Verify the settings before a client attempts to connect * Check that status file is writeable * Handle IRC monitored nicknames. Marked as offline if they are away on slack * Handle CAP irc command and stop logging an error * Implement workaround for slack's bug of not escaping "<" when messages are edited 1.33 * Use new API from websockets module 1.32 * Move project to codeberg * Install systemd stuff under usr/ to make Debian happy 1.31 * Store state into /var/lib/localslackirc when started from systemd 1.30 * Do not crash when encountering graves of deleted files 1.29 * Do not crash when encountering deleted files 1.28 * Do not crash on errors with last known timestamp * Stop using match statement, so it can work with pypy 1.27 * New group chats are automatically joined rather than ignored This used to work but slack changed API 1.26 * Add experimental command lsi-getconf to read the slack token from the browser * Install correct manpage for lsi-write * Improve descriptions * Improve --help output * Do not crash when messages cannot be parsed 1.25 * Fix crash when sending a non existing file 1.24 * Add /dropautoreact command * Add /listautoreact command * Add /listannoy command * Add /dropannoy command * Store annoy and autoreact in state, so they are preserved * Allow unlimited timeout for annoy and autoreact 1.23 * Add /autoreact command to automatically put reactions to messages. 1.22 * Fetch only the list of joined channels if the full list is not needed. Thanks to: Jiri Bohac * Ignore chats with deleted users when downloading history * Remove calls to removed API calls 1.21 * Introduce lsi-send to send files from the shell * Introduce lsi-write to send messages from the shell 1.20 * Fix crash when slack sends ids of channels that do not exist * Automatically create the download directory for the preformatted text 1.19 * Send token and cookie to authenticate to websocket as well 1.18 * Once leaving a thread, you won't get autojoined every new message * Leaving a channel but not a thread leaves the threads working * Can now automatically rejoin channels/threads when mentioned directly 1.17 * Improve handling of UNIX signals * More readable names for thread channels * Reduce CPU usage to parse messages 1.16 * Can ignore yelling (@here and such) for entire channels 1.15 * Map slack threads to IRC channels * Rewritten parser for slack messages 1.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/LICENSE0000664000175000017500000010451314634376111013737 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.md0000664000175000017500000001744414634400031014204 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. [![Donate to LtWorf](docs/donate.svg)](https://liberapay.com/ltworf/donate) 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 silence @here notifications for selected users and channels where they are abused. * 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://codeberg.org/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.10 * 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. Use lsi-getconf --------------- After logging in slack with firefox, run `lsi-getconf`. This tool is experimental. If it fails to work you need to do it manually. Obtain a token from the browser ------------------------------- * Open firefox * Open slack * Login * Open developer mode * Go to "network" tab * Click on "WS", that means websocket * Select the connection, right click and copy value > copy with cURL. If there is no connection, refresh the page and it will appear. It will be something like this: ``` curl 'wss://wss-primary.slack.com/?token=xoxc-1111111111-111111111111-1111111111111-11111111111111111&sync_desync=1&start_args=%3Fagent%3Dclient%26org_wide_aware%3Dtrue%26agent_version%111111111111%26eac_cache_ts%3Dtrue' \ -H 'User-Agent: Mozilla/5.0' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.5' \ -H 'Accept-Encoding: gzip, deflate, br' -H 'Sec-WebSocket-Version: 13' \ -H 'Origin: https://app.slack.com' \ -H 'Sec-WebSocket-Extensions: permessage-deflate' \ -H 'Sec-WebSocket-Key: 111111111111111111111111' \ -H 'DNT: 1' \ -H 'Connection: keep-alive, Upgrade' \ -H 'Cookie: b=1111111111111111; d=xoxd-1111111111111111111111111111111; tz=60; OptanonConsent=isGpcEnabled=0&datestamp=Wed+Feb+07+2024+15%3A37%3A16+GMT%2B0100+(Ora+standard+dell%E2%80%99Europa+centrale)&version=202211.1.0&isIABGlobal=false&hosts=&consentId=11111111-1111-1111-1111-111111111111&interactionCount=1&landingPath=NotLandingPage&groups=1%3A1%2C3%3A0%2C2%3A0%2C4%3A0&AwaitingReconsent=false; lc=1111111111; shown_download_ssb_modal=1; d-s=1111111111; x=11111111111111111111111111111111.1111111111' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: websocket' \ -H 'Sec-Fetch-Site: same-site' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'Upgrade: websocket' ``` The `token=` part of the URL (terminated by `&`) and the `Cookie:` header are the parts that are important. The cookie header contains more than one cookie, we want the one starting with `d=`. The value for the cookie must include the initial `d=` and the final `;`. So, for example (the real values will be longer): ``` TOKEN=xoxc-1111111 COOKIE=d=xoxd-1111111; ``` Remember to quote if you pass them in a shell. 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. From the shell you can do `lsi-send -F file '#general'` ## Annoying people You can use `/annoy user` to send typing notifications whenever the specified user sends a typing notification. ## Discussion threads There is some support for discussion threads. They are mapped as irc channels that get automatically joined when a message is received. The channel of origin is specified in the topic. Until a thread has some activity you can't write to it. They are only tested for channels, not private groups or chats. ## Leaving channels Leaving a discussion thread means that you will no longer receive updates within that thread Leaving a regular channel means that discussion threads from that channel will no longer appear After leaving a channel, a personal mention in that channel will automatically join it again. @here will be ignored. ## Reacting to messages Since I don't feel like manually wasting time to do it, a very nice `/autoreact` command is available to automate reacting. ## 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.md0000664000175000017500000000036114634376111014517 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.txt0000664000175000017500000000006414634376111016212 0ustar salvosalvotypedload>=2.16 emoji>=2.0.0 types-emoji websockets localslackirc/docker/Dockerfile0000664000175000017500000000065214634376111016172 0ustar salvosalvoFROM python:3.10-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/0000775000175000017500000000000015026423607013500 5ustar salvosalvolocalslackirc/man/lsi-send.10000664000175000017500000000266614634400031015300 0ustar salvosalvo.TH lsi-send 1 "Jun 18, 2024" "Send files to slack" .SH NAME lsi-send \- Send a file to a slack user or channel. .SH SYNOPSIS lsi-send [OPTIONS] DESTINATION < file .br lsi-send [OPTIONS] -F file DESTINATION .SH DESCRIPTION This command sends files to an instance of localslackirc that is running locally. .br DESTINATION indicates a channel or user to send the file to. .br When using the provided .service file and starting localslackirc with systemd, this command should be able to autodetect the location of the socket. .br In case the same user is running multiple instances, then it is possible that the path to the unix socket must be provides as a parameter. .br NOTE: the files are entirely loaded in RAM before sending. .SS Options: .TP .B -h, --help Show the help message and exit. .TP .B -f FILENAME, --filename FILENAME The name to give to the filename. .br It will appear on slack. .TP .B --control-socket CONTROL_SOCKET If the path to the socket cannot be auto-detected, this option must be used to indicate the path to connect to the control socket. .TP .B -F SOURCE, --file SOURCE When used, instead of reading from stdin, lsi-send will read from the specified file. .br The --filename option will be ignored in this case, and the real name of the file will be used. .SH "SEE ALSO" .BR localslackirc (1), lsi-write (1) .SH WEB .BR https://codeberg.org/ltworf/localslackirc .SH AUTHOR .nf Salvo "LtWorf" Tomaselli localslackirc/man/lsi-write.10000664000175000017500000000151615026423607015504 0ustar salvosalvo.TH lsi-write 1 "Apr 14, 2025" "Send files to slack" .SH NAME lsi-write \- Send a message to a slack user or channel. .SH SYNOPSIS lsi-write [OPTIONS] user .SH DESCRIPTION Inspired by the classical write, this works more or less in the same way. .br It uses the control socket of a localslackirc instance to send messages to a user or channel. .SS Options: .TP .B -h, --help Show the help message and exit. .TP .B --control-socket CONTROL_SOCKET If the path to the socket cannot be auto-detected, this option must be used to indicate the path to connect to the control socket. .br If there is only one instance running, the control socket will be autodetected and used. .SH "SEE ALSO" .BR localslackirc (1), lsi-send (1) .SH WEB .BR https://codeberg.org/ltworf/localslackirc .SH AUTHOR .nf Salvo "LtWorf" Tomaselli localslackirc/man/lsi-getconf.10000664000175000017500000000166314634400031015770 0ustar salvosalvo.TH lsi-getconf 1 "Jun 18, 2024" "Send files to slack" .SH NAME lsi-getconf \- Read the browser database to try to find the cookie and token that are necessary to set up localslackirc. .SH SYNOPSIS lsi-getconf [OPTIONS] .SH DESCRIPTION This command reads the browser database to try to find token and cookie that are necessary to localslackirc. .br For now it only supports Firefox. .br This is experimental. It might not work on your machine. In which case you should fall back to extracting the data directly from the browser. .SS Options: .TP .B -h, --help Show the help message and exit. .TP .B --mozilla-dir DIRECTORY Alternative search path for the mozilla directory. It defaults to ~/.mozilla. .SH "Known errors" .TP .B database is locked Close the browser to solve this issue. .SH "SEE ALSO" .BR localslackirc (1) .SH WEB .BR https://codeberg.org/ltworf/localslackirc .SH AUTHOR .nf Salvo "LtWorf" Tomaselli localslackirc/man/localslackirc.10000664000175000017500000001724614671045735016411 0ustar salvosalvo.TH localslackirc 1 "Sep 13, 2024" "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 and channels 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. .br The channels must begin with #. .br The threads created from a silenced channel will also be silenced. .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. .br If the user gets personally mentioned in one of the ignored channels, it will be joined anyway. General mentions will be ignored. .TP .B --no-rejoin-on-mention Normally localslackirc will automatically join channel and threads if someone mentions the user. .br When this is set the mentions will be ignored and no channels or threads will be joined upon mention. .TP .B --control-socket CONTROL_SOCKET When used, localslackirc will create a unix socket in the specified path, that can be used by the various lsi-* commands to interact with localslackirc. .br Before an IRC client connects to localslackirc, the process is in a dormant unconnected state and is not connected to slack. For this reason the control socket exists only when an IRC client is connected. .SH TOKEN The easiest way to obtain the COOKIE and the TOKEN, is to login in slack using Firefox, closing Firefox and running lsi-getconf. .br It will parse your saved cookies and try to find the values. .br If that should fail, the README contains the procedure to manually extract them from the browser. .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 .br Set to "true" to enable. .TP .B NOUSERLIST Alternative to --nouserlist .br Set to "true" to enable. .TP .B DEBUG Alternative to --debug .TP .B LOG_SUFFIX Alternative to --log-suffix .TP .B IGNORED_CHANNELS Alternative to --ignored-channels .TP .B NO_REJOIN_ON_MENTION Alternative to --no-rejoin-on-mention .br Set to "true" to enable. .TP .B SILENCED_YELLERS Alternative to --silenced-yellers .TP .B CONTROL_SOCKET Alternative to --control-socket .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 .TP .B /autoreact user probability [reaction] [duration] To automate reacting to messages, this nice feature is available. .br user is the username of the user that we want to react to. .br probability is a number between 0 and 1, to decide how much to react. .br reaction is the reaction to use. The default is "thumbsup". .br duration indicates when to stop doing it, in minutes. Defaults to 10. Setting it to -1 makes it never expire. .SS .TP .B /dropautoreact user Deletes all the automatic reacts for a given user .SS .TP .B /dropannoy user Stops annoying the given user .SS .TP .B /listannoy Lists the users that are currently being annoyed .SS .TP .B /listautoreact Lists the automatic reactions .SS .SH "SEE ALSO" .BR lsi-getconf(1), lsi-send (1), lsi-write (1) .SH WEB .BR https://codeberg.org/ltworf/localslackirc .SH AUTHOR .nf Salvo "LtWorf" Tomaselli localslackirc/tests/__init__.py0000664000175000017500000000000014634376111016167 0ustar salvosalvolocalslackirc/tests/__main__.py0000664000175000017500000000170614634376111016166 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_diff import * from .test_executable import * from .test_message_bot import * from .test_irc import * from .test_msgparsing import * if __name__ == '__main__': unittest.main() localslackirc/tests/test_diff.py0000664000175000017500000000525614634376111016421 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_with_ltgt(self): assert seddiff('Optional', 'Optional') == 's/Optional/Optional/' assert seddiff('`Optional`', '`Optional`') == 's/`Optional`/`Optional`/' 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.py0000664000175000017500000000412615027356570017631 0ustar salvosalvo# localslackirc # Copyright (C) 2020-2025 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 os import unittest import subprocess import tempfile from pathlib import Path if os.path.exists("./localslackirc"): # inside source directory localslackirc = "./localslackirc" else: # test installed program localslackirc = "localslackirc" class TestStart(unittest.TestCase): def test_print_help(self): subprocess.check_call([localslackirc, '--help'], stdout=subprocess.DEVNULL) def test_test_status_file(self): with self.assertRaises(subprocess.CalledProcessError): subprocess.check_call([localslackirc, '--status-file', '/a', '--port', '12345'], env={'TOKEN':'123'}) t = Path(tempfile.mktemp()) t.write_bytes(b'') t.chmod(0o000) with self.assertRaises(subprocess.CalledProcessError): subprocess.check_call([localslackirc, '--status-file', t, '--port', '12345'], env={'TOKEN':'123'}) t.unlink() def test_downloads_dir(self): with self.assertRaises(subprocess.CalledProcessError): subprocess.check_call([localslackirc, '--downloads-directory', '/', '--port', '12345'], env={'FORMATTED_MAX_LINES':'3', 'TOKEN':'123'}) with self.assertRaises(subprocess.CalledProcessError): subprocess.check_call([localslackirc, '--downloads-directory', '/a', '--port', '12345'], env={'FORMATTED_MAX_LINES':'3', 'TOKEN':'123'}) localslackirc/tests/test_irc.py0000664000175000017500000001023714634376111016261 0ustar salvosalvo# localslackirc # Copyright (C) 2021 Antonio Terceiro # Copyright (C) 2022 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 . 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) 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',b'#asd') assert msg == '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', b'#asd') assert msg == 'yelling: watch this!' # No effect on regular messages msg = await self.client.parse_message("hello world", b'rose.adams', b'#asd') assert msg == 'hello world' class TestParseMessage(TestIRC): async def test_simple_message(self): msg = await self.client.parse_message("hello world", b'ciccio', b'#asd') self.assertEqual(msg, "hello world") async def test_url(self): msg = await self.client.parse_message("See ", b'ciccio', b'#asd') self.assertEqual(msg, "See the documentation¹\n ¹ https://example.com/docs/") async def test_url_aggressive_shortening(self): msg = await self.client.parse_message("See ", b'ciccio', b'#asd') self.assertEqual(msg, "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', b'#asd') self.assertEqual(msg, "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', b'#asd') self.assertEqual(msg, output) async def test_url_with_no_label_just_goes_inline(self): msg = await self.client.parse_message("Please look at ", b'ciccio', b'#asd') self.assertEqual(msg, "Please look at https://example.com/") async def test_replace_label_for_urls_with_no_different_text(self): msg = await self.client.parse_message("", b'ciccio', b'#asd') self.assertEqual(msg, "LINK¹\n ¹ https://example.com/") localslackirc/tests/test_message_bot.py0000664000175000017500000000505214634376111017773 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_msgparsing.py0000664000175000017500000000602615026423607017656 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 msgparsing import preblocks, split_tokens, SpecialItem, Itemkind, convertpre, tokenize, PreBlock class TestMsgParsing(unittest.TestCase): def test_preblocks(self): assert list(preblocks('')) == [('', False)] assert list(preblocks('asd')) == [('asd', False)] assert list(preblocks('a ```a``` a')) == [('a ', False), ('a', True), (' a', False)] assert list(preblocks('```a``` a')) == [('', False), ('a', True), (' a', False)] assert list(preblocks('```a')) == [('', False), ('a', True)] def test_split_tokens(self): assert list(split_tokens('a b c d')) == ['a b c d'] assert list(split_tokens('a d')) == ['a ', SpecialItem(''), ' ', SpecialItem(''), ' d'] def test_special_item(self): c = SpecialItem('<@ciccio>') assert c.kind == Itemkind.MENTION assert c.human is None assert c.val == 'ciccio' c = SpecialItem('') assert c.kind == Itemkind.OTHER assert c.human == 'link' assert c.val == 'http://ciccio' c = SpecialItem('<#ciccio>') assert c.kind == Itemkind.CHANNEL assert c.human is None assert c.val == 'ciccio' c = SpecialItem('') assert c.kind == Itemkind.YELL assert c.human is None assert c.val == 'here' def test_convertpre(self): assert convertpre('asd') == 'asd' assert convertpre('asd >') == 'asd http://ciccio >' assert convertpre(':coffin:') == ':coffin:' def test_tokenize(self): assert list(tokenize('a')) == ['a'] assert list(tokenize('a ```ciao```')) == ['a ', PreBlock('ciao')] assert list(tokenize(':coffin:')) == ['⚰️'] assert list(tokenize('>')) == ['>'] assert list(tokenize('a d ``````')) == ['a ', SpecialItem(''), ' ', SpecialItem(''), ' d ', PreBlock('http://ciccio')] def test_workaround_escaping_bug(self): ''' In message changed events the fuckers of slack do not escape '<' sometimes. This is a real message: MessageEdit( type='message', subtype='message_changed', previous=NoChanMessage(text='>'), current=NoChanMessage(text='<')) ''' assert list(tokenize('<')) == ['<'] localslackirc/localslackirc.d/0000775000175000017500000000000015027356570015762 5ustar salvosalvolocalslackirc/localslackirc.d/example0000664000175000017500000000452415027356570017345 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 # You can try using lsi-getconf to automatically obtain TOKEN and COOKIE from firefox # 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 # Stops rejoining channel on a mention (@here is not considered) #NO_REJOIN_ON_MENTION=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 # # A personal mention on one of these will trigger a channel join, while # general mentions are ignored. #IGNORED_CHANNELS=#general,#chat # Where to create files for automatic downloads. # Make sure it is writable and has space # # NOTE: If you want to use a directory that is not under /home # Using the provided .service file only /home is mounted read-write # to use a different path you must add a ReadWritePaths directive in an # override of the .service file. # # To add an override run systemctl edit localslackirc@filename.service #DOWNLOADS_DIRECTORY=/home/username/localslackirc-logs # 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 and channels not allowed to use general mentions #SILENCED_YELLERS="rose.adams,alfio.cuttigghiu,#sales" # Debugging (disabled by default) # DEBUG=1 localslackirc/systemd/0000775000175000017500000000000015027356570014422 5ustar salvosalvolocalslackirc/systemd/localslackirc@.service0000664000175000017500000000313315027356570020712 0ustar salvosalvo# localslackirc # Copyright (C) 2020-2025 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 ${STATE_DIRECTORY}/localslackirc-status-%i --log-suffix %i --control-socket ${RUNTIME_DIRECTORY}/localslackirc-%i.sock # Using the same mode as /tmp so that after changing uid a control socket can still be created RuntimeDirectory=localslackirc RuntimeDirectoryMode=1777 StateDirectory=localslackirc StateDirectoryMode=1777 # Log StandardOutput=journal StandardError=journal SyslogIdentifier=localslackirc-%i # Config EnvironmentFile=/etc/localslackirc.d/%i # Security ProtectSystem=strict PrivateDevices=true LockPersonality=true localslackirc/systemd/localslackirc.service0000664000175000017500000000215314634376111020607 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.conf0000664000175000017500000000022514634376111014572 0ustar salvosalvo[mypy] python_version=3.10 warn_unused_ignores=False warn_redundant_casts=True strict_optional=True scripts_are_modules=True check_untyped_defs=True