def __init__(self, default_channel, api_token): from slacker import Slacker self._default_channel = default_channel self._api_token = api_token self.slack = Slacker(self._api_token) self.slack.auth.test()
from slacker import Slacker from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody, FileAttachment # Assign credentials for email account. Include '@uvic.ca' in username and smtp address creds = Credentials(username = '******',password = '******') a = Account(primary_smtp_address='SAME EMAIL ABOVE',credentials=creds,autodiscover = True, access_type = DELEGATE) onc = ONC("USER_ONC_TOKEN") slackToken = 'ONC_Data_SlackApp_Token ' slackToken_ONC = 'ONC_Main_SlackApp_Token ' slack_client = Slacker(slackToken) slack_client_ONC = Slacker(slackToken_ONC) os.makedirs("_Maps", exist_ok = True) # Get the main directory of the application curdir = os.getcwd() # Get the most recent log in EventMaintenance url='EventMaintenanceMostRecent_url" response = requests.get(url) data = response.json() # Unpack the HTML. Get relevant time stamps
logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) config = Config() """ Base configuration """ env.user = app_config.SERVER_USER env.forward_agent = True env.hosts = [] env.settings = None slack = Slacker(app_config.SLACK_KEY) SECONDS_BETWEEN_CHECKS = 1 * 60 * 60 # 1 hour MAX_SECONDS_SINCE_POSTING = 3 * 24 * 60 * 60 # 2 days """ MINUTES_BETWEEN_CHECKS = 15 MINUTES_BETWEEN_REPORTS = [ 240, # 4 hours 480 # 8 hours ] """ """ Configuration """
def slack(): slackClient = Slacker(SLACK_TOKEN) slackClient.chat.post_message(SLACK_CHANNEL, cot)
import time import json from slacker import Slacker with open('var/secrets.json') as secrets_file: secrets = json.load(secrets_file) EMAIL_ACCOUNT = secrets['EMAIL_ACCOUNT'] # Use 'INBOX' to read inbox. Note that whatever folder is specified, # after successfully running this script all emails in that folder # will be marked as read. EMAIL_FOLDER = secrets['EMAIL_FOLDER'] EMAIL_PASSWORD = secrets['EMAIL_PASSWORD'] SLACK_TOKEN = secrets['SLACK_TOKEN'] SLACK_CHANNEL = secrets['SLACK_CHANNEL'] slack = Slacker(SLACK_TOKEN) def process_mailbox(M): """ Do something with emails messages in the folder. For the sake of this example, print some headers. """ rv, data = M.search(None, "ALL") if rv != 'OK': print("No messages found!") return for num in data[0].split(): rv, data = M.fetch(num, '(RFC822)')
def __init__(self, token: str, channel_name: str, root_directory=None): super().__init__(root_directory) self._client = Slacker(token) self.channel_name = channel_name self._domain = None
def __init__(self): self.__slacker = Slacker(BotConfig.token()) print(BotConfig.token())
def __init__(self, slack_token, get_archived_channels=True): # type: (str, bool) -> None self.slack = Slacker(slack_token) self.get_archived_channels = get_archived_channels self._check_slack_token()
def __init__(self, token, channel, suffix='%'): self.suffix = suffix self.channel = channel self.slack = Slacker(token)
def send_slack_message(token, channel, messge): token = token slack = Slacker(token) slack.chat.post_message(channel, messge)
#!/usr/bin/env python3 from subprocess import getoutput from slacker import Slacker # slack API トークン slack_api_token = "xoxp-XXX" # slack で投稿先のチャンネル名 slack_channel_name = "seminar_raspi-testspace" MESSAGE_1 = "メッセージ送信てすと" # SlackAPIを使ってメッセージをslackに投稿する print("Sending message..") slacker = Slacker(slack_api_token) channel_name = "#" + slack_channel_name slacker.chat.post_message(channel_name, MESSAGE_1) print("Done! Check slack channel")
from summarizer import textrank from flask import Flask, jsonify, request import requests from slacker import Slacker import json import os from config import * print "after import" #slack = Slacker(keys["slack"]) slack = Slacker("xoxp-230558855988-230558856164-231615460626-1753fc61f518e3c7c411b67df46fed8f") print "Slacker interfaced" app = Flask(__name__) print "Flask instance created" @app.route("/slack", methods=['POST']) def slackReq(): print "handling slack request to main" #slack.chat.post_message('#general', 'Hello fellow slackers!') req_data = request.form print "obtained request data" channel_id = req_data.getlist('channel_id') print "Get channel id" print "Get channel id 2" print "Get channel id 3" response = slack.channels.history(channel_id) print "get convo log" a = (response.body) para = "" concepts = "" for i in range(len(a['messages']) - 1, -1, -1):
import re import sys import traceback import json import datetime import time import random 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.environ['TOKEN']) username = os.environ['USERNAME'] if 'USERNAME' in os.environ.keys( ) else 'morgenbot' icon_emoji = os.environ['ICON_EMOJI'] if 'ICON_EMOJI' in os.environ.keys( ) else ':coffee:' channel = os.environ['CHANNEL'] if 'CHANNEL' in os.environ.keys( ) else '#standup' ignore_users = os.environ['IGNORE_USERS'] if 'IGNORE_USERS' in os.environ.keys( ) else '' giphy = True if 'GIPHY' in os.environ.keys() and os.environ['GIPHY'].lower( ) == 'true' else False commands = [ 'standup', 'start', 'cancel', 'next', 'skip', 'table', 'left', 'ignore', 'heed', 'ignoring', 'help' ]
def respond_contest_func(message): channel = "test" # slack api token 設定 slack = Slacker(slackbot_settings.API_TOKEN) info(channel, slack)
def __init__(self, token): self.token = token self.client = Slacker(token) self.users = []
def __init__(self, token_path=None, channel=None): self.token_path = token_path self.channel = channel self.slacker = Slacker(self._get_token(self.token_path))
import umsgpack import sys, os import datetime try: import configparser except ImportError: import ConfigParser as configparser config_path = os.getenv('HOME') + '/.changelog_to_slack.ini' user_data_dir = os.getenv('HOME') + '/.changelog_to_slack' config = configparser.ConfigParser() config.read(config_path) slack_token = config.get("slack", "slack_token") slack = Slacker(slack_token) slack_channel = config.get("slack", 'channel') database = os.path.join(user_data_dir, 'changelog_to_slack.bin') def get(url): """Get request object :param url: url where we can get information :return: request object or False if any errors """ try: r = requests.get(url) except requests.exceptions: return False if r.status_code == 200:
class MarketDB: def __init__(self): self.conn = pymysql.connect(host='localhost',user='******',password='******',db='meeseeks',charset='utf8') self.codes = {} self.get_buy_list() def __del__(self): self.conn.close() def get_buy_list(self): dayCheck = datetime.today().strftime('%Y-%m-%d') sql = f"SELECT * FROM buy_list WHERE date = '{dayCheck}'" buyList = pd.read_sql(sql, self.conn) return buyList #['A028300', 'A007570'] slack = Slacker('xoxb-1398877919094-1406719016898-vSj7JEDRgOSEeK6MTDOygRng') 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('#meeseeks-bot', strbuf) logger.info(strbuf) def printlog(message, *args): """인자로 받은 문자열을 파이썬 셸에 출력한다.""" print(datetime.now().strftime('[%m/%d %H:%M:%S]'), message, *args) msg = datetime.now().strftime('[%m/%d %H:%M:%S] ') + message + str(*args) logger.info(msg) # 크레온 플러스 공통 OBJECT cpCodeMgr = win32com.client.Dispatch('CpUtil.CpStockCode')
import os, sys, ctypes import win32com.client import pandas as pd from datetime import datetime from slacker import Slacker import time, calendar # slack Oauth 코드 불러오기 시작 f = open("slack.txt", 'r') slackoauth = f.readline() f.close() # slack Oauth 코드 불러오기 끝 slack = Slacker(slackoauth) 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')
#import logging #import time #import requests import urllib.request import yaml configdir = "/config" #configdir = "x:\\hass-config" with open('{}/secrets.yaml'.format(configdir), 'r') as sf: secrets = yaml.load(sf) slack_cams_api_key = secrets["slack_cams_api_key"] if len(sys.argv) > 1: #set variables slack = Slacker(slack_cams_api_key) cam = str(sys.argv[1]) #filename = ("C:\\temp\\{}.jpg").format(cam) filename = ("{}/shell_command_scripts/{}.jpg").format(configdir, cam) if cam == "garagecam": user = secrets["bi_garagecam_user"] pw = secrets["bi_garagecam_pass"] garagecam_url = secrets["bi_garagecam_url"] url = "{}/CGIProxy.fcgi?cmd=snapPicture2&usr={}&pwd={}".format( garagecam_url, user, pw) elif cam == "jackcam": url = "" elif cam == "ryancam": url = "" else:
def slacking(attachments): slack = Slacker(os.environ['SLACK_TOKEN']) slack.chat.post_message(channel=os.environ['SLACK_CHANNEL'], text='', as_user=True, attachments=attachments)
def get_slacker(): global _slacker if _slacker is None: _slacker = Slacker(SLACK_TOKEN) return _slacker
import json import web from slacker import Slacker slack = Slacker('<slack-key>') urls = ('/.*', 'hooks') app = web.application(urls, globals()) class hooks: def POST(self): data = web.data() print print 'DATA RECEIVED:' print data print obj = json.loads(data) if obj["action"] == "opened": if obj["repository"]["full_name"] == "TodoPago/SDK-PHP": channel = "#todopago-sdk-php" if obj["repository"]["full_name"] == "TodoPago/SDK-Python": channel = "#todopago-sdk-python" if obj["repository"]["full_name"] == "TodoPago/SDK-Java": channel = "#todopago-sdk-java" if obj["repository"]["full_name"] == "TodoPago/SDK-Node.js": channel = "#todopago-sdk-nodejs" if obj["repository"]["full_name"] == "TodoPago/SDK-Ruby": channel = "#todopago-sdk-ruby" if obj["repository"]["full_name"] == "TodoPago/SDK-.NET":
# -*- coding: utf-8 -*- from slackbot.bot import Bot from slacker import Slacker import slackbot_settings def main(): bot = Bot() bot.run() if __name__ == "__main__": slack = Slacker(slackbot_settings.API_TOKEN) slack.chat.post_message( '**********', #channel '**********', #message username='******', #name of bot icon_emoji='********' #name of icon ) main()
#!/usr/bin/python # # # Author: Stephen J. Hilt # Purpose: To read RSS feeds and post to a given slack channel # # import feedparser from slacker import Slacker import time #Setup to pull RSS feed example is ICS-CERT Alerts rss =feedparser.parse('https://ics-cert.us-cert.gov/alerts/alerts.xml') #setup slack via Slacker slack = Slacker('YOUR_API_KEY') # create current time based off RSS feeds format # the minus -4 is for an offset of GMT to East Cost minus an hour since i'm running this # as a cron job every how, so this will pull everything from the past hour day = time.strftime("%d") month = time.strftime("%b") year = time.strftime("%Y") hour = time.strftime("%H") if int(time.strftime("%H"))+4 < 23: date_time = ", {:02d} {} {} {:02d}:".format(int(day), month, year, int(hour) + 4) else: hour = abs(24 - (int(hour) + 4)) date_time = ", {:02d} {} {} {:02d}:".format(int(day)+1, month, year, int(hour)) count = 0 # set a counter to 0 to loop through all the RSS feed entries
def connect(self): self.client = Slacker(self.api_key) self.update_channels()
#note, you'll need to be running python2 (built with 2.7, python DOES NOT WORK ) #you'll need to pip install pyral (the python-rally connector) as slacker (the slack connector) # sudo pip install slacker # source: MartinCron https://github.com/MartinCron/rally_slack_integration/blob/master/rallyslack.py#L1 # from datetime import datetime from datetime import timedelta from pyral import Rally from slacker import Slacker slack = Slacker('enter slack token here') # 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 ID for NaviSite workspace="NaviSite Workspace" # project ID for Team Systems Team for Systems and Teams project="Team Systems Team for Systems and Teams" # API key for tandre 1/13/2017 #cmoore-hackathon-moes
from selenium import webdriver from slacker import Slacker #send a messate slack slack = Slacker('your bot token start with xoxb-') import datetime #add time info f = open('new_lists.txt','w') myoptions = webdriver.ChromeOptions() myoptions.add_argument('--incognito') myoptions.add_argument('--disable-gpu') myoptions.add_argument("--start-maximized") myoptions.add_argument("--no-sandbox") myoptions.add_argument('window-size=1920x1080') #for headless mode myoptions.add_argument('headless') #for headless mode driver = webdriver.Chrome('your chromedirver location', options=myoptions) #add parmeter options=[webdriver chrome options] dt = datetime.datetime.now() #add time info try: driver.get('https://ridibooks.com/category/new-releases/3000?order=recent') #crawling lite novel new-release page using h3 tag lists = driver.find_elements_by_tag_name('h3') f.write(dt.strftime("%A %d. %B %Y")) #add time info for novel in lists: head = novel.text print(head) f.write(head+'\n') f.close() r = open('new_lists.txt','r') title = r.read() slack.chat.post_message('#[your slack channel]', title) r.close() except Exception as e: print(e) f.close() finally:
import os import time import re from slackclient import SlackClient from slacker import Slacker import websocket token = '' slack = Slacker(token) slack.chat.post_message('#study-tensorflow', 'test message for new channel') # instantiate Slack client # slack_client = SlackClient('xoxb-470902892800-471037595441-Ym2bPtmNOnd6CJCgE9gsufzv') # # starterbot's user ID in Slack: value is assigned after the bot starts up # starterbot_id = None # # # constants # RTM_READ_DELAY = 1 # 1 second delay between reading from RTM # EXAMPLE_COMMAND = "do" # MENTION_REGEX = "^<@(|[WU].+?)>(.*)"
from coin_util import * from logger import logger dirname = os.path.dirname(__file__) # access key 가져오기 with open(os.path.join(dirname, '../../file/upbit_aces_key.txt'), 'r') as file: access_key = file.read().rstrip('\n') # security key 가져오기 with open(os.path.join(dirname, '../../file/upbit_sec_key.txt'), 'r') as file: secret_key = file.read().rstrip('\n') # slack_key 가져오기 with open(os.path.join(dirname, '../../file/slack_key.txt'), 'r') as file: slack_key = file.read().rstrip('\n') slack = Slacker(slack_key) 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('#python-trading-bot', strbuf) def printlog(message, *args): """인자로 받은 문자열을 파이썬 셸에 출력한다.""" tmp_msg = message for text in args: tmp_msg += str(text) logger.info(tmp_msg) #print(datetime.now().strftime('[%m/%d %H:%M:%S]'), message, *args)