import argparse import datetime import logging import os import time import pytz from slacker import Slacker from alec import config from alec.api import BitfinexClientError from alec.api import bitfinex_v1_rest from alec.api import bitfinex_v2_rest slack = Slacker(config.SLACK_TOKEN) if config.SLACK_ENABLE else None logger = logging.getLogger(__name__) def timestamp_to_string(t): tz = pytz.timezone('Asia/Taipei') local_time = datetime.datetime.fromtimestamp(int(t), tz) return str(local_time.strftime('%Y-%m-%d %H:%M:%S')) def log(text): print(timestamp_to_string(time.time()) + '\t' + text) if slack: slack.chat.post_message(config.SLACK_CHANNEL, text)
from slacker import Slacker import random # 슬랙 토큰으로 객체 생성 token = '토큰 값' slack = Slacker(token) # 메시지 전송 (#채널명, 내용) slack.chat.post_message('#day4', 'Slacker 파일 업로드 테스트') #기온에 따른 옷 추천 def choose_clothes(temperature): photo_num = random.randrange(1, 11) photo_name = ".png" if (temperature > 23): photo_name = "summer" + str(photo_num) + photo_name elif (temperature > 10): photo_name = "middle" + str(photo_num) + photo_name else: photo_name = "winter" + str(photo_num) + photo_name slack.files.upload(photo_name, channels="#day4") # 파일 업로드 (파일 경로, 채널명) slack.files.upload('dog.png', channels="#day4") # 사용자 리스트 반환 response = slack.users.list() users = response.body['members']
def connect(self): self.client = Slacker(self.api_key) self.update_channels()
from datetime import datetime from datetime import timedelta from pyral import Rally from slacker import Slacker slack = Slacker('SLACKAPIKEY') # Send a message to #integration-testing channel server = "rally1.rallydev.com" #as we are using an API key, we can leave out the username and password user = "" password = "" workspace = "" project = "" apikey = "RALLYAPIKEY" #which slack channel does this post to? channel = "" #Assume this system runs (via cron) every 15 minutes. interval = 15 * 60 #format of the date strings as we get them from rally format = "%Y-%m-%dT%H:%M:%S.%fZ" #create the rally service wrapper rally = Rally(server, user,
import logging import requests from django.conf import settings from django.core.management.base import BaseCommand from slacker import Slacker from ...models import FundraisingStatus # https://github.com/oxguy3/patreon-api API_KEY = '1745177328c8a1d48100a9b14a1d38c1' DJANGOGIRLS_USER_ID = 483065 BASE_API_URL = 'http://api.patreon.com/' slack = Slacker(settings.SLACK_API_KEY) class Command(BaseCommand): help = 'Fetch current amount of money raised on our Patreon' def handle(self, *args, **options): logging.basicConfig(level=logging.INFO) logging.info("Trying to fetch data from Patreon...") url = "{}user/{}".format(BASE_API_URL, DJANGOGIRLS_USER_ID) request = requests.get(url) data = request.json() patron_count = data['linked'][0]['patron_count'] pledge_sum = int(int(data['linked'][0]['pledge_sum'])/100)
def __init__(self): self.token = settings.SLACK_KEY self.slack = Slacker(self.token)
def get_slacker(): global _slacker if _slacker is None: _slacker = Slacker(SLACK_TOKEN) return _slacker
from slacker import Slacker import vk_api import time slack = Slacker('Your token API Slack') login_vk = 'your login VK' pass_vk = 'your pass VK' group_id = '-1234567890' def main(): login, password = login_vk, pass_vk vk_session = vk_api.VkApi(login, password) try: vk_session.authorization() except vk_api.AuthorizationError as error_msg: print(error_msg) return vk = vk_session.get_api() while True: #запускаем цикл man_id = str( group_id) #id группы с которой будем брать посты и комментарии postidlist = vk.wall.get(owner_id=man_id, count=1, offset=0) #получаем последний пост a = str(postidlist['items'][0] ['id']) #получаем id поста в виде цифры и записываем time.sleep(5) #засыпаем на 5 секунд ts = 10
from slacker import Slacker import smartcommon SLACK_WEBHOOK_URL = 'https://hooks.slack.com/services/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' DMP_AZKABAN_CHANNEL = '#ad-dmp-azkaban' slack = Slacker('', incoming_webhook_url=SLACK_WEBHOOK_URL) logger = smartcommon.get_logger("smartnews.slack") def notify(text, channel=DMP_AZKABAN_CHANNEL, attachments=None): slack.incomingwebhook.post({ 'channel': channel, 'text': text, 'link_names': '1', 'attachments': attachments }) def print_df(df, channel="#ad-dmp-azkaban-dev", title="Untitled", author="df_reporter", color="good"): cols = list(df.columns.values) attachments = [] logger.info(df) for idx, row in df.iterrows(): fs = [] for col in cols:
import requests import codecs import slackbot_settings from slacker import Slacker slacker = Slacker(slackbot_settings.API_TOKEN) class DownloadFile: def __init__(self, file_types, save_directly): # 引数が省略された場合は、デフォルトのタイプを指定 self.file_types = file_types self.save_directly = save_directly def exe_download(self, file_info): file_name = file_info['name'] url_private = file_info['url_private_download'] # 保存対象のファイルかチェックする #if file_info['filetype'] in self.file_types: # ファイルをダウンロード self.file_download(url_private, self.save_directly + file_name) return 'ok' # else: # 保存対象外ファイル #return 'file type is not applicable.' def file_download(self, download_url, save_path): content = requests.get(download_url, allow_redirects=True, headers={ 'Authorization': 'Bearer %s' % slackbot_settings.API_TOKEN
def notify(title, message, token, recipient, retcode=None): slack = Slacker(token) slack.chat.post_message(recipient, message)
def __init__(self, channel=None, username=None): self.slack = Slacker(self.get_bot_user_oauth_token()) self.channel = channel self.username = username
from slackbot.bot import listen_to, respond_to from slacker import Slacker import slackbot_settings as conf from core.utils import get_track_image SLACK_MSG_DEFAULT_KWARGS = { 'as_user': False, 'username': conf.NAME.capitalize(), 'icon_url': 'https://avatars.slack-edge.com/2016-06-30/55979414291_73f334a62a9e2750436a_72.png', } spotify = spotipy.Spotify() slack = Slacker(conf.API_TOKEN) speaker = SoCo(conf.SPEAKER_IP) @listen_to('^help$', re.IGNORECASE) @respond_to('^help$', re.IGNORECASE) def help(message): """ Shows Robot Help. """ try: print('Got command help') message.reply('\n'.join(( ' :musical_note: :guitar: :robot_face: Hello! I\'m ' + conf.NAME + '. and i play cool', ' music on your Sonos speakers. Here\'s how I work: :rock:\n'
def __init__(self, token): self.__slacker = Slacker(token)
"--comment", ACK_URL, "-j", "DROP" ], stdout=subprocess.PIPE) output, err = p.communicate() def stop_ppp(): f = open('/var/run/' + args.ifname + '.pid') PID = f.read().split('\n') f.close() p = subprocess.Popen(["kill", "-9", PID[0]], stdout=subprocess.PIPE) output, err = p.communicate() ipt_add() slack = Slacker('<put here slack token>') slack.chat.post_message( '@' + args.username, '*<https://<Your url for ACK>:' + str(PORT) + ACK_URL + '|VPN ACK>*') class Handler(http.server.SimpleHTTPRequestHandler): def do_GET(self): try: if self.path == ACK_URL: self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(bytes('OK!\n', 'utf8')) ipt_del() else:
if svn_author == "": svn_author = "swkim" # 커밋 로그에 '#1234' 형식이 있는 경우 트랙 번호로 생각해서 변환해 준다. 공백으로 토큰을 구분하니 반드시 한칸을 띄어야 한다. trac_ticket_url = "" log_list = svn_log.split() for log_token in log_list: start_pos = log_token.find('#') if start_pos >= 0: log_token = log_token[start_pos + 1:len(log_token) - start_pos + 1] trac_ticket_url = "{0}{1}".format(trac_url, log_token.replace('#', "")) break #end if #end for slack = Slacker(bot_token) title_text = "{0}님이 {1}을 변경하였습니다.\n변경된 리비전은 {2}입니다.".format( commit_dict.get(svn_author, svn_author), product_dict.get(svn_path, svn_path), svn_rev) pretext = "{0} 제품이 변경되었습니다.".format(product_dict.get(svn_path, svn_path)) attachments_dict = dict() attachments_dict['pretext'] = pretext attachments_dict['title'] = title_text attachments_dict['fallback'] = pretext attachments_dict['text'] = svn_log attachments_dict['mrkdwn_in'] = ["text", "pretext"] if trac_ticket_url != "": new_pretext = "{0}\nTRAC : {1}".format(pretext, trac_ticket_url)
#coding: utf-8 import json import random from slacker import Slacker from crontab import CronTab from datetime import datetime, timedelta import logging import math from multiprocessing import Pool import time slackjson = open("slack.json").read() settings = json.loads(slackjson) slack = Slacker(settings['token']) members_m = settings['members_mention'] class JobConfig(object): def __init__(self, crontab): """ :type crontab: crontab.CronTab :param crontab: 実行時間設定 """ self._crontab = crontab def schedule(self): """ 次回実行日時を取得する。 :rtype: datetime.datetime
from ctapi import Alerter import dirapi import pymongo from threading import Thread import json client = pymongo.MongoClient("mongodb://*****:*****@app.route('/list-domains', methods=['POST']) def list(): if request.method == 'POST': domains = alerter.listDomains() slack.chat.post_message('#subdomain-alerts', "List of subscribed domains") for domain in domains: slack.chat.post_message('#subdomain-alerts', domain['domain']) return '', 200
train_labels_encoded = to_categorical(train_labels) test_labels_encoded = to_categorical(test_labels) train_images = train_images / 255 test_images = test_images / 255 n = int(len(test_images) / 2) X_valid, y_valid = test_images[:n], test_labels_encoded[:n] X_test, y_test = test_images[n:], test_labels_encoded[n:] slack_token_id = None filepath = 'config' with open(filepath) as fp: slack_token_id = fp.readline() slack = Slacker(slack_token_id) updater = SlackUpdate(channel=reporting_channel) cnn_model = model() cnn_model.save('my_model.h5') print(cnn_model.summary()) cnn_history = cnn_model.fit(x=train_images, y=train_labels_encoded, batch_size=32, epochs=2000, verbose=2, validation_split=0.0, validation_data=(X_valid, y_valid), shuffle=True, callbacks=[updater], class_weight=None,
def getChannelsMessage(token): slack = Slacker(token) testAuth = doTestAuth(slack) return getChannels(slack)
import json import datetime import time import random from collections import namedtuple from slacker import Slacker from flask import Flask, request app = Flask(__name__) curdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(curdir) slack = Slacker(os.getenv("TOKEN")) username = os.getenv("USERNAME", "StandupBot") icon_emoji = os.getenv("ICON_EMOJI", ":coffee:") channel = os.getenv("CHANNEL", "#standup") ignore_users = os.getenv("IGNORE_USERS", "") ignore_users = ignore_users.split(",") ignore_users = [usr.strip() for usr in ignore_users] init_greeting = os.getenv("INIT_GREETING", "Good morning!") start_message = os.getenv( "START_MESSAGE", "What did you work on yesterday? What are you working on today? What, if any, are your blockers?", ) giphy = os.getenv("GIPHY") == "true"
cfg = yaml.load(ymlfile) settings = cfg['settings'] tableau_username = settings['username'] tableau_password = settings['password'] tab_server_url = settings['url'] slack_token = settings['token'] #Step 1 - Login #encrypt your username and password # kms = boto3.client('kms') # keyid = "arn:aws:kms:yourkmskey" # username_encrypt = kms.encrypt(KeyId=keyid,Plaintext=tableau_username) # cipher = username_encrypt.get('CiphertextBlob') # username_decrypt = kms.decrypt(CiphertextBlob=cipher) slack = Slacker(slack_token) def _encode_for_display(text): """ Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholders (for example, "?"). """ return text.encode('ascii', errors="backslashreplace").decode('utf-8') # Establish a session so we can retain the cookies session = requests.Session()
def slack_message(msg, key): client = Slacker(key) resp = client.chat.post_message("#zoneminder", msg, as_user=True) print(resp)
if INTERACT: import code code.interact(local=locals()) sys.exit() run_num = orca.get_injectable("run_number") if LOGS: print '***The Standard stream is being written to /runs/run{0}.log***'\ .format(run_num) sys.stdout = sys.stderr = open("runs/run%d.log" % run_num, 'w') if SLACK: from slacker import Slacker slack = Slacker(os.environ["SLACK_TOKEN"]) host = socket.gethostname() def get_simulation_models(SCENARIO): models = [ "neighborhood_vars", # local accessibility vars "regional_vars", # regional accessibility vars "rsh_simulate", # residential sales hedonic "nrh_simulate", # non-residential rent hedonic "households_relocation", "households_transition", "jobs_relocation", "jobs_transition", "price_vars",
default=False, help="skip fetching history for private channels") parser.add_argument('--skipChannels', action='store_true', default=False, help="skip fetching history for channels") parser.add_argument('--skipDirectMessages', action='store_true', default=False, help="skip fetching history for directMessages") args = parser.parse_args() slack = Slacker(args.token) testAuth = doTestAuth(slack) userIdNameMap = getUserMap(slack) dryRun = args.dryRun if not dryRun: with open('metadata.json', 'w') as outFile: print("writing metadata") metadata = {'auth_info': testAuth, 'users': userIdNameMap} json.dump(metadata, outFile, indent=4) if not args.skipChannels: getChannels(slack, dryRun)
action='count', help='Do nothing (for test purpose)') args = parser.parse_args() if args.verbose != None: print("Using args:", args) # Parse the configuration file if args.verbose != None: print("Parsing configuration file:", args.file) config = configparser.ConfigParser() config.read(args.file) # Open the connection to Slack if args.verbose != None: print("Opening Slack connection") slack = Slacker(config['DEFAULT']['SlackTocken']) # Iterate over all sections in the config file for sectionName in config.sections(): section = config[sectionName] eraserType = section.get('Type') searchRequest = section.get('Request', "") searchFrom = section.get('From') if searchFrom != None and " " not in searchFrom: searchRequest += " from:" + searchFrom searchIn = section.get('In') if searchIn != None: searchRequest += " in:" + searchIn searchSort = section.get('Sort', "timestamp") searchOrder = section.get('Order', "desc")
except Exception as ex: # Quietly fail, and try again if attempt < 2: output("Upload failed... trying again") else: # Throw loud exception raise ex return url try: # Validate command-line arguments if len(sys.argv) >= 2: slack_token = sys.argv[1] slack_object = Slacker(slack_token) if len(sys.argv) >= 4: s3_access_key = sys.argv[2] s3_secret_key = sys.argv[3] s3_connection = tinys3.Connection(s3_access_key, s3_secret_key, tls=True) if len(sys.argv) >= 6: windows_key = sys.argv[4] windows_key_password = sys.argv[5] if len(sys.argv) >= 8: github_user = sys.argv[6] github_pass = sys.argv[7] # Login and get "GitHub" object gh = login(github_user, github_pass) repo = gh.repository("OpenShot", "openshot-qt")
import datetime import time from slacker import Slacker SLACK = Slacker('<enter API key here>') quotes = { 'Groucho Marx': [ 'A likely story — and probably true.', "Although it is generally known, I think it's about time to announce that I was born at a very early age.", "I sent the club a wire stating, 'PLEASE ACCEPT MY RESIGNATION. I DON'T WANT TO BELONG TO ANY CLUB THAT WILL ACCEPT PEOPLE LIKE ME AS A MEMBER'", "I never forget a face, but in your case I'll be glad to make an exception.", "From the moment I picked your book up until I laid it down I was convulsed with laughter. Someday I intend on reading it.", 'I find television very educational. Every time someone switches it on I go into another room and read a good book.', "Die, my dear? Why that's the last thing I'll do!" ], 'Winston Churchill': [ 'I may be drunk, Miss, but in the morning I will be sober and you will still be ugly.', 'Courage is what it takes to stand up and speak; courage is also what it takes to sit down and listen.', 'Success is not final, failure is not fatal: it is the courage to continue that counts.', 'To improve is to change; to be perfect is to change often.', 'Attitude is a little thing that makes a big difference.' ], 'Mark Twain': [ "If you tell the truth, you don't have to remember anything.", "Good friends, good books, and a sleepy conscience: this is the ideal life", "The man who does not read has no advantage over the man who cannot read.", "Never put off till tomorrow what may be done day after tomorrow just as well.", "I have never let my schooling interfere with my education.", "′Classic′ - a book which people praise and don't read.",
import os, sys, ctypes import win32com.client import pandas as pd from datetime import datetime from slacker import Slacker import time, calendar from bs4 import BeautifulSoup from urllib.request import urlopen from selenium import webdriver from selenium.webdriver.chrome.options import Options slack = Slacker('xoxb-1980562838979-1973585432390-HJsNIOSStBhDUtDCCIy5B8XO') def dbgout(message): """인자로 받은 문자열을 파이썬 셸과 슬랙으로 동시에 출력한다.""" print(datetime.now().strftime('[%m/%d %H:%M:%S]'), message) strbuf = datetime.now().strftime('[%m/%d %H:%M:%S] ') + message slack.chat.post_message('#stock', strbuf) def printlog(message, *args): """인자로 받은 문자열을 파이썬 셸에 출력한다.""" print(datetime.now().strftime('[%m/%d %H:%M:%S]'), message, *args) # 크레온 플러스 공통 OBJECT cpCodeMgr = win32com.client.Dispatch('CpUtil.CpStockCode') cpStatus = win32com.client.Dispatch('CpUtil.CpCybos') cpTradeUtil = win32com.client.Dispatch('CpTrade.CpTdUtil') cpStock = win32com.client.Dispatch('DsCbo1.StockMst')
import time import urllib from collections import defaultdict from slacker import Slacker datestr = '%m/%d/%Y-%H:%M:%S' table_vote_options = 'vote-options' table_vote_open = 'vote-open' delimiter = ',' with open(os.path.join(os.path.dirname(__file__), 'SLACK_BOT_API_TOKEN')) as f: bot_api_token = f.read().strip() with open(os.path.join(os.path.dirname(__file__), 'SLACK_CHANNEL_TOKEN')) as f: incoming_token = f.read().strip() slack = Slacker(bot_api_token) ddb = boto3.resource('dynamodb', region_name='us-west-2') def _formparams_to_dict(s1): """ Converts the incoming formparams from Slack into a dictionary. Ex: 'text=votebot+ping' """ retval = {} for val in s1.split('&'): k, v = val.split('=') retval[k] = v return retval def lambda_handler(event, context): """ This is the function Lambda will call. Supported commands: - ping: Immediately responds back with a 'pong' message.