def run_notification_service(webclient): while True: for post_type in notification_data: for subreddit in notification_data[post_type]['subreddits']: sub_name = subreddit['name'] for channel in subreddit['channels']: latest_post = apis.reddit_info.get_post_from_subreddit( sub_name, post_type) if not latest_post[0] == subreddit['last_post']['content']: sub_name_response = f'*{sub_name}*' post_type_response = f'*{post_type}*' emote = ':warning:' if post_type == 'hot': emote = ':fire:' response = f'{emote}[{post_type_response}][{sub_name_response}]{emote}' \ f'New post --> {latest_post[0]} \n' \ f'Link: {latest_post[1]}' post(channel, response) subreddit['last_post']['content'] = latest_post[0] subreddit['last_post']['url'] = latest_post[1] get_logger().info( f'Notification data changed. {notification_data}') else: get_logger().info( f'Post already logged on channel {channel}. Content: {latest_post[0]}' ) time.sleep(REDDIT_POST_CHECK_INTERVAL_SECONDS)
def handle_currency(message, channel_id): split = message.split() from_cur = split[2] to_cur = split[3] quantity = split[4] try: result = exchange.exchange(from_cur, to_cur, quantity) message = f'{quantity} {from_cur} = {result} {to_cur}' post(channel_id, message) except ValueError: message = f'Cannot calculate exchange rate. Pattern: ' \ '"[@bot_name] currency [CURRENCY-FROM] [CURRENCY-TO] [QUANTITY]" \n' \ f'Supported currencies: {supported_currencies} \n' \ f'Quantity format examples: 0.10, 1.1, 100.22, 420.69' post(channel_id, message)
def handle_message(data, **kwargs): if 'bot_id' not in data: channel_id = data['channel'] get_logger().info( f'Incoming Message. Channel: {channel_id}. Content: {data}') if bot_user_id in data['text']: # thread_ts = data['ts'] user = data['user'] message = data['text'] if is_reddit_request(message): handle_reddit(message, channel_id) return if is_currency_request(message): handle_currency(message, channel_id) return response = f'Hi <@{user}> {kekw}' post(channel_id, response)
def watch_subreddit(subreddit, post_type, channel_id): sub_exists = False for sub in notification_data[post_type]['subreddits']: if sub['name'] == subreddit: sub_exists = True if channel_id not in sub['channels']: sub['channels'].append(channel_id) if not sub_exists: notification_data[post_type]['subreddits'].append({ 'name': subreddit, 'last_post': { 'content': '', 'url': '' }, 'channels': [channel_id] }) post(channel_id, f'Successfully subscribed to "{subreddit}" subreddit')
def unwatch_subreddit(subreddit, post_type, channel_id): for sub in notification_data[post_type]['subreddits']: if sub['name'] == subreddit and channel_id in sub['channels']: sub['channels'].remove(channel_id) post(channel_id, f'Successfully unsubscribed "{subreddit}" subreddit')