def __init__(self): self.stdscr = None # instantiate a Slack client self.slack_client = Slack() self.slack_client.setup() self.showing = 0 self.selection = 0
def __init__(self, laddr, raddr, uilogger): SMTPServer.__init__(self, laddr, raddr) self.uilogger = uilogger self.ib_clients = dict() # a dict to reference different client by account id self.em_clients = list() # list of emails only clients self.ems = None # email sender object self.slack = None # slack client # Retrieve application config from app.yml to initialize emailsender and slack with open('conf/app.yml', 'r') as cf: conf = yaml.load(cf, Loader=yaml.FullLoader) if "email_sender" in conf: self.ems = EmailSender( conf["email_sender"]["smtp_server"], conf["email_sender"]["smtp_port"], conf["email_sender"]["sender"], self.uilogger ) if "slack" in conf: self.slack = Slack( conf['slack']['webhook_path'], url=conf['slack']['webhook_url'], channel=conf['slack']['channel'], username=conf['slack']['username'], icon=conf['slack']['icon'] )
def main(): # load parameter of slack params = load() # scrape draft from web site html = fetch('https://datatracker.ietf.org/doc/active/') if not html: sys.stderr.write("An error occurred. Can not html data") sys.exit(2) draft_list = extract_draft_from_html(html) date_list = extract_date_from_html(html) # create dictionary list dict_list = OrderedDict() for (draft, date) in zip(draft_list, date_list): dict_list[draft] = date search_date = '' if not params['search_date']: # get yesterday date date = datetime.date.today() - datetime.timedelta(1) search_date = date.strftime("%Y-%m-%d") else: search_date = params['search_date'] # post to slack slack = Slack(params['token']) for key, value in dict_list.items(): if value == search_date: print(f'draft: {key}') slack.post(params['channel'], key)
def download_file( cls, token, file, file_dir, user_map: dict, overwrite=False, ): download_url = file['url_private_download'] file_size = cls.bytes_to_str(file['size']) file_user = Slack.get_username(file, user_map) file_name = file['title'] if not file_name.endswith(file['filetype']): file_name += "." + file['filetype'] file_name = file_name.replace(':', ';') file_name = re.sub('[\\\/*?"<>|]', '', file_name) save_name = Slack.format_timestamp(file['timestamp'], full=True, min_divide_char=';', no_slashes=True) save_name += f"- {file_name}" save_loc = os.path.join(file_dir, file_user, save_name) Files.make_dirs(save_loc) print("Downloading file from '" + download_url + "' (" + file_size + ")") return cls.download(download_url, save_loc, overwrite, token)
def exe(): ga = GA() metrics = ga.get_metrics() slack = Slack(metrics) slack.post() return metrics
def test_post(self): slack_webhook_url = "https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX" os.environ["url_env"] = slack_webhook_url responses.add(responses.POST, slack_webhook_url, body="ok", status=200) slack = Slack("url_env") response_text = slack.post("test") self.assertEqual("ok", response_text)
def main(event, context): slack = Slack(os.environ['SLACK_MESSAGE_URL']) slack.ok('Test OK') body = { "message": "Go Serverless v1.0! Your function executed successfully!", "input": event } response = {"statusCode": 200, "body": json.dumps(body)} return response
def main(): """ Starts the Two Bedrooms Scraper """ scraper = Scraper(ASCENT_URL) results = scraper.get_available_floor_plans() formatter = Formatter(results) message = formatter.create_slack_message() slack = Slack(WEBHOOK_URL) slack.send(message)
class SlackLogger: def __init__(self): self.slack = Slack() def InitSlack(self, token, channel): """slack 관련 정보를 초기화한다.""" self.slack.token = token self.slack.channel = channel def __call__(self, msg): """콘솔과 slack에 로그 메시지를 쓴다""" msg = "{0} {1}".format( datetime.now().strftime('[%Y/%m/%d %H:%M:%S]'), msg) print(msg) self.slack.post(msg)
def __init__(self, app, action, formJson, service, env): self.app = app logging.basicConfig( filename='restart.log', level=logging.INFO, format= '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S") #INFO,WARNING self.slackConfig = SlackConfig() self.SLACK_BOT_TOKEN = self.slackConfig.get("SLACK_BOT_TOKEN") self.slack_client = SlackClient(self.SLACK_BOT_TOKEN) self.slack = Slack(self.app) self.auth = Auth(self.app) self.slackDB = SlackDB(self.app) self.formJson = formJson self.user = formJson["user"]["name"] self.channel = formJson["channel"]["name"] self.channelId = formJson["channel"]["id"] self.action = action self.service = service self.env = env self.headers = { 'content-type': 'application/json', } if (not action == ""): function = "self." + action.encode('utf-8') + "()" output = eval(function)
def __init__(self, token): # hardcoded self.blacklist = set(["markovbot", "kitty"]) # hardcoded self.save_file = ".messagestore" # Keyed by user_id self.markovs = defaultdict(Markov) # Flag to inform polling thread of shutdown self.running = False self.slack = Slack(token) self.thread = None # Load saved MCs if os.path.isfile(self.save_file): with open(self.save_file) as handle: self.markovs = pickle.load(handle) # Clean up old versions for key in self.markovs: if not self.markovs[key]: del self.markovs[key] # Reverse dict lookup id_list = [k for k in self.markovs if self.slack.users[k].name == "markovbot"] if id_list: print "Deleting introspective data" del self.markovs[id_list[0]] else: self.messages = defaultdict(list)
def __get_slack_client(self): if not self.__slack: config = configparser.ConfigParser() config.read(self.CONFIG_FILENAME) self.__slack = Slack(config['DEFAULT']['bot_id'], config['DEFAULT']['bot_token']) return self.__slack
def __init__(self): """ 設定ファイルの使う部分をそれぞれセット slackをセット """ super().__init__() self.team_config = self.configs['Team'] self.slack = Slack()
class LunchMinister(Common): """lunch_time_now!!!""" def __init__(self): """ 設定ファイルの使う部分をそれぞれセット slackをセット """ super().__init__() self.team_config = self.configs['Team'] self.slack = Slack() def lunch_time_now(self): """実行関数だよ""" message = '{0:s}チームのみなさん、ランチの時間ですよ'.format(self.team_config['Name']) self.slack.send(message) return 0
def main(): """ Start the Slack Client """ os.system("clear; figlet 'Slack Gitsin' | lolcat") history = FileHistory(os.path.expanduser("~/.slackHistory")) while True: text = prompt("slack> ", history=history, auto_suggest=AutoSuggestFromHistory(), on_abort=AbortAction.RETRY, style=DocumentStyle, completer=Completer(fuzzy_match=False, text_utils=TextUtils()), complete_while_typing=Always(), get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, key_bindings_registry=manager.registry, accept_action=AcceptAction.RETURN_DOCUMENT ) slack = Slack(text) slack.run_command()
def lambda_handler(event, context): logger = logging.getLogger() logger.setLevel(logging.INFO) slack = Slack() try: target_urls = get_target_urls() message_template = '{url} status is {code}' for url in target_urls: response = requests.get(url) code = response.status_code logger.info(code) if code != 200: slack.sendMessage( message_template.format( url=url, code=code ), '#notify' ) except Exception as e: slack.sendMessage(traceback.format_exc(), '#error') logger.error(traceback.format_exc()) raise(traceback.format_exc())
def __init__(self, app, action, formJson, stage, env, version, buildName=""): if (app == None): self.app = Flask(__name__) else: self.app = app logging.basicConfig( filename='teletraan.log', level=logging.INFO, format= '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S") #INFO,WARNING self.maxDisplayAgents = 100 self.slackConfig = SlackConfig() self.slack = Slack(self.app) self.auth = Auth(self.app) self.slackDB = SlackDB(self.app) self.formJson = formJson if (not self.formJson == {}): self.user = formJson["user"]["name"] self.channel = formJson["channel"]["name"] self.channelId = formJson["channel"]["id"] self.action = action self.stage = stage self.env = env self.version = version self.buildName = buildName self.SLACK_BOT_TOKEN = self.slackConfig.get("SLACK_BOT_TOKEN") self.slack_client = SlackClient(self.SLACK_BOT_TOKEN) self.teletraanUrl = self.slackConfig.get("teletraan_url") self.headers = { 'content-type': 'application/json', } if (not action == ""): function = "self." + action.encode('utf-8') + "()" output = eval(function)
def __init__(self, url, name, username, channel, admin, batch, testing=False): self.slack = Slack(url) self.name = name self.username = username self.channel = channel self.batchTime = batch[0] self.batchAmount = batch[1] self.postLock = Lock() self.testing = testing self.admin = admin self.batchEnabled = self.batchAmount > 0 self.usingTimer = self.batchTime > 0 self.posts = []
def main(config_file_name: str): dirpath = os.path.abspath(os.path.dirname(__file__)) conf = yaml.load(open(dirpath + '/' + config_file_name).read()) r = Redmine(conf['atom_url']) try: f = open(dirpath + '/' + conf['last_updated_at'], 'r') last_updated_at = f.read().strip() f.close() except IOError: last_updated_at = r.updated_at entries = r.get_new_entries(last_updated_at) s = Slack(conf['webhook_url'], conf['channel']) for entry in entries: s.post(entry['author_name'], entry['title'], entry['title_link'], entry['text']) # update last_updated_at f = open(dirpath + '/' + conf['last_updated_at'], 'w') f.write(r.updated_at) f.close()
def thread_watchdog(): print('watchdog is running...') process = subprocess.Popen( shlex.split('./airodump-ng --berlin 5 --update 1 wlan0'), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) while process.poll() is None: line = process.stdout.readline().decode().rstrip() if regex_mac48.match(line): if line in dict_mac_user and line in dict_mac_last and int( Epoch()) - int(dict_mac_last[line]) > 1800: Slack.notice( 'TYPE_YOUR_ENDPOINT', '{:s}がプロジェクトルームにいるかもしれません.'.format(dict_mac_user[line])) lock_dict_mac_last.acquire() dict_mac_last[line] = Epoch() lock_dict_mac_last.release()
def __init__(self, url, name, username, channel, batch): self.slack = Slack(url) self.name = name self.username = username self.channel = channel self.batchTime = batch[0] self.batchAmount = batch[1] self.postLock = Lock() if self.batchTime > 0: self.usingTimer = True else: self.usingTimer = False self.posts = []
def process_message(self, peer, mailfrom, rcpttos, data): """ This is the function for smtpServer to receive emails from TradeStation :param peer: :param mailfrom: :param rcpttos: :param data: :return: """ # TODO: restrict sender ip via peer? self.logger.info(' '.join( ["Receiving signal from:", str(peer), ' with\n', data])) # send data to slack channel Slack().send(data) # print "mailfrom:", mailfrom # print "rcpttos:", rcpttos if data: ts_signal = TradeStationSignal(data) if ts_signal.verify_attributes(): self.log_all(' '.join([ 'verified signal:', ts_signal.action, str(ts_signal.quantity), ts_signal.symbol, '@', ts_signal.order_type, "\n\n" ])) # make this threaded perhaps? for ib_cli in self.ib_clients.itervalues(): # sending order to each IB client quantity = int( round(ts_signal.quantity * ib_cli.sig_multiplier)) ib_cli.placeOrder( ib_cli.nextOrderId, ib_cli.create_contract(ts_signal.symbol, 'stk'), ib_cli.create_order( self.order_type_map[ts_signal.order_type], quantity, ts_signal.action)) self.log_all(' '.join([ "sent", ib_cli.account_id, ts_signal.action, str(quantity), ts_signal.symbol, '@', ts_signal.order_type ])) ib_cli.nextOrderId += 1
def init(cls): # Set up Slack load_dotenv() slack = Slack(os.getenv('QS_TOKEN')) # Read statuses statuses_raw = Config.read_config('statuses') statuses = { key: Status.from_dict(statuses_raw[key]) for key in statuses_raw } # Read default status stack default_statuses = [] defaults = Config.read_config('defaults') try: for status in defaults['statuses']: default_statuses.append(Status.from_dict(status)) except KeyError: defaults['statuses'] = [] # Read default Do Not Disturb default_dnd = Expiration.from_timestamp(defaults.get('dnd', None)) # If either the default status or default DND are expired, the config will need to be rewritten rewrite = False while len(default_statuses) > 0: if default_statuses[-1].status_expiration.is_expired(): default_statuses.pop() rewrite = True else: break if default_dnd is not None and default_dnd.is_expired(): default_dnd = None rewrite = True config = cls(slack, statuses, default_statuses, default_dnd) # Rewrite the config, if needed if rewrite: config.write_config() return config
def parse_app(app, meta): if app['name'] == "Atom": return Atom( folder=parse_field('folder', app, meta), file=parse_field('file', app, meta) ) elif app['name'] == "Google-chrome": return GoogleChrome( file=parse_field('file', app, meta) ) elif app['name'] == "XTerm": return XTerm( command=app['cmd'], cwd=parse_field('cwd', app, meta), args=[meta[arg] for arg in app['args']] ) elif app['name'] == "Slack": return Slack() elif app['name'] == "idea": return Idea(folder=parse_field('folder', app, meta))
def recommend(data: pd.DataFrame, interest) -> object: slack = Slack() _interest = interest[0] most_similar = extract_most_similar_paper(data) most_similar_message = generate_recommend_message(data=most_similar, recommend_type='similar', interest=_interest) slack.post_message(most_similar_message) most_dissimilar = extract_most_dissimilar_paper(data) most_dissimilar_message = generate_recommend_message( data=most_dissimilar, recommend_type='dissimilar', interest=_interest) slack.post_message(most_dissimilar_message)
def lambda_handler(event, context): # cloudwatchlogs print 'event: {}'.format(json.dumps(event, indent=2)) data = zlib.decompress(base64.b64decode(event['awslogs']['data']), 16+zlib.MAX_WBITS) data_json = json.loads(data) print 'data: %s' % json.dumps(data_json, indent=2) # slack setting slack = Slack(SLACK_INCOMING_WEBHOOK_URL) slack.username = SLACK_USERNAME slack.icon_emoji = SLACK_EMOJI slack.channel = SLACK_CHANNEL # generate post text for log in data_json["logEvents"]: log_json = json.loads(json.dumps(log, ensure_ascii=False)) print 'log: ' + json.dumps(log_json, indent=2) date_jp = datetime.fromtimestamp(int(str(log_json["timestamp"])[:10])) + timedelta(hours=9) fields = [] fields.append({'title': 'Time', 'value': date_jp.strftime('%Y-%m-%d %H:%M:%S'), 'short': True}) fields.append({'title': 'Owner', 'value': data_json['owner'], 'short': True}) fields.append({'title': 'LogGroup', 'value': data_json['logGroup'], 'short': True}) fields.append({'title': 'LogStream', 'value': data_json['logStream'], 'short': True}) fields.append({'title': 'EventId', 'value': log_json['id'], 'short': True}) fields.append({'title': 'SubscriptionFilters', 'value': ''.join(data_json["subscriptionFilters"]), 'short': True}) text = [] text.append({ 'title': 'CloudWatchLogs', 'color': 'danger', 'fallback': log_json['message'], 'fields': fields }) # post to slack slack.attachments = text slack.post()
def get_player_key(search_string, requestor, name_key_switch): players = Players().get_all_players() bot_type = os.environ["BOT_TYPE"] if bot_type == "groupme": bot_id = os.environ["BOT_ID"] bot = GroupMe(bot_id) elif bot_type == "slack": webhook = os.environ["SLACK_WEBHOOK"] bot = Slack(webhook) elif bot_type == "discord": webhook = os.environ["DISCORD_WEBHOOK"] bot = Discord(webhook) found_players = [] if name_key_switch == 0: for player_id in players: player = players[player_id] try: token_set_ratio = fuzz.token_set_ratio(search_string, player["search_full_name"]) try: injury_status = player["injury_status"] except: injury_status = None if search_string in player["search_full_name"]: found_players.append((player_id, player["full_name"], player["position"], player["team"], injury_status)) elif token_set_ratio > 79: found_players.append((player_id, player["full_name"], player["position"], player["team"], injury_status)) except: pass if player["position"] == "DEF": search_name = player["first_name"].lower() + player["last_name"].lower() search_name = search_name.replace(" ","") full_name_clean = player["first_name"] + " " + player["last_name"] def_ratio = fuzz.ratio(search_string, search_name) try: injury_status = player["injury_status"] except: injury_status = None if def_ratio > 54: found_players.append((player_id, full_name_clean, player["position"], player["team"], injury_status)) if len(found_players) > 1: text = "Which player are you looking for?\n\n" for p in found_players: text += "for {} ({} - {}) - reply {}\n\n".format(p[1], p[2], p[3], p[0]) bot.send(send_any_string, text) return "True" elif len(found_players) == 1: get_player_stats(found_players[0]) return "False" elif len(found_players) == 0: bot.send(send_any_string, 'Player not found') return "False" elif name_key_switch == 1: player = players[search_string] if player["position"] == "DEF": full_name_clean = player["first_name"] + " " + player["last_name"] try: injury_status = player["injury_status"] except: injury_status = None found_players.append((search_string, full_name_clean, player["position"], player["team"], injury_status)) else: try: injury_status = player["injury_status"] except: injury_status = None found_players.append((search_string, player["full_name"], player["position"], player["team"], injury_status)) get_player_stats(found_players[0]) return "False"
def get_depth_chart(team, position): players = Players().get_all_players() bot_type = os.environ["BOT_TYPE"] if bot_type == "groupme": bot_id = os.environ["BOT_ID"] bot = GroupMe(bot_id) elif bot_type == "slack": webhook = os.environ["SLACK_WEBHOOK"] bot = Slack(webhook) elif bot_type == "discord": webhook = os.environ["DISCORD_WEBHOOK"] bot = Discord(webhook) final_string = "Depth Chart for {} - {}\n\n".format(team, position) if position == 'WR': lwrdc_num = [] rwrdc_num = [] swrdc_num = [] for player_id in players: player = players[player_id] if player["team"] == team and player["position"] == position: if player["depth_chart_order"] is not None: if player["depth_chart_position"] == 'LWR': lwrdc_num.append(player["depth_chart_order"]) elif player["depth_chart_position"] == 'RWR': rwrdc_num.append(player["depth_chart_order"]) elif player["depth_chart_position"] == 'SWR': swrdc_num.append(player["depth_chart_order"]) if len(lwrdc_num) > 0: lwrdc_cnt = max(lwrdc_num) i =1 final_string += "WR1:\n" while i <= lwrdc_cnt: for player_id in players: player = players[player_id] if team == player["team"] and position == player["position"] and player["depth_chart_position"] == 'LWR' and i == player["depth_chart_order"]: final_string += "{}. {}\n".format(i, player["full_name"]) i += 1 final_string += "\n" if len(rwrdc_num) > 0: rwrdc_cnt = max(rwrdc_num) i =1 final_string += "WR2:\n" while i <= rwrdc_cnt: for player_id in players: player = players[player_id] if team == player["team"] and position == player["position"] and player["depth_chart_position"] == 'RWR' and i == player["depth_chart_order"]: final_string += "{}. {}\n".format(i, player["full_name"]) i += 1 final_string += "\n" if len(swrdc_num) > 0: swrdc_cnt = max(swrdc_num) i = 1 final_string += "WR3:\n" while i <= swrdc_cnt: for player_id in players: player = players[player_id] if team == player["team"] and position == player["position"] and player["depth_chart_position"] == 'SWR' and i == player["depth_chart_order"]: final_string += "{}. {}\n".format(i, player["full_name"]) i += 1 final_string += "\n" else: dc_num = [] for player_id in players: player = players[player_id] if player["team"] == team and player["position"] == position: if player["depth_chart_order"] is not None: dc_num.append(player["depth_chart_order"]) dc_cnt = max(dc_num) i = 1 while i <= dc_cnt: for player_id in players: player = players[player_id] if team == player["team"] and position == player["position"] and i == player["depth_chart_order"]: final_string += "{}. {}\n".format(i, player["full_name"]) i += 1 bot.send(send_any_string, final_string)
def process_order(self,data,braintree_result=None): shipping = Shipping(self.config) slack = Slack() customer = data['customer']; cart = data['cart']; try: braintree_id = braintree_result.transaction.id except AttributeError: braintree_id = None; #get the stars profit per item influencer_profit = self.db.stars.find_one({"id":data['star_id']})['campaigns'][0]['profit'] #group the cart into separate brand orders #pull the data via profiles section brands = {} for item in cart: ID = str(item['company_id']) if ID in brands: brands[ID]['products'].append(item) else: brands[ID] = {} brands[ID]['company'] = self.db.profiles.find_one({'system':'partners','bio.company_id':ID}) brands[ID]['products'] = [] brands[ID]['products'].append(item) orders = [] #create shipping labels for company_id, value in brands.iteritems(): company = {} company['name'] = company_id company['street'] = value['company']['bio']['address']['street'] company['city'] = value['company']['bio']['address']['city'] company['state'] = value['company']['bio']['address']['state'] company['zip'] = value['company']['bio']['address']['zip'] company['country'] = "US" shipping_info = shipping.purchase_shipping_label(company=company,customer=customer) #build order and submit to the database order = { "order_id": data['order_id'], "star_id": data['star_id'], "company_id": company_id, "braintree_id": braintree_id, "type": "order", "customer": { "name": customer['name'], "email": customer['email'], "addr": { "street": customer['street'], "city": customer['city'], "state": customer['state'], "zip": customer['zip'], "country": customer['country'] } }, "order_date": int(time.time()), "expected_delivery_date": int(time.time()) + 432000, "shipped": False, "received": False, "label_url": shipping_info['label_url'], "tracker_url": shipping_info['tracker_url'], "tracking_code":shipping_info['tracking_code'], "total_price": data['total_price'], "sub_price": data['total_price'] } order['products'] = [] for product in brands[company_id]['products']: order['products'].append({ "sku": "", "item_num": product['item_num'], "product_name": product['name'], "variation": product['variation'], "price": product['price'], "influencer_profit": influencer_profit, "qty": 1 }) #create orders array orders.append(order) #insert all orders at once self.db.orders.insert_many(orders); #send slack alert to Fandemic team slack.sendOrderConfirmation(orders,customer,data) #return success return True
from slack import Slack from score import Score # oledest_day日前から oldest_day = -1 now = datetime.now() duration_day = 1 oldest = datetime(now.year, now.month, now.day, 0, 0, 0, 0) + timedelta(days=oldest_day) latest = oldest + timedelta(days=duration_day) score_all_np = 0 print(oldest, ' ~ ', latest) # get all id ids = Slack.get_channel_list() sc = Score(len(ids)) for id in ids: log = Slack(oldest, latest, id) print('#', log.info['name'], '(', len(log.info['members']), 'members) -', len(log.logs), 'logs') print(log.logs) score = sc.score_log(len(log.logs), len(log.info['members'])) print('num-score:', score) if len(log.logs) == 0: score_pn = 0 print("np-score:", score_pn) print("\n") continue
def get_player_stats(search_object): today = pendulum.today() starting_date = pendulum.datetime(STARTING_YEAR, STARTING_MONTH, STARTING_DAY) if starting_date >= today: year = STARTING_YEAR else: year = int(STARTING_YEAR) - 1 stats = Stats(). get_all_stats("regular",year) bot_type = os.environ["BOT_TYPE"] if bot_type == "groupme": bot_id = os.environ["BOT_ID"] bot = GroupMe(bot_id) elif bot_type == "slack": webhook = os.environ["SLACK_WEBHOOK"] bot = Slack(webhook) elif bot_type == "discord": webhook = os.environ["DISCORD_WEBHOOK"] bot = Discord(webhook) stats_run = True player_id = search_object[0] player_name = search_object[1] position = search_object[2] team = search_object[3] if search_object[4] == None: injury_status = 'Active' else: injury_status = search_object[4] try: player = stats[player_id] except: stats_run = False pass if position not in ["QB","RB","WR","TE","DEF"]: stats_run = False if stats_run: if position is not "DEF": final_string = "{} ({} - {})\n{}\n\n".format(player_name, position, team, injury_status) else: final_string = "{} ({} - {})\n\n".format(player_name, position, team) if position is not "DEF": try: ga = int(player["gms_active"]) except: ga = 0 pass try: gp = int(player["gp"]) except: gp = 0 pass try: gs = int(player["gs"]) pass except: gs = 0 pass try: pts_half_ppr = player["pts_half_ppr"] except: pts_half_ppr = 0 pass final_string += "Fantasy Points: {}\n\nGames Active: {}\nGames Played: {}\nGames Started: {}\n\n".format(pts_half_ppr, ga, gp, gs) try: team_snaps = player["tm_off_snp"] player_snaps = player["off_snp"] snap_perc = round((player_snaps / team_snaps)*100,2) final_string += "Snap Share: {}%\n".format(snap_perc) except: pass if "QB" in position: #try: #rating = player["pass_rtg"] #final_string += "Passer Rating: {}\n".format(rating) #except: #pass try: pyards = int(player["pass_yd"]) final_string += "Passing Yards: {}\n".format(pyards) except: pass try: ptd = int(player["pass_td"]) final_string += "Passing TDs: {}\n".format(ptd) except: pass try: ryards = int(player["rush_yd"]) final_string += "Rushing Yards: {}\n".format(ryards) except: pass try: rtd = int(player["rush_td"]) final_string += "Rushing TDs: {}\n".format(rtd) except: pass try: pass_int = int(player["pass_int"]) final_string += "Interceptions {}\n".format(pass_int) except: pass try: fum = int(player["fum"]) final_string += "Fumbles: {}\n".format(fum) except: pass if "RB" in position: try: ryards = int(player["rush_yd"]) final_string += "Rushing Yards: {}\n".format(ryards) except: pass try: rtd = int(player["rush_td"]) final_string += "Rushing TDs: {}\n".format(rtd) except: pass try: fum = int(player["fum"]) final_string += "Fumbles: {}\n".format(fum) except: pass try: catch_perc = round((player["rec"]/player["rec_tgt"])*100,2) final_string += "Catch Rate: {}%\n".format(catch_perc) except: pass try: rcyards = int(player["rec_yd"]) final_string += "Receiving Yards: {}\n".format(rcyards) except: pass try: rctd = int(player["rec_td"]) final_string += "Receiving TDs: {}\n".format(rctd) except: pass if "WR" in position: try: rcyards = int(player["rec_yd"]) final_string += "Receiving Yards: {}\n".format(rcyards) except: pass try: rctd = int(player["rec_td"]) final_string += "Receiving TDs: {}\n".format(rctd) except: pass try: drop_perc = round((player["rec"]/player["rec_tgt"])*100,2) final_string += "Catch Rate: {}%\n".format(drop_perc) except: pass try: ryards = int(player["rush_yd"]) final_string += "Rushing Yards: {}\n".format(ryards) except: pass try: rtd = int(player["rush_td"]) final_string += "Rushing TDs: {}\n".format(rtd) except: pass try: fum = int(player["fum"]) final_string += "Fumbles: {}\n".format(fum) except: pass if "TE" in position: try: rcyards = int(player["rec_yd"]) final_string += "Receiving Yards: {}\n".format(rcyards) except: pass try: rctd = int(player["rec_td"]) final_string += "Receiving TDs: {}\n".format(rctd) except: pass try: drop_perc = round((player["rec"]/player["rec_tgt"])*100,2) final_string += "Catch Rate: {}%\n".format(drop_perc) except: pass try: ryards = int(player["rush_yd"]) final_string += "Rushing Yards: {}\n".format(ryards) except: pass try: rtd = int(player["rush_td"]) final_string += "Rushing TDs: {}\n".format(rtd) except: pass try: fum = int(player["fum"]) final_string += "Fumbles: {}\n".format(fum) except: pass if "K" in position: try: fga = int(player["fga"]) fgm = int(player["fgm"]) fgperc = round((fgm/fga)*100,2) final_string += "FG%: {}\n\nField Goals Attempted: {}\nField Goals Made: {}\n".format(fgperc, fga, fgm) except: pass try: fgm = int(player["fgm"]) final_string += "Field Goals Made: {}\n".format(fgm) except: pass try: fgm1 = int(player["fgm_0_19"]) final_string += "0-19: {}\n".format(fgm1) except: pass try: fgm2 = int(player["fgm_20_29"]) final_string += "20-29: {}\n".format(fgm2) except: pass try: fgm3 = int(player["fgm_30_39"]) final_string += "30-39: {}\n".format(fgm3) except: pass try: fgm4 = int(player["fgm_40_49"]) final_string += "40-49: {}\n".format(fgm4) except: pass try: fgm5 = int(player["fgm_50p"]) final_string += "50+: {}\n".format(fgm5) except: pass try: xpa = int(player["xpa"]) xpm = int(player["xpm"]) xpperc = round((xpm/xpa)*100,2) final_string += "XP%: {}\n\nXP Attempted: {}\nXP Made: {}\n".format(xpperc, xpa, xpm) except: pass if "DEF" in position: try: td = int(player["td"]) final_string += "Touchdowns: {}\n".format(td) except: pass try: ff = int(player["ff"]) final_string += "Forced Fumbles: {}\n".format(ff) except: pass try: fum_rec = int(player["fum_rec"]) final_string += "Fumbles Recoved: {}\n".format(fum_rec) except: pass try: tkl = int(player["tkl_loss"]) final_string += "Tackles For Loss: {}\n".format(tkl) except: pass try: qbh = int(player["qb_hit"]) final_string += "QB Hits: {}\n".format(qbh) except: pass try: sck = int(player["sack"]) final_string += "Sacks: {}\n".format(sck) except: pass else: if player_name == "Aaron Hernandez": final_string = "{} hung himself. Gone Forever! Aaron Hernandez.".format(player_name) elif position not in ["QB","RB","WR","TE"]: final_string = "I do not do IDP stats" else: final_string = "No {} stats found for {}".format(year, player_name) bot.send(send_any_string, final_string)
import logging from exchanges import Exchanges from imgur import Imgur from slack import Slack from firestore import FireStore from dotenv import load_dotenv load_dotenv() logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO, datefmt='%m/%d/%Y %I:%M:%S %p') logger = logging.getLogger(__name__) if __name__ == '__main__': logger.info('Starting crypto-balance-check worker') exchanges = Exchanges() slack = Slack() firestore = FireStore() imgur = Imgur() positions_by_exchange = exchanges.get_all_positions_by_exchange() slack.publish_all_positions_by_exchange(positions_by_exchange) firestore.update_historic_balances(positions_by_exchange) balances = firestore.get_historic_balances() url = imgur.send_graph([b[0] for b in balances], [b[1] for b in balances]) slack.publish_url(url) logger.info('Exiting crypto-balance-check worker')
def init_redmine_api(url=api_conf.redmine_url, version=api_conf.redmine_version, api_key=api_conf.redmine_key): return Redmine(url, version=version, key=api_key) # ZAP variables zap = init_zap_api() core = zap.core ascan = zap.ascan forcedUser = zap.forcedUser spider = zap.spider ajax = zap.ajaxSpider script = zap.script context = zap.context auth = zap.authentication users = zap.users sessionManagement = zap.sessionManagement replacer = zap.replacer # Redmine variables redmine = init_redmine_api() # Slack variable slack = Slack(webhook=api_conf.slack_hook, token=api_conf.slack_token, channel_id=api_conf.slack_channel_id, channel=api_conf.slack_channel, slack_url=api_conf.slack_url)
from teamwork import Teamwork from slack import Slack from dateutil import parser import json import sys import datetime config = json.loads(open(sys.argv[1]).read()) idmap = {'34144':'U04QRTZ3X'} tw = Teamwork(config['tw']['account-name'], config['tw']['token']) s = Slack(config['slack']['token']) now = datetime.datetime.now() today = tw.calendarevents(startdate=now, enddate=now) for twid, sid in idmap.items(): message = "*Your meetings for today*\n" for event in today['events']: print print event print if twid in event['notify-user-ids'] or (twid in event['attending-user-ids']): #for key, value in event.items(): # print key, value #print
return "No processes found", 200 slackClient.SendProcessSelection(processes, trigger) return "", 200 def FavoriteProcesses(request, user, slackClient): trigger = request.form['trigger_id'] envProcessObj = user.GetEnvProcesses() slackClient.SendEnvProcesses(envProcessObj, trigger) return "", 200 #@app.route("/thanks", methods=["GET", "POST"]) def thanks(): """ This route is called by Slack after the user installs our app. It will exchange the temporary authorization code Slack sends for an OAuth token which we'll save on the bot object to use later. To let the user know what's happened it will also render a thank you page. """ # Let's grab that temporary authorization code Slack's sent us from # the request's parameters. code_arg = request.args.get('code') # The bot's auth method to handles exchanging the code for an OAuth token #pyBot.auth(code_arg) return render_template("thanks.html") if __name__ == '__main__': slackClient = Slack() app.run(debug=True)
from forum import ForumPosts from slack import Slack if __name__ == '__main__': posts = ForumPosts() uncommented_posts = posts.filter_uncommented_posts() for post in uncommented_posts: slack = Slack(post.slack_text.asdict()) slack.post()
from slack import Slack from items import Sneaker sneaker = Sneaker() sizes = list() sizes.append("5 / Stock: 10") sizes.append("10 / Stock: 0") sizes.append("20 / Stock: 30") sizes.append("30 / Stock: 0") sizes.append("40 / Stock: 50") sneaker['name'] = "Trip.io beta V2" sneaker['price'] = 200 sneaker['currency'] = "USD" sneaker['url'] = "https://shop.bdgastore.com/products/w-nike-air-max-plus-lux" sneaker[ 'image'] = "http://cdn.shopify.com/s/files/1/0049/9112/products/BTKA_15144940918813283_f79c0aa0e2825fd0d41629395bbb49_grande.jpg?v=1514494399" sneaker['stock'] = 150 sneaker['sizes'] = sizes # sneaker['tag'] = "supreme" match_type = "New product" slack = Slack() slack.post(sneaker, match_type)
class Bot(object): """Slackchat bot for imitating users""" def __init__(self, token): # hardcoded self.blacklist = set(["markovbot", "kitty"]) # hardcoded self.save_file = ".messagestore" # Keyed by user_id self.markovs = defaultdict(Markov) # Flag to inform polling thread of shutdown self.running = False self.slack = Slack(token) self.thread = None # Load saved MCs if os.path.isfile(self.save_file): with open(self.save_file) as handle: self.markovs = pickle.load(handle) # Clean up old versions for key in self.markovs: if not self.markovs[key]: del self.markovs[key] # Reverse dict lookup id_list = [k for k in self.markovs if self.slack.users[k].name == "markovbot"] if id_list: print "Deleting introspective data" del self.markovs[id_list[0]] else: self.messages = defaultdict(list) def start(self): """Begin polling for messages""" self.running = True self.thread = threading.Thread(target=self.poll) self.thread.start() print "Started polling thread" def kill(self): """Kill the polling thread""" self.running = False self.thread.join() self.save() def get_history(self): """Download as much history as possible""" count = 0 for user, text in self.slack.get_history(): if self.add_message(user, text): count += 1 print "Loaded %d messages from history" % count def save(self): """Save dictionary of MCs #TODO: Incremental save """ with open(self.save_file, 'w+') as handle: pickle.dump(self.markovs, handle) def add_message(self, user, text): """Add transition counts from a received message""" if user and self.slack.users[user].name not in self.blacklist: self.markovs[user].add(text) return True else: return False def poll(self): """Poll slack API for messages TODO: Break saving state out into separate thread or at least method """ count = 0 while self.running: user, message = self.slack.get_message() # This is here to make it so we can exit cleanly # TODO: Something less clunky if message is None: continue count += 1 # hardcoded if count == 50: self.save() count = 0 print "%s: %s" % (user, message) self.add_message(user, message) def send_message(self): """Choose a user, generate a message for them, and send it TODO: Break out user selection, and make clever TODO: Somehow seed by previous message """ if self.markovs: user_id = random.choice([k for k in self.markovs]) text = self.markovs[user_id].generate() # hardcoded self.slack.send_message("bot-playground", user_id, text) else: # No data loaded pass
class Skin(object): startPos = 0 # proportion of the left panel body, to the chat panel body_proportion = 0.20 # proportion of textarea vertically to the chat panel text_area_proportion = 0.20 def __init__(self): self.stdscr = None # instantiate a Slack client self.slack_client = Slack() self.slack_client.setup() self.showing = 0 self.selection = 0 def setup(self, stdscr): self.stdscr = stdscr # define curses color pairs set_color_pairs() # set getch to blocking self.stdscr.nodelay(0) # don't echo key strokes on the screen curses.noecho() # read keystrokes instantly, without waiting for enter to be pressed curses.cbreak() # enable keypad mode self.stdscr.keypad(1) # draw the main frame self.setup_draw() # find what's the erase character self.del_char = curses.erasechar() self.run() def setup_draw(self): # get screen dimensions self.maxY, self.maxX = self.stdscr.getmaxyx() # n_lines, n_cols, begin_y, begin_x self.head_win = curses.newwin(1, self.maxX, 0, 0) # left panel, contacts self.body_win = curses.newwin(self.maxY - 1, int(self.maxX * self.body_proportion), 1, 0) # chat frame self.chat_win = curses.newwin( self.maxY - 1 - int(self.maxY * self.text_area_proportion), self.maxX - int(self.maxX * self.body_proportion), 1, int(self.maxX * self.body_proportion)) # chat window (displays text) self.chatarea = curses.newwin( self.maxY - 1 - int(self.maxY * self.text_area_proportion) - 2, self.maxX - int(self.maxX * self.body_proportion) - 2, 2, int(self.maxX * self.body_proportion) + 1) # bottom frame window self.text_win = curses.newwin( int(self.maxY * self.text_area_proportion), self.maxX - int(self.maxX * self.body_proportion), self.maxY - int(self.maxY * self.text_area_proportion), int(self.maxX * self.body_proportion)) # bottom textarea self.textarea = curses.newwin( int(self.maxY * self.text_area_proportion) - 2, self.maxX - int(self.maxX * self.body_proportion) - 2, self.maxY - int(self.maxY * self.text_area_proportion) + 1, int(self.maxX * self.body_proportion) + 1) self.init_head() self.init_body() self.init_chat() self.init_chatarea() self.init_textbox() self.init_textarea() self.body_win.keypad(1) curses.doupdate() def init_head(self): name = "Slacky (github.com/mathiasbc)" middle_pos = int(self.maxX / 2 - len(name) / 2) self.head_win.addstr(0, middle_pos, name, curses.color_pair(2)) self.head_win.bkgd(' ', curses.color_pair(7)) self.head_win.noutrefresh() def init_body(self): """ Initializes the body/story window """ self.bodyMaxY, self.bodyMaxX = self.body_win.getmaxyx() self.body_win.noutrefresh() self.refresh_body() def init_chat(self): """ Draws the chat frame """ self.chat_max_y, self.chat_max_x = self.chat_win.getmaxyx() self.body_win.noutrefresh() self.chat_win.box() self.chat_win.refresh() def init_chatarea(self): """ Draws the chat area to display chat text """ self.chatarea.refresh() # represents the y position where to start writing chat self.chat_at = 0 def init_textbox(self): """ Draws the textbox under the chat window """ self.text_win.box() self.text_win.refresh() def init_textarea(self): # the current displayed text self.char_pos = [0, 0] self.text = "" self.textarea.refresh() self.refresh_textarea() def set_body_selection(self, number): """ Select chat """ self.selection = number maxDisplayedItems = self.bodyMaxY - 2 if self.selection - self.startPos >= maxDisplayedItems: self.startPos = self.selection - maxDisplayedItems + 1 elif self.selection < self.startPos: self.startPos = self.selection def refresh_body(self): """ sets the new selection on the body and clears the chat """ self.body_win.erase() self.body_win.box() maxDisplay = self.bodyMaxY - 1 for lineNum in range(maxDisplay - 1): i = lineNum + self.startPos if i < len(self.slack_client.active): self.__display_body_line(lineNum, self.slack_client.active[i].name) self.body_win.refresh() def __display_body_line(self, lineNum, station): col = curses.color_pair(5) # if the cursor is on the highligted chat/group is_current = self.selection == self.showing if lineNum + self.startPos == self.selection and is_current: col = curses.color_pair(9) self.body_win.hline(lineNum + 1, 1, ' ', self.bodyMaxX - 2, col) elif lineNum + self.startPos == self.selection: col = curses.color_pair(6) self.body_win.hline(lineNum + 1, 1, ' ', self.bodyMaxX - 2, col) elif lineNum + self.startPos == self.showing: col = curses.color_pair(4) self.body_win.hline(lineNum + 1, 1, ' ', self.bodyMaxX - 2, col) line = "{0}. {1}".format(lineNum + self.startPos + 1, station) self.body_win.addstr(lineNum + 1, 1, line, col) def refresh_textarea(self, char=None): # draws a border on the window self.textarea.addstr(0, 0, self.text) self.textarea.refresh() def update_chat(self): """ clears the chatbox and resets some things """ self.chatarea.clear() self.chat_at = 0 # TODO: draw last 2 messages self.chatarea.refresh() def backspace(self): self.text = self.text[:-1] self.textarea.clear() self.refresh_textarea() def send_text(self): """ Sends the string in textarea and clear the window """ _id = self.slack_client.active[self.showing].id self.slack_client.message_channel(_id, self.text) self.char_pos = [1, 1] self.text = "" self.textarea.clear() self.refresh_textarea() def push_chat(self, username, chat): """ write the given string at the correct position in the chatarea """ # FIXME: fails when text goes beyond window limit # highlight username col = curses.color_pair(8) self.chatarea.addstr(self.chat_at, 0, username + ':', col) # write the actual chat content self.chatarea.addstr(chat) # update cursor self.chat_at, _ = self.chatarea.getyx() self.chat_at += 1 self.chatarea.refresh() def run(self): self.refresh_body() while True: try: c = self.body_win.getch() ret = self.keypress(c) except KeyboardInterrupt: break def keypress(self, char): # right arrow select a user/group to chat with if char == curses.KEY_RIGHT: self.refresh_body() self.update_chat() self.showing = self.selection current_id = self.slack_client.active[self.showing].id current_name = self.slack_client.active[self.showing].name for m in self.slack_client.last_messages(current_id): self.push_chat(m['user'], m['text']) return # moves to the user/group below current selection elif char == curses.KEY_DOWN: if self.selection < len(self.slack_client.active) - 1: self.set_body_selection(self.selection + 1) self.refresh_body() return # move cursor one position up elif char == curses.KEY_UP: if self.selection > 0: self.set_body_selection(self.selection - 1) self.refresh_body() return # send the content on the textbox elif char == curses.KEY_ENTER or chr(char) == "\n": # Fixme: send message as 'me', should be username self.push_chat('me', self.text) self.send_text() return # delete a character elif chr(char) == self.del_char or chr(char) == "\x7f": self.backspace() return # send the char to textbox area else: self.text += chr(char) self.refresh_textarea(char) return
class SlackServer(): def __init__(self, url, name, username, channel, batch): self.slack = Slack(url) self.name = name self.username = username self.channel = channel self.batchTime = batch[0] self.batchAmount = batch[1] self.postLock = Lock() if self.batchTime > 0: self.usingTimer = True else: self.usingTimer = False self.posts = [] def post(self, content): with self.postLock: self.posts.append(SlackPost(content)) if len(self.posts) >= self.batchAmount: self._flush() elif len(self.posts) == 1: # start timer self.timer = Timer(self.batchTime, self.flush) self.timer.daemon = True self.timer.start() def postRich(self, title, content, color, fallback): post = SlackPost() post.addAttachment(title, content, color, fallback) with self.postLock: self.posts.append(post) if len(self.posts) >= self.batchAmount: self._flush() elif len(self.posts) == 1: # start timer self.timer = Timer(self.batchTime, self.flush) self.timer.daemon = True self.timer.start() def flush(self): with self.postLock: if self.timer is not None: # cancel any outstanding timers self.timer.cancel() if len(self.posts) > 0: self._flush() def _flush(self): final_post = SlackPost() for i in self.posts: final_post.merge(i) data = final_post.render() data.update({"channel": self.channel, "username": self.username}) # print "Sending: " + str(data) self.slack.send(data) # clear posts self.posts = [] def __str__(self): if self.batchTime: return "<SlackServer {}, username {}, channel {}, batch [time {}, amount {}]>".format( self.name, self.username, self.channel, self.batchTime, self.batchAmount) else: return "<SlackServer {}, username {}, channel {}>".format( self.name, self.username, self.channel)
# Check if the user specified the close game num. Default is 20. try: close_num = os.environ["CLOSE_NUM"] except: close_num = 20 starting_date = pendulum.datetime(STARTING_YEAR, STARTING_MONTH, STARTING_DAY) if bot_type == "groupme": bot_id = os.environ["BOT_ID"] bot = GroupMe(bot_id) elif bot_type == "slack": webhook = os.environ["SLACK_WEBHOOK"] bot = Slack(webhook) elif bot_type == "discord": webhook = os.environ["DISCORD_WEBHOOK"] bot = Discord(webhook) bot.send(get_welcome_string) # inital message to send schedule.every().thursday.at("19:00").do( bot.send, get_matchups_string, league_id) # Matchups Thursday at 4:00 pm ET schedule.every().friday.at("12:00").do( bot.send, get_scores_string, league_id) # Scores Friday at 12 pm ET schedule.every().sunday.at("23:00").do( bot.send, get_close_games_string, league_id, int(close_num)) # Close games Sunday on 7:00 pm ET schedule.every().monday.at("12:00").do( bot.send, get_scores_string, league_id) # Scores Monday at 12 pm ET
def notice(candidates: list): if len(candidates): Slack.notice( 'TYPE YOUR ENDPOINT', 'わんちゃんありやなぁ・・・\n' + '\n'.join(candidates) + '\n今すぐ予約! → https://biwako-booking.doshisha.ac.jp/' )