def renew_line_access_token(self): try: headers = {'Content-Type': 'application/x-www-form-urlencoded'} payload = { 'grant_type': 'client_credentials', 'client_id': configuration.LINE_CLIENT_ID, 'client_secret': configuration.LINE_CLIENT_SECRET } response = requests.post(configuration.LINE_ACCESS_TOKEN_URL, headers=headers, data=payload) result_code = response.status_code if result_code == 200: slack = SlackHelper() decoded_response = response.text.encode("utf-8") json_response = json.loads(decoded_response, encoding='utf8') access_token = json_response['access_token'] notification_msg = 'Old token is invalid and new token is: {0}'.format( access_token) self.update_line_access_token(access_token) info(notification_msg) slack.send_msg(notification_msg) except Exception, e: error(e)
CREDENTIALS_FILE = get_conf_or_env('CREDENTIALS_FILE', config_data, 'credentials.json') WORKBOOK = get_conf_or_env('WORKBOOK', config_data) WORKSHEET_META_TAB = get_conf_or_env('WORKSHEET_META_TAB', config_data) SLACK_TOKEN = get_conf_or_env('SLACK_TOKEN', config_data) SLACK_USERNAME = get_conf_or_env('SLACK_USERNAME', config_data) SLACK_ICON_URL = get_conf_or_env('SLACK_ICON_URL', config_data) WORKSHEET_PEOPLE_TAB = get_conf_or_env('WORKSHEET_PEOPLE_TAB', config_data) required_variables = 'CREDENTIALS_FILE WORKBOOK WORKSHEET_META_TAB SLACK_TOKEN SLACK_USERNAME SLACK_ICON_URL'.split(' ') for variable in required_variables: if eval(variable) is None: logger.error('Missing ' + variable) exit(1) sh = SlackHelper(SLACK_TOKEN) gh = GSheetHelper(CREDENTIALS_FILE) people_phone_numbers = get_people_phone_numbers(WORKBOOK, WORKSHEET_PEOPLE_TAB) meta_rows = get_meta_rows(WORKBOOK, WORKSHEET_META_TAB) print(meta_rows) for row in meta_rows: tab, message, date_col, user_cols, message_col, calendar_type, slack_channels, active, ack, include_phone = \ [row[x] for x in ('Tab', 'Message', 'Date Column', 'User Columns', 'Message Col', 'Calendar Type', 'Slack Channels', 'Active', 'Acknowledge', 'Include Phone')] active = active == '1' ack = ack == '1' include_phone = include_phone == '1'
#!/usr/bin/python import sys import os import Adafruit_DHT from slack_helper import SlackHelper import logging import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) led_pin = 18 dht_pin = 4 dht_type = 11 slacker = SlackHelper(os.environ['SLACK_TOKEN']) humidity_treshold = 80 temperature_threshold = 22 slack_channel = "#team" GPIO.setup(led_pin, GPIO.OUT) current_readings = { 'humidity': 0, 'temperature': 0, } while True: humidity, temperature = Adafruit_DHT.read_retry(dht_type, dht_pin) last_h = current_readings['humidity'] last_t = current_readings['temperature'] is_alerted = False if last_h != humidity and humidity >= humidity_treshold: slacker.send(slack_channel, f'Humidity has reached a high level: {humidity}')
#! /usr/bin/env python # Comes from: https://github.com/dangoldin/automating-management. Some changes made. import config from slack_helper import SlackHelper import sys from datetime import datetime if __name__ == '__main__': if len(sys.argv) != 4: print('Please specify channel and message') exit() channel_name = sys.argv[1] post_at = sys.argv[2] message = sys.argv[3] sh = SlackHelper(config.BOT_USER_TOKEN, config.OAUTH_USER_TOKEN) channel_members = sh.get_channel_members('#' + channel_name) # Below is the code for sending messages to everyone for member_id in channel_members: username = sh.get_name_by_id(member_id) print('Sending to {0}'.format(username)) print( sh.schedule_message( msg=message, channel=member_id, post_time=sh.convert_date_to_unix(post_at), ))
"WORKBOOK WORKSHEET_META_TAB SLACK_TOKEN SLACK_USERNAME SLACK_ICON_URL" .split(" ")) for variable in required_variables: if eval(variable) is None: logger.error("Missing ", variable) sys.exit(1) if CREDENTIALS is None and CREDENTIALS_FILE is None: logger.error("Either CREDENTIALS or CREDENTIALS_FILE is required") sys.exit(1) if CREDENTIALS is not None: CREDENTIALS = json.loads(CREDENTIALS) sh = SlackHelper(SLACK_TOKEN) gh = GSheetHelper(credentials=CREDENTIALS, credentials_file=CREDENTIALS_FILE) people_phone_numbers = get_people_phone_numbers(WORKBOOK, WORKSHEET_PEOPLE_TAB) meta_rows = get_meta_rows(WORKBOOK, WORKSHEET_META_TAB) print(meta_rows) for row in meta_rows: ( tab, message, date_col,
#! /usr/bin/env python import config from slack_helper import SlackHelper import sys from datetime import datetime if __name__ == "__main__": if len(sys.argv) != 3: print "Please specify channel and message" exit() channel_name = sys.argv[1].replace("#", "") message = sys.argv[2] sh = SlackHelper(config.SLACK_TOKEN) channel_members = sh.get_channel_members("#" + channel_name) for member_id in channel_members: username = sh.get_name_by_id(member_id) print "Sending to {0}".format(username) print sh.send_message( msg=message, username=None, as_user=True, channel=member_id, icon_url=None, )
from util import get_conf_or_env, read_config_file FORMAT = "%(asctime)-15s %(message)s" logging.basicConfig(format=FORMAT, level=logging.INFO) logger = logging.getLogger("quiz") if __name__ == "__main__": config_data = read_config_file("config.env") CREDENTIALS_FILE = get_conf_or_env( "CREDENTIALS_FILE", config_data, "credentials.json" ) SLACK_TOKEN = get_conf_or_env("SLACK_TOKEN", config_data) sh = SlackHelper(SLACK_TOKEN) gh = GSheetHelper(CREDENTIALS_FILE) rows = gh.get_rows("Quiz questions", "Questions") row = random.choice(rows) answer_choices = [row[x] for x in ("Answer", "Choice A", "Choice B", "Choice C")] random.shuffle(answer_choices) msg = row["Question"] + "\n" + "\n".join(answer_choices) sh.send_message( msg, "TEST TEST", "#tmp-slack-api", "http://dan.triplelift.net/q.png" ) msg = (
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from datetime import datetime from slack_helper import SlackHelper logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', filename='/var/log/s3_sync.log') slack = SlackHelper() def get_year_str(): return datetime.today().strftime("%Y") def get_month_str(): return datetime.today().strftime("%m") # return the date with YYYYMMDD format def get_today_str(): return datetime.today().strftime("%Y%m%d") def generate_file_path(path): return path + '/' + get_year_str() + '/' + get_month_str() # this method support to generate file name pattern: {prefix}_{accountId}_{yyyyMMdd}_{H}_{num}.{extension}
from sheet_helper import GSheetHelper from util import get_conf_or_env, read_config_file FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(format=FORMAT, level=logging.INFO) logger = logging.getLogger('quiz') if __name__ == '__main__': config_data = read_config_file('config.env') CREDENTIALS_FILE = get_conf_or_env('CREDENTIALS_FILE', config_data, 'credentials.json') SLACK_TOKEN = get_conf_or_env('SLACK_TOKEN', config_data) sh = SlackHelper(SLACK_TOKEN) gh = GSheetHelper(CREDENTIALS_FILE) rows = gh.get_rows('Quiz questions', 'Questions') row = random.choice(rows) answer_choices = [ row[x] for x in ('Answer', 'Choice A', 'Choice B', 'Choice C') ] random.shuffle(answer_choices) msg = row['Question'] + '\n' + '\n'.join(answer_choices) sh.send_message(msg, 'TEST TEST', '#tmp-slack-api', 'http://dan.triplelift.net/q.png')
from file_io import FileReader, FileWriter from slack_helper import SlackHelper LAST_WHEN_FILENAME = 'last_when' if __name__ == '__main__': hook_urls = FileReader('hook_url.conf', default_value=None).read_lines() last_when = FileReader(LAST_WHEN_FILENAME, default_value=None).read() crawler = COVIDCrawler() when = crawler.when all_counts = crawler.counts counts_available = list(filter(lambda count: count.overall > 0, all_counts)) counts_messages = list( map(lambda count: count.to_message(), counts_available)) messages = '\n'.join(counts_messages) message = f'오늘의 대한민국 COVID-19 [{when}]\n\n' \ f'{messages}' # print(message) if last_when == when: exit(0) FileWriter(LAST_WHEN_FILENAME, when).write() for hook_url in hook_urls: slack = SlackHelper(hook_url=hook_url) slack.report_to_slack(message)
from slack_helper import SlackHelper from flask import Flask from flask import request from flask import jsonify from flask import abort from models import UserScore app = Flask(__name__) questions_answers = {} user_scores = defaultdict(UserScore) gs = GSheetHelper(os.environ['CREDENTIALS_FILE']) sh = SlackHelper(os.environ['SLACK_TOKEN']) def get_questions(): try: return gs.get_rows('Quiz questions', 'Questions') except: app.logger.info( 'Failed to get questions. Trying to get new credentials') gs = GSheetHelper(os.environ['CREDENTIALS_FILE']) return gs.get_rows('Quiz questions', 'Questions') def get_message_info(request): return { 'user_id': request.form.get('user_id'),
#! /usr/bin/env python import config from slack_helper import SlackHelper import sys from datetime import datetime if __name__ == '__main__': if len(sys.argv) != 3: print 'Please specify channel and message' exit() channel_name = sys.argv[1].replace('#', '') message = sys.argv[2] sh = SlackHelper('xoxb-394146951447-432142156005-4cvMCcDtyTzQ7cApVKiLtdlS') channel_members = sh.get_channel_members('#' + channel_name) for member_id in channel_members: username = sh.get_name_by_id(member_id) print 'Sending to {0}'.format(username) print sh.send_message( msg=message, username=None, as_user=True, channel=member_id, icon_url=None, )