def check_filters(notification): session = Session() filters = session.query(Filter).all() for filter in filters: if re.search(filter.ban_title, notification.title): return False return True
def count_legacy_reactions(response, database, file_path): reactions_legacy = dict() session = Session() with open(file_path, "rb") as fp: reactions_legacy.update(pickle.load(fp)) # timestamp of the last reaction recorded in the legacy file last_ts = max([ float(reactions_legacy[slack_user['id']]) if slack_user['id'] in reactions_legacy else 0 for slack_user in response['members'] ]) for key in reactions_legacy: if len(key) == 3: sender, receiver, reaction = key # legacy file reaction count - overlap with reactions already stored in database num = reactions_legacy[key] - len( session.query(Reaction).filter( and_(Reaction.sender == sender, Reaction.receiver == receiver, Reaction.name == reaction, Reaction.timestamp < last_ts)).all()) # this allows script to run N times without putting duplicates into database num -= len( session.query(Reaction).filter( and_(Reaction.sender == sender, Reaction.receiver == receiver, Reaction.name == reaction, Reaction.channel == None, Reaction.timestamp == None)).all()) for i in range(num): database.insert( Reaction(None, None, reaction, sender, receiver))
def check_pins(client, logger): session = Session() pins = session.query(Pin).filter(Pin.done == False).all() for pin in pins: if datetime.now() >= pin.creation_date + pin.timer: response = client.pins_remove(channel=pin.channel, timestamp='%.6f' % pin.timestamp) pin.done = True session.commit() logger.info_log('Unpinned message with timestamp ' + str(pin.timestamp) + ' in channel ' + pin.channel)
def count_reactions(client): # legacy_reactions = get_legacy_reactions() database = DataBase() for user in Session().query(SlackUser).all(): reactions_response = client.reactions_list(user=user.id) items = reactions_response.data['items'] for item in items: channel = item['channel'] message = item['message'] ts = message['ts'] author = message['user'] reactions = message['reactions'] # if user.id in legacy_reactions.keys() and ts == legacy_reactions[user.id]: # break for reaction in reactions: if user.id in reaction['users']: reaction_code = reaction['name'].split(':')[0] if database.select(Reaction, channel=channel, timestamp=ts, sender=user.id, receiver=author, name=reaction_code) is None: database.insert( Reaction(channel, ts, reaction_code, user.id, author))
def unarchive_channel(): session = Session() channel_tag = '#' + request.args.get('tag') channel = session.query(Channel).filter(Channel.tag == channel_tag).first() try: client.conversations_join(channel=channel.id) client.conversations_unarchive(channel=channel.id) except Exception as e: print(e) channel.archived = False session.add(channel) session.commit() session.flush() return redirect(url_for('app_course.course_handler'))
def generate_reactions_message(target_reaction): session = Session() reactions = [] for user in session.query(SlackUser).all(): sent_count = len( session.query(Reaction).filter(Reaction.sender == user.id).filter( Reaction.name == target_reaction).all()) received_count = len( session.query(Reaction).filter( Reaction.receiver == user.id).filter( Reaction.name == target_reaction).all()) reactions.append((user.id, received_count, sent_count)) results = sorted(reactions, key=lambda x: x[1]) results.reverse() result_string = 'Here is top chart for :' + target_reaction + ':\n\n' for i in range(len(results)): item = results[i] result_string += str(i + 1) + '. <@' + item[0] + '> with ' + str( item[1]) + ' total reactions received (sent ' + str( item[2]) + ')\n' return result_string
def add_channel_tag(): session = Session() channel_tag = request.form.get('tag') topic = request.form.get('topic') users = request.form.getlist('user_select') response = client.conversations_create(name=channel_tag, is_private=False) channel = response['channel'] channel_model = Channel(channel['id'], '#' + channel['name'], channel['creator'], datetime.fromtimestamp(channel['created'])) session.add(channel_model) client.conversations_setTopic(channel=channel['id'], topic=topic) client.conversations_invite(channel=channel['id'], users=users) session.commit() session.flush() return redirect(url_for('app_course.course_handler'))
def check_reminders(client, logger): session = Session() reminders = session.query(Reminder).filter( Reminder.end_date - Reminder.timer <= datetime.now()).filter( Reminder.posted == False).all() for reminder in reminders: notification = session.query(Notification).filter( Notification.id == reminder.notification).first() course = session.query(Course).filter( notification.site == Course.id).first() time_left = reminder.end_date - datetime.now() text = '*' + str(time_left) + ( 'h* left until this event\n>' + notification.title + '\n>' + reminder.text + '\nSee more at ' + notification.link) response = client.chat_postMessage(channel=course.channel_tag, text=text) reminder.posted = True logger.info_log('Posted reminder with id ' + str(reminder.id) + ' in channel ' + course.channel_tag + '(' + str(course.channel.id) + ')') session.commit()
def course_handler(): session = Session() default_course_url = 'www.fer.unizg.hr/predmet/' form = WatchlistForm() courses = session.query(Course).all() archived_channel_tags = [ channel.tag for channel in session.query(Channel).filter( Channel.archived == True).all() ] if form.validate_on_submit(): watch = False if request.form.get('watch_input') == 'on': watch = True if form.id.data == -1: new_course = Course(form.name.data, request.form.get('tag_select'), default_course_url + form.url.data, watch) session.add(new_course) session.commit() session.flush() else: course = session.query(Course).filter( Course.id == form.id.data).first() course.name = form.name.data course.url = default_course_url + form.url.data course.channel_tag = request.form.get('tag_select') course.watch = watch session.commit() session.flush() courses = session.query(Course).all() form.name.data = '' form.url.data = '' form.watch.data = True watched = [ course for course in courses if course.watch and course.channel_tag not in archived_channel_tags ] unwatched = [ course for course in courses if not course.watch and course.channel_tag not in archived_channel_tags ] archived = [ course for course in courses if course.channel_tag in archived_channel_tags ] users = session.query(SlackUser).filter(SlackUser.name != 'infobot').all() # channels = session.query(Channel).all() channels = session.query(Channel).outerjoin( Course, Channel.tag == Course.channel_tag).filter( Course.channel_tag == None).all() channel_tags = [channel.tag for channel in channels] if not channel_tags.__contains__('#general'): channel_tags.append('#general') return render_template('course.html', watched_courses=watched, unwatched_courses=unwatched, tags=channel_tags, form=form, users=users, archived_courses=archived), 200
def archive_channel(): session = Session() channel_tag = '#' + request.args.get('tag') course = session.query(Course).filter( Course.channel_tag == channel_tag).first() course.watch = False session.add(course) pins = session.query(Pin).join(Channel, Pin.channel == Channel.id).filter( Pin.done == False).filter(Channel.tag == channel_tag).all() for pin in pins: client.pins_remove(channel=pin.channel, timestamp='%.6f' % pin.timestamp) pin.done = True session.add(pin) reminders = session.query(Reminder).join(Notification, Reminder.notification == Notification.id)\ .join(Course, Course.id == Notification.site).filter(Course.channel_tag == channel_tag)\ .filter(Reminder.posted == False).all() for reminder in reminders: reminder.posted = True session.add(reminder) channel = session.query(Channel).filter(Channel.tag == channel_tag).first() client.conversations_archive(channel=channel.id) channel.archived = True session.add(channel) session.commit() session.flush() return redirect(url_for('app_course.course_handler'))
def __init__(self, client: WebClient, database: DataBase, logger: Logger): self.client, self.database, self.logger = client, database, logger self.session = Session()
class ReminderManager: """ A class that is responsible for handling all actions regarding Slack Workspace reminders Attributes ---------- client : WebClient a Slack WebClient with which reminders are pulled from Slack Workspace database : DataBase a objects that is responsible for communicating with database logger : Logger a object that is saving scanner logs to a predefined file Methods --------- get_reminders() returns reminders from database kwargs: course, author, from and to dates default is return all get_filter_options() returns all authors and courses save() saves a changed reminder returns result of saving delete() removes reminder from database params: id of the reminder return result of removal """ def __init__(self, client: WebClient, database: DataBase, logger: Logger): self.client, self.database, self.logger = client, database, logger self.session = Session() def get_reminders(self, **kwargs): self.logger.info_log('Pulling reminders') if not kwargs: return self.database.select_many(Reminder) else: result = self.session.query(Reminder).join(Notification).join(Author).join(Course) for filters in kwargs.keys(): if filters == 'name': result = result.filter(getattr(Course, 'name') == kwargs['name']) elif filters == 'author': result = result.filter(getattr(Author, 'first_name') == kwargs['author'].split(' ')[0]) result = result.filter(getattr(Author, 'last_name') == kwargs['author'].split(' ')[1]) elif filters == 'from': result = result.filter(getattr(Reminder, 'end_date') >= kwargs['from']) elif filters == 'to': result = result.filter(getattr(Reminder, 'end_date') < kwargs['to']) elif filters == 'posted': result = result.filter(getattr(Reminder, 'posted') == kwargs['posted']) return result.all() def get_filter_options(self): self.logger.info_log('Pulling all courses and authors') return self.database.select_many(Course), self.database.select_many(Author) def save(self, **kwargs): self.logger.info_log('Updating reminder with id: ' + kwargs['id']) reminder = self.session.query(Reminder).get(kwargs['id']) # parse string data year, month, day = kwargs['end_date'].split(' ')[0].split('-') hour, minute, second = kwargs['end_date'].split(' ')[1].split(':') try: reminder.end_date = datetime(int(year), int(month), int(day), int(hour), int(minute), int(second)) reminder.timer = timedelta(seconds=kwargs['timer']) reminder.text = kwargs['text'] reminder.posted = True if kwargs['posted'] is True else False self.session.commit() except SQLAlchemyError as e: self.logger.error_log(e) return False return True def delete(self, reminder_id): self.logger.info_log("Removing reminder with id: " + reminder_id) try: self.session.query(Reminder).filter_by(id=reminder_id).delete() self.session.commit() except SQLAlchemyError as e: self.logger.error_log(e) return False return True