def main(): slack = slackweb.Slack(url=os.environ['SLACKWEB_ANDDATA_MARKETBOT']) with open('tosho.list', 'r') as f: codes = f.read().splitlines() for code in codes: attachments = [] print(code) company_name, infos = get_fundametals(code) try: data = get_data(code) except: print("ETF?") continue series1, series2, series3 = get_moving_average(data) if golden_crossover(series1, series2, series3): attachment = { "title": company_name, "color": "good", "title_link": "https://stocks.finance.yahoo.co.jp/stocks/detail/?code={}". format(code), "text": "{}".format("\n".join(infos)) } attachments.append(attachment) elif dead_crossover(series1, series2, series3): attachment = { "title": company_name, "color": "danger", "title_link": "https://stocks.finance.yahoo.co.jp/stocks/detail/?code={}". format(code), "text": "{}".format("\n".join(infos)) } attachments.append(attachment) else: pass #attachment = {"title": company_name, # "color": "warning", # "title_link": "https://stocks.finance.yahoo.co.jp/stocks/detail/?code={}".format(code), # "text": "{}".format("\n".join(infos))} #attachments.append(attachment) if attachments: slack.notify(attachments=attachments) print("all {} companies were analized".format(len(codes)))
def configure_slack(self): slack_url = "" try: self.configfile = os.getcwd() + '/config' config = ConfigParser.RawConfigParser() config.read(self.configfile) slack_url = config.get('slack', 'hookurl') except: print "Warning: No Slack integration found, so not using. See config file to setup." self.slack = None if len(slack_url) > 0: self.slack = slackweb.Slack(url=slack_url)
def _notify(text, color): if 'CIRCLE_BUILD_URL' in os.environ: text += ' <{}|#{}>'.format(os.environ['CIRCLE_BUILD_URL'], os.environ['CIRCLE_BUILD_NUM']) slack = slackweb.Slack(url=os.environ['SLACK_INCOMING_WEBHOOK']) attachment = { 'color': color, 'text': text, 'author_name': author_name, } slack.notify(username=username, icon_url=icon_url, attachments=[attachment])
def slack_notify(message, channel="#botlog", username="******"): ''' slack = slackweb.Slack(url="https://hooks.slack.com/services/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") slack.notify(text="[%s] %s" % (socket.gethostname(), message), channel="#botlog", username="******", icon_emoji=":ellie:") ''' slack = slackweb.Slack( url= "https://hooks.slack.com/services/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" ) slack.notify(text="[%s] %s" % (socket.gethostname(), message), channel=channel, username=username, icon_emoji=":ellie:")
def slack_notify(message): """ Send notification to slack channel. - `pip install slackweb` - URL should be set by incoming webhook. Args: message (str): message. """ # Don't forget to disable token url = "<Incoming Webhook>" slack = slackweb.Slack(url=url) slack.notify(text=message)
def slackout(daytable, df_tan_nin, jockey, youbi): slack = slackweb.Slack(url=os.environ.get('WEBHOOK_URL')) if len(df_tan_nin) == 0: slack.notify(text="*" + jockey + "の" + youbi + "のレースで条件に合致するものはありません:racehorse:" + "*", mrkdwn=True) else: slack.notify(text="*" + jockey + "の" + youbi + "のレースで条件に合致するものを報告します:racehorse:" + "*", mrkdwn=True) for i in daytable.index: slack.notify(text=daytable['場'][i] + "第" + str(daytable['R'][i]) + "レース" + str(daytable['レース名'][i]) + str(daytable['コース'][i]) + "mが" + df_tan_nin["人気"][i] + "番人気で、" + "単勝は" + df_tan_nin["単勝"][i] + "です")
def handle(self, *args, **options): f = open('crawl_progress.log', 'r') last_line = f.readlines()[-1].strip() f.close() infos = last_line.split(' - ') now_count = Review.objects.all().count() print(infos) slack = slackweb.Slack(url=os.environ.get('SLACK_WEBHOOK_URL')) if infos: last_time = infos[0].split(',')[0] slack.notify( text="<!channel>\n前回取得時刻: {}、取得数: {}\n現在取得数: {}, 前回からの進捗: {}". format(last_time, infos[1], now_count, now_count - int(infos[1]))) self.logger.info(now_count)
def _notify(text, color): if 'CIRCLE_BUILD_URL' in os.environ: text += ' <{}|#{}>'.format(os.environ['CIRCLE_BUILD_URL'], os.environ['CIRCLE_BUILD_NUM']) slack = slackweb.Slack(url=os.environ['SLACK_INCOMING_WEBHOOK']) attachment = { 'color': color, 'text': text, 'author_name': 'blog', 'author_icon': firebase_mini_icon, } slack.notify(username='******', icon_url=circleci_icon, attachments=[attachment])
def handle_text_message(event): """ Text Message """ slack_info = slackweb.Slack(url=WEB_HOOK_LINKS) user_id, user_name, msg_type, room_id = get_event_info(event) send_msg = "[bot-line] {user_name}\n".format(user_name=user_name) \ + "{msg}\n".format(msg=event.message.text) \ + "---\n" \ print("!!! get slack info !!!", slack_info) slack_info.notify(text=send_msg)
def main(): get_temp() get_ram_usage() get_disk_usage() post = "" with open(result_file, 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: post += line print(post) slack = slackweb.Slack(url=slack_post) slack.notify(text=post)
def post(self, data): if (data == False): return False title = data["title"] maxint = self.__parse_maxint(data["maxint"])[:1] body = None if (title == self.__detail_title): body = self.__create_slack_body_detail(data) if (title == self.__quick_title): body = self.__create_slack_body_quick(data) user_name = self.__create_slack_username(title) slack_conn = slackweb.Slack(url=self.__token) if int(maxint) >= self.__minint: icon = self.__create_slack_icon(maxint) slack_conn.notify(text=body, username=user_name, icon_emoji=icon)
def train(dataset_dir: str, word_length: bool, last_char: bool, model_name: str = 'crf'): """ Args: dataset_dir (str): dataset path used by NER experiment word_length (bool): if True, add word length features last_char (bool): if True, add last char in a word features model_name (str, optional): used in saving model. Defaults to 'crf'. """ dataset_dir += '/' if dataset_dir[-1] != '/' else '' logger.info('show setting parameters\n\ dataset_dir: {}\n\ word_length: {}\n\ last_char: {}\n\ model_name: {}' .format(dataset_dir, word_length, last_char, model_name)) logger.info('start experiment') target_class = re.match(r'([^/]+?)?$', dataset_dir[:-1]) target_class = dataset_dir[dataset_dir[:-1].rfind('/') + 1:-1] dataset = Dataset(dataset_dir, target_class, False, word_length, last_char) model = Model() trainer = Trainer(model, dataset) logger.info('training!') trainer.train() report = trainer.report() # show report for target in ['all', 'unknown', 'known']: metrics_dict = { 'precision': [], 'recall': [], 'f1-measure': [] } for NE_label in ['PRO', 'SHO']: for metrics in ['precision', 'recall', 'f1_score']: # ライブラリの都合で名前を変更している truemet = 'f1-measure' if metrics == 'f1_score' else metrics metrics_dict[truemet] += [ report[target][NE_label][metrics] ] df = pd.DataFrame(metrics_dict, index=['PRO', 'SHO']) print(target) print(df) df.to_csv('data/03_result/{0}_{1}.csv'.format(model_name, target)) slack = slackweb.Slack(url=os.environ.get('SLACK_NOTIFY_URL')) slack.notify(text='実験が終了しました') pickle.dump(model, open('data/result/{}.pickle'.format(model_name), 'wb'))
def __send(self, json_data): hypo_type = str(json_data['request_hypo_type']) report_num = str(json_data['report_num']) intensity = str(json_data['calcintensity']) report_time = str(json_data['report_time']) slack_conn = slackweb.Slack(url=self.__token) intensity = int(str(json_data['calcintensity'])[:1]) alertflg = str(json_data['alertflg']) user_name = self.__title body = self.__create_body(json_data) icon = self.__create_icon(json_data) # 緊急地震速報かつ第一報かつ予想震度が2以上ならslackに通知する if hypo_type == 'eew' and ( (report_num == '1' and int(intensity) >= self.__minint) or alertflg == '警報'): slack_conn.notify(text=body, username=user_name, icon_emoji=icon)
def enable_access(self): with open(HOSTS_FILEPATH, mode="r") as f: txt = f.read() txt = txt.replace("\n"+"0.0.0.0 "+self.penalty_sites[0]+" #"+self.penalty_endtimes[0].strftime("%Y-%m-%d %H:%M"), "") with open(HOSTS_FILEPATH, mode="w") as f: f.write(txt) slack = slackweb.Slack(url=self.webhook_var.get()) slack.notify(text=self.computer_name+"へのお仕置きはこれくらいにしといてあげたわよ\n" + "- 対象アプリケーション:" + self.penalty_files[0] + "\n" + "- 対象Webサイト:" + self.penalty_sites[0]) del self.penalty_sites[0] del self.penalty_files[0] del self.penalty_endtimes[0] if len(self.penalty_endtimes) == 0: self.penalty_val.set("") self.penalty_label.config(bg='SystemButtonFace')
def hook_send(message): """sends message to selected for bot-hook channel""" slack_client = SlackClient(message.team.bot_access_token) users = slack_client.api_call("users.list") for user in users['members']: if user['id'] == message.user_id: sender = user break name = sender['real_name'] nick = sender['id'] message.user_name = name message.save() hook = message.team.incoming_hook slack = slackweb.Slack(url=hook) slack.notify(text="{0}({1}): {2}".format(name, nick, message.text))
def post(): # move to the repository os.chdir(os.path.dirname(os.path.abspath(__file__))) slack = slackweb.Slack(url=config.SLACK_URL) hist = history() with open("misc/history.pickle", "rb") as f: hist = pickle.load(f) files = os.listdir("img") for f in files: slack.notify(text=hist.get_url(f)) os.remove("img/" + f) os.removedirs("img")
def notify_slack(status): slack = slackweb.Slack(url=WEBHOOK_URL) attachments = [{ "color": "#36a64f", "title": "Manipulate composer automatically", "fields": [{ "title": "Project", "value": f"{PROJECT_ID}" }, { "title": "status", "value": status }], }] slack.notify(attachments=attachments)
def main(self): options = Options() options.add_argument('--headless') driver = webdriver.Chrome(options=options) number = 0 while number < 1000: wait = WebDriverWait(driver, 20) url = "https://yoyaku-f.koyama.co.jp/scripts/mtr1010.asp" driver.get(url) time.sleep(5) login_element = wait.until( EC.element_to_be_clickable((By.NAME, 'login'))) user_code_xpath = "/html/body/div/form/table/tbody/tr[1]/td[2]/input" user_password_xpath = "/html/body/div/form/table/tbody/tr[2]/td[2]/input" driver.find_element_by_xpath(user_code_xpath).send_keys(USC) driver.find_element_by_xpath(user_password_xpath).send_keys(USP) login_element.click() # ログインボタン reserve_element = wait.until( EC.element_to_be_clickable((By.NAME, 'mtr1010'))) reserve_element.click() # 技能予約を選択 wait.until(EC.element_to_be_clickable((By.NAME, 'logout'))) kushya1 = driver.find_elements_by_xpath( "//input[@src='/images/ko2_kusya.gif']") logout_path = "/html/body/div[1]/form[2]/input" wait.until(EC.element_to_be_clickable((By.NAME, 'logout'))) driver.find_element_by_xpath(logout_path).click() wait.until(EC.element_to_be_clickable((By.NAME, 'login'))) empty_number = len(kushya1) dt_now = datetime.datetime.now() webhook_url = WHU text = '現在コヤマに空きが%d件あります。急げ!' % empty_number if empty_number > 0: slack = slackweb.Slack(url=webhook_url) slack.notify( username="******", icon_url= "https://stickershop.line-scdn.net/stickershop/v1/product/1154602/LINEStorePC/main.png;compress=true", text=text) elif empty_number == 0: print(dt_now.strftime('%Y年%m月%d日 %H:%M') + "時点空き無し") time.sleep(60) number += 1 pass
def request_slack(self): # POレビュー依頼 import slackweb slack = slackweb.Slack(url=os.environ["slack_webhook_url"]) list_after = self.tr_event.get_list_after_name() attachments = [{ "color": "#2eb886", "title": f"ストーリー「{self.card.name}」", "title_link": f"{self.card.url}", "text": "がDoneになりました。お手すきの際にPOレビューお願いします。" }] if "Done" in list_after: slack.notify(text=f"<@{os.environ['slack_mention']}>", attachments=attachments)
def PostSlackNotify(self, str: str) -> int: """Slack通知ポスト Args: str (str): Slackに通知する文字列 Returns: int: 0(成功) """ try: slack = slackweb.Slack(url=self.SLACK_WEBHOOK_URL) slack.notify(text="<!here> " + str) except ValueError: logger.error("Webhook URL error: {0} is invalid".format(self.SLACK_WEBHOOK_URL)) return None return 0
def lambda_handler(event, context): # SNS sns_dumps = json.dumps(event['Records'][0]['Sns']) sns = json.loads(sns_dumps) # Message message_loads = json.loads(sns_dumps)['Message'] message = json.loads(message_loads) # Slack url = os.environ['SLACK_WEBHOOK_URL'] slack = slackweb.Slack(url=url) text = sns['Message'] slack.notify(text=text) return {'message': text}
def __init__(self, api='line', output=True): if not os.path.exists(JSONFILE): raise FileNotFoundError('No JSON file.') with open(JSONFILE, 'r') as t: tokens = json.load(t) if api == 'slack': self.token = tokens['slack_token'] self.s = slackweb.Slack(url=self.token) elif api == 'line': self.token = tokens['line_token'] self.s = None else: raise ValueError('API : slack or LINE') self.api = api self.output = output
def lambda_handler(event, context): url = os.getenv("SLACKURL", None) if url is None: exit(1) imageurl = os.getenv("IMAGEURL", None) if imageurl is None: exit(1) print("Received event: " + json.dumps(event, indent=2)) channel = os.getenv("CHANNEL", "#sns") name = os.getenv("NAME", "Gyazo") slack = slackweb.Slack(url=url) key = event['Records'][0]['s3']['object']['key'] message = imageurl + '/' + key slack.notify(channel=channel, username=name, text=message) return message
def __load_config(self): parser = configparser.ConfigParser() parser.read(os.getcwd() + '/config/datadog.ini') if 'slack' not in parser: raise RuntimeWarning s = parser['slack'] self.slack = slackweb.Slack(url=s.get('url')) channel = s.get('channel') or '#general' username = s.get('username') or 'Bot' icon_emoji = s.get('icon_emoji') or ':ghost:' self.slack_notifier = partial(self.slack.notify, channel=channel, username=username, icon_emoji=icon_emoji)
def set_send_slack(self, token, title, sender, **kwargs): print(len(kwargs)) #토큰을 통해 해당 채널에 접속 slack = slackweb.Slack(url=token) if len(kwargs) >= 1: attachments = kwargs['attachements'] #내역 slack 으로 전송 #text : 슬랙 메세지 제목, username : 보내는 사람, attachments : 보내는 내역 slack.notify(text=title, username=sender, attachments=attachments) else: #내역 slack 으로 전송 #text : 슬랙 메세지 제목, username : 보내는 사람, slack.notify(text=title, username=sender)
def send_slack_notification(message: str, title: str = None, message_type: str = None): logger = setup_logger("slack") slack_config = load_slack_config() if slack_config is None: logger.info(f"Couldn’t load Slack config to send “{message}”") return url, message_dict = build_message(slack_config, message, title, message_type) slack = slackweb.Slack(url) try: slack.notify(**message_dict) except HTTPError: logger.info(f"Slack URL or channel name is incorrect.")
def get_ripple(): # slackのwebhookのURL slack = slackweb.Slack( url= 'https://hooks.slack.com/services/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' ) # coincheckのURL target_url = 'https://coincheck.com/ja/exchange' # phantomjsのpath # windowsの場合 phantomjs_path = '../node_modules/phantomjs/lib/phantom/bin/phantomjs' # macの場合 # phantomjs_path = '../node_modules/phantomjs/bin/phantomjs' try: # seleniumによりphantomjsを起動 browser = webdriver.PhantomJS(executable_path=phantomjs_path) # phantomjsでcoincheckにアクセス browser.get(target_url) # JavaScriptのレンダリング後のcoincheckのサイトのソースを取得 source = browser.page_source # 取得したhtmlをファイル出力 with open('coincheck.html', mode='w', encoding='utf-8') as f: f.write(source) # htmlを解析 soup = BeautifulSoup(source, 'lxml') # Rippleの値段をスクレイプ ripple = soup.find_all( class_=re.compile('currency_desc ng-binding'))[7].text # print(ripple) finally: # ブラウザを終了 browser.quit() message = '*Ripple Price*\n`' + ripple + '`' # markdownを使ってslackに通知 slack.notify(text=message, mrkdwn=True)
def send2app(text: str, slack_id: str, line_token: str, teams_token: str) -> None: # slack if slack_id is not None: slack = slackweb.Slack(url=slack_id) slack.notify(text=text) # line if line_token is not None: line_notify_api = 'https://notify-api.line.me/api/notify' headers = {'Authorization': f'Bearer {line_token}'} data = {'message': f'message: {text}'} requests.post(line_notify_api, headers=headers, data=data) # teams if teams_token is not None: myTeamsMessage = pymsteams.connectorcard(teams_token) myTeamsMessage.text(text) myTeamsMessage.send()
def __init__(self, access_token, slack_web_hook_url=None, twitter_keys=None): self.access_token = access_token self.resrvation_items = [] self.client = QiitaClient(access_token=access_token) self._get_all_items() print(f'all_items: {len(self.items)}') self.slack = None if slack_web_hook_url is not None: self.slack = slackweb.Slack(url=slack_web_hook_url) self.twitter = None if twitter_keys is not None: tw_auth = twitter.OAuth( consumer_key=twitter_keys['twitter_api_key'], consumer_secret=twitter_keys['api_secret_key'], token=twitter_keys['access_token'], token_secret=twitter_keys['access_token_secret']) self.twitter = twitter.Twitter(auth=tw_auth)
def handle_text_message(event): """ Text Message の処理 """ slack_info = slackweb.Slack(url=WEB_HOOK_LINKS) # トーク情報の取得 user_id, user_name, msg_type, room_id = get_event_info(event) # slack側に投稿するメッセージの加工 send_msg = "[bot-line] {user_name}さん\n".format(user_name=user_name) \ + "{msg}\n".format(msg=event.message.text) \ + "---\n" \ + "送信元: {msg_type} ( {room_id} )\n".format(msg_type=msg_type, room_id=room_id) \ + "送信者: {user_name} ( {user_id} )".format(user_name=user_name, user_id=user_id) # メッセージの送信 slack_info.notify(text=send_msg)