Example #1
0
 def __init__(self, token: str = SLACK_TOKEN):
     self.sc = SlackClient(token)
Example #2
0
## dotd_summary contains the book summary ##
print(dotd_summary)

dotd_image = soup.find('div', {'class': 'dotd-main-book-image'})
im = dotd_image.find('img')['src']
dotd_image = 'http:' + im
dotd_image = re.sub(" ", "%20", dotd_image)
print(dotd_image)

## dotd_image contains the url for image ##

#sending slack notification

channel = 'packt-tracer'
token = key.token
sc = SlackClient(token)

image_url = dotd_image
attachments = attachments = [{"title": dotd_title, "image_url": image_url}]
date = str(strftime("%A, %d %b %Y"))
date = "[{}] {}".format(date, dotd_title)
link = "Click to download: " + url
message = date + '\n\n' + dotd_summary + '\n' + link

sc.api_call('chat.postMessage',
            channel=channel,
            text=message,
            username='******',
            icon_emoji=':robot_face:',
            attachments=attachments)
#!/usr/bin/env python
import time, os, sys
from slackclient import SlackClient

botToken = os.getenv('SLACK_TOKEN')
botUsername = os.getenv('SLACK_BOT')
botChannel = os.getenv('SLACK_CHANNEL')

if len(sys.argv) > 1:
    msg = sys.argv[1]
else:
    msg = "Test Message - Hello World"

if not botToken:
    print("A slack token is required using ENV of SLACK_TOKEN")
    sys.exit(1)

if not botUsername:
    botUsername = "******"
    asUser = True
else:
    asUser = False

if not botChannel:
    botChannel = "#general"

sc = SlackClient(botToken)

print(sc.api_call("chat.postMessage", channel=botChannel, username=botUsername, as_user=asUser, text=msg))
Example #4
0
import os
from dotenv import load_dotenv, find_dotenv
from slackclient import SlackClient

load_dotenv(find_dotenv())

BOT_NAME = "pythonworldcupbot"

slack_client = SlackClient(os.getenv('SLACK_BOT_TOKEN'))

if __name__ == "__main__":
    api_call = slack_client.api_call("users.list")
    if api_call.get('ok'):
        # retrieve all users so we can find our bot
        users = api_call.get('members')
        for user in users:
            if 'name' in user and user.get('name') == BOT_NAME:
                print("Bot ID for '" + user['name'] + "' is " + user.get('id'))
    else:
        print("API Call failed")
import os
import time
import re
from slackclient import SlackClient

# instantiate Slack client
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
# 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].+?)>(.*)"


def parse_bot_commands(slack_events):
    """
        Parses a list of events coming from the Slack RTM API to find bot commands.
        If a bot command is found, this function returns a tuple of command, channel, event 
	time stamp, and the user who called the command.
        If its not found, then this function returns None, None.
    """
    for event in slack_events:
        if event["type"] == "message" and not "subtype" in event:
            user_id, message = parse_direct_mention(event["text"])
            if user_id == starterbot_id:
                return message, event["channel"], event["event_ts"], event[
                    "user"]
    return None, None, None, None
Example #6
0
 def __init__(self):
     self._token = os.environ.get('SLACK_TOKEN', None)
     self._sc = SlackClient(self._token)
Example #7
0
    filelist = sc.api_call("files.list", token=tok)
    if filelist.get('ok'):
        count = filelist.get('paging').get('total')
        print "got", count, "files"
        filelist = sc.api_call("files.list", token=tok, count=count)

        return filelist.get('files')
    else:
        print "Cannot get file list"


def rm_file(sc, tok, file):
    file_id = file.get('id')
    result = sc.api_call("files.delete", token=tok, file=file_id)

    if result.get('ok') == False:
        print "ERROR removing " + file.get('name')
        print result


if __name__ == "__main__":
    slack_token = slacktoken.get_token()
    sc = SlackClient(slack_token)

    filelist = get_files(sc, slack_token, USER)

    for f in filelist:
        if f.get('size') > 2 * 1024 * 1024:
            print f.get('name'), " ", f.get('size')
            rm_file(sc, slack_token, f)
Example #8
0
def invite_to_slack(email):
    if settings.DEBUG:
        return {}
    sc = SlackClient(settings.SLACK_TOKEN)
    response = sc.api_call('users.admin.invite', email=email)
    return response
Example #9
0
"""
import os
import time
import json
import requests
import sqlite3

from Huscii import Huscii
from HusciiQuest import HusciiQuest
# from Huscii import id
from slackclient import SlackClient

# get the keys off the key chain
keys = Huscii()
BOT_ID = keys.id
slack_client = SlackClient(keys.key)

# connect to database
con = sqlite3.connect("husciidata.db")
cur = con.cursor()

# constants
AT_BOT = "<@" + BOT_ID + ">"
EXAMPLE_COMMAND = "do"

hq = HusciiQuest();

responses = {"dojo" : "Dojo is at Expedia in Bellevue every Friday 4:30-6:00 pm. The classes we have are Python, CodeCamp, Hour of Code, and Scratch.", \
            "facebook" : "Join us on Facebook @ https://www.facebook.com/groups/UWTProgrammingClub/", \
            "dawgden" : "Join us on Dawgden @ https://dawgden.tacoma.uw.edu/organization/HuSCII"}
Example #10
0
def handle(alert,
           recipient_email=None,
           channel=None,
           template=None,
           message=None):
    if 'SLACK_API_TOKEN' not in os.environ:
        log.info(f"No SLACK_API_TOKEN in env, skipping handler.")
        return None

    slack_token = vault.decrypt_if_encrypted(os.environ['SLACK_API_TOKEN'])

    sc = SlackClient(slack_token)

    # otherwise we will retrieve email from assignee and use it to identify Slack user
    # Slack user id will be assigned as a channel

    title = alert['TITLE']

    if recipient_email is not None:
        result = sc.api_call("users.lookupByEmail", email=recipient_email)

        # log.info(f'Slack user info for {email}', result)

        if result['ok'] is True and 'error' not in result:
            user = result['user']
            userid = user['id']
        else:
            log.error(
                f'Cannot identify  Slack user for email {recipient_email}')
            return None

    # check if channel exists, if yes notification will be delivered to the channel
    if channel is not None:
        log.info(f'Creating new SLACK message for {title} in channel', channel)
    else:
        if recipient_email is not None:
            channel = userid
            log.info(
                f'Creating new SLACK message for {title} for user {recipient_email}'
            )
        else:
            log.error(f'Cannot identify assignee email')
            return None

    blocks = None
    attachments = None
    text = title

    if template is not None:
        properties = {'channel': channel, 'message': message}

        # create Slack message structure in Snowflake javascript UDF
        try:
            payload = message_template(locals())
        except Exception:
            return None

        if payload is not None:
            if 'blocks' in payload:
                blocks = json.dumps(payload['blocks'])

            if 'attachments' in payload:
                attachments = json.dumps(payload['attachments'])

            if 'text' in payload:
                text = payload['text']
        else:
            log.error(f'Payload is empty for template {template}')
            return None
    else:
        # does not have template, will send just simple message
        if message is not None:
            text = message

    response = sc.api_call("chat.postMessage",
                           channel=channel,
                           text=text,
                           blocks=blocks,
                           attachments=attachments)

    log.debug(f'Slack response', response)

    if response['ok'] is False:
        log.error(f"Slack handler error", response['error'])
        return None

    if 'message' in response:
        del response['message']

    return response
Example #11
0
import sys
import os
import time
import auth_keys
import spotipy
import spotipy.util as util

from slackclient import SlackClient

#init slack
slack_client = SlackClient(auth_keys.SLACK_BOT_TOKEN)
status_emoji = ":musical_note:"

#init spotify
scope = 'user-read-currently-playing'
client_id = auth_keys.SPOTIPY_CLIENT_ID
client_secret = auth_keys.SPOTIPY_CLIENT_SECRET
redirect_url = auth_keys.SPOTIPY_REDIRECT_URL
username = auth_keys.SPOTIFY_USERNAME
token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_url)

poll_interval = 20
clear_status = '{"status_text":"","status_emoji":""}'

"""
todo: 
- add proper error handling
- allow spotify to refresh tokens
"""
def main():
	last_id = 0
Example #12
0
    DATABASE=os.path.join(app.root_path, 'workit.db'),
    SECRET_KEY='development key',
    USERNAME='******',
    PASSWORD='******'
))
DB_ADDRESS = os.path.join(app.root_path, 'workit.db')

#Dynamically setting the PORT
port = int(os.getenv('PORT', '5000'))

#CONSTANTS
app_token = "MP6bV33AHeBEFxDdUBjaoBsG"
bot_token = os.environ["bot_token"]
config = oauth2_config((["users:read", "channels:history", "channels:read", "channels:write", "chat:write:bot",
"incoming-webhook", "commands", "bot"]), "107526814087.107515751334", "b8b2779318baa62d6e71dd9e2f07e247", "https://workit-py.scapp.io/authenticate")
sc = SlackClient(bot_token)

#DB_UTILS
def connect_db():
    with app.app_context():
        rv = sqlite3.connect(DB_ADDRESS)
        rv.row_factory = sqlite3.Row
        return rv

def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
Example #13
0
 def __init__(self, slack_token):
     """Requires the slack bot oauth token"""
     self._slack = SlackClient(slack_token)
Example #14
0
load_dotenv(find_dotenv())


SLACK_BOT_TOKEN = os.getenv("SLACK_BOT_TOKEN")
SLACK_BOT_ID = os.getenv("SLACK_BOT_ID")

# constants
AT_BOT = f'<@{SLACK_BOT_ID}>'
BOT_COMMAND = "subscribe"
TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.getenv("TWILIO_AUTH_TOKEN")
# instantiate Twilio Client
CLIENT = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
# instantiate Slack Client
SLACK_CLIENT = SlackClient(SLACK_BOT_TOKEN)

def add_subscriber(phone_number: str):
    """
    Calls endpoint to add subscriber to SMS updates.
    If successful, returns success message. Returns error message otherwise.
    :param phone_number:
    :return:  str: text message
    """
    response = requests.post("http://localhost:5000/subscribe",
                             json={"number": phone_number})

    return response.json()["message"]


def handle_command(command: str, channel: str):
Example #15
0
# coding: utf-8

import os
import sys
import time
import datetime
from slackclient import SlackClient

kmcToken = os.environ["KMCtk"]
kc3Token = os.environ["KC3tk"]

kmcSC = SlackClient(kmcToken)
kc3SC = SlackClient(kc3Token)


def postKMC(msg, channel="C29T0SANS"):
    kmcSC.api_call("chat.postMessage",
                   channel=channel,
                   text=msg,
                   icon_emoji=":mawarunos:",
                   username="******")


def tunnelToKMC(rtm):
    try:
        postKMC(escapeAtchannel(rtm["text"]))
    except:  # 一回だけリトライ
        time.sleep(5)
        postKMC(escapeAtchannel(rtm["text"]))

#!/usr/bin/python
#
# @author: Eric Anderson ([email protected])
#
# https://slackapi.github.io/python-slackclient

import sys
import yaml
from slackclient import SlackClient

slack_config_file = '/etc/zabbix/slack.yml'

with open(slack_config_file, 'r') as ymlfile:
    slack_config = yaml.load(ymlfile)

slack = SlackClient(slack_config['slack_api_token'])

channel = sys.argv[1]
message = "```Status: %s\n%s```" % (sys.argv[2], sys.argv[3])

response = send_slack_message(channel, message)

if response["ok"]:
    print("Message posted successfully: " + response["message"]["ts"])
    # If the message failed, check for rate limit headers in the response
elif response["ok"] is False and response["headers"]["Retry-After"]:
    # The `Retry-After` header will tell you how long to wait before retrying
    delay = int(response["headers"]["Retry-After"])
    print("Rate limited. Retrying in " + str(delay) + " seconds")
    time.sleep(delay)
    slack.api_call("chat.postMessage", channel=channel, text=message)
Example #17
0
if output_error_file != "":
    logging_config['handlers']['file_error'] = {
        'class': 'logging.handlers.RotatingFileHandler',
        'level': 'ERROR',
        'formatter': 'f',
        'filename': output_error_file,
        'mode': 'a',
        'maxBytes': 10485760,
        'backupCount': 5,
    }
    logging_config['root']['handlers'].append('file_error')

dictConfig(logging_config)
logger = logging.getLogger('SAMbot')
slack_client = SlackClient(token)
logger.info("Slack client created")
logger.info("Connecting to misp server")
misp = misp_custom(data['misp']['url'], data['misp']['key'],
                   data['misp']['ssl'])
logger.info("Connected to misp server successfully")
helperFunc = helper.TonyTheHelper(slack_client)
# 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 = "Tell a joke"
MENTION_REGEX = "^<@(|[WU].+?)>(.*)"

Example #18
0
__author__ = '*****@*****.**'

import pingdomlib
import fabric
from paramiko import ssh_exception
import urllib
import sys
import time
from invoke import UnexpectedExit
from slackclient import SlackClient

# slack creds
st1 = "st1"
st2 = "st2"
st = st1 + st2
sc = SlackClient(st)

# pingdom creds
api = pingdomlib.Pingdom('user',
                         'key', 'secret')
# servers runnning apache
hosta = 'a.example.com'
hostb = 'b.example.com'

# virtual ip
ip = 'ip'

# ssh user for fabric.Connection
user = '******'

# site we're monitoring via pingdom
Example #19
0
# Create the ADC object using the I2C bus
ads = ADS.ADS1015(i2c)

# Create single-ended input on channel 0
# photoreceptor_channel = 0
photod = AnalogIn(ads, ADS.P0)

# P_drug_times = [2/1.4]
# P_nut_times = [2/1.6]
# P_waste_times = [2/1.6]
P_drug_times = 1.25
P_nut_times = 1.25
P_waste_times = 1.25

# Set Up Reporting for Slack
slack_client = SlackClient(
    "xoxb-15598920096-507190138311-pIsmBndOCk1YsVbflP5qXnnT")

user_list = slack_client.api_call("users.list")

for user in user_list.get('members'):
    if user.get('name') == "blob":
        slack_user_id = user.get('id')
        break

if slack_client.rtm_connect():
    print("Connected!")

#Report on RAM usage every half hour


class Morbidostat():
Example #20
0
timeoutResponse5="Hey.. me again.  You haven't checked Slack all day.  Please reply to the survey as soon as you get a chance"
timeoutResponse6="Sup. Please take a second to quickly reply to this survey.  It will only be open for a few more hours."
'''
closer1 = "Ok, cool.  Thanks very much!"
closer2 = "Your feedback will be reflected anonymously on the dashboard very soon."
closedPoll = "\n---------------- Survey Closed ----------------\nThe survey poll for this week is now closed. If you missed it despite the reminders, there will be another one next week.\n\nThanks very much,\n- Connected B0T"

pollStartTime = time.time()
print "\n--- New Survey: %s : %d ---" % (time.strftime("%Y/%m/%d"),
                                         pollStartTime)

listOfUsers = "%s/%s" % (workingDirectory, userListFile
                         )  # prod use clUsers.txt | test
#listOfUsers = "%s/clUsersTest.txt" % workingDirectory		# prod use clUsers.txt | test use clUsersTest.txt
outPutResponses = "%s/%s" % (workingDirectory, responseOutputFile)
slackClientObject = SlackClient(slackToken)


def closePoll():
    global pollIsStillOpen
    global responseList
    signal.alarm(0)
    print("Closing the Poll!")

    sendMsg("all", closedPoll)
    pollIsStillOpen = False  # main method while flag

    # Write the results to file
    responseDataFile = open(outPutResponses, 'a+')
    for userEntry in responseList.keys():
        if (responseList[userEntry]['resp1'] !=
Example #21
0
#!/usr/bin/env python
# encoding: utf-8
import os
import time

from flask import current_app

from flask_admin import Admin
from flask_login import LoginManager
from flask_mail import Mail
from flask_jwt import JWT
from flask_redis import FlaskRedis
from raven.contrib.flask import Sentry
from slackclient import SlackClient

from application.services.theme import _reload_template, _get_template_name


sc = SlackClient("xoxb-68385490752-9gPeX5F6krKS84C1LO6moByC")
jwt = JWT()
mail = Mail()
admin = Admin()
redis = FlaskRedis()
login_manager = LoginManager()
sentry = Sentry()
Example #22
0
import os
from slackclient import SlackClient
from flask import Flask, request, Response
from die_roller import Roll

app = Flask(__name__)

SLACK_WEBHOOK_SECRET = os.environ.get('SLACK_WEBHOOK_SECRET')
SLACK_TOKEN = os.environ.get('SLACK_TOKEN', None)
slack_client = SlackClient(SLACK_TOKEN)
rollerBotName = "RollerBot"
msg = ""
username = ""


@app.route('/roll', methods=['POST'])
def inbound():
    if request.form.get('token') == SLACK_WEBHOOK_SECRET:
        channel = request.form.get('channel_name', '')
        username = request.form.get('user_name', '')
        text = request.form.get('text', '')
        if text == "help":
            msg = """/roll generates a random dice roll result with arbitrary modifiers.\n`/roll <name> <dice>... <modifiers>...`\n>*name:* (optional) String name of the roll i.e. `attack`, `damage`, `perception`\n>*dice:* A list of space or comma seperated dice to roll i.e. `2d10,5d4`\n>*modifiers:* (optional) A list of modifiers i.e. `+3-4`, `+3 -4`, `+3,-4`"""
        else:
            try:
                roller = Roll(text)
                mod = "`{}{}`".format("+" if roller.mod > 0 else "",
                                      roller.mod)
                dice = [
                    "*{}d{}:* `{}`".format(c, d, " ".join(list(map(str, v))))
                    for c, d, v in roller.results
Example #23
0
 def _slack_client(self):
     if self.__slack_client:
         return self.__slack_client
     self.__slack_client = SlackClient(self.slack_bot_token)
     return self.__slack_client
Example #24
0
from bs4 import BeautifulSoup as bs4
import requests
from slackclient import SlackClient
import time

#Slack connection
slack_client = SlackClient(
    'your slack bot token goes here. More info:https://api.slack.com/bot-users'
)


#searches CL for keyword and posts to Slack
def cl():
    url_base = ('https://louisville.craigslist.org/search/sss')
    params = dict(
        query=keyword, sort='date'
    )  #etc - just add parameters as you see fit. Taken from cl.com search url then reformat
    rsp = requests.get(url_base, params=params)
    html = bs4(rsp.text, 'html.parser')
    shit = []
    shit = html.find_all('p', attrs={'class': 'result-info'})
    for s in shit:
        price = s.find('span', attrs={'class': 'result-price'})
        if price == None:
            price = 'unknown'
        else:
            price = str(price.text)
        date = s.find('time', attrs={'class': 'result-date'})
        date = date.text
        link = s.find('a', attrs={'class': 'result-title'})
        text = link.text
Example #25
0
 def __init__(self):
     self.socket_connections = 0
     self.users = {}
     self.sc = SlackClient(SLACK_API_TOKEN)
     self.connected_to_rtm = False
     self.channel_info = {}
Example #26
0
 def __init__(self, slack_token, config):
     self.slack_token = slack_token
     self.slack = SlackClient(slack_token)
     self.state = State()
     self.cache = Cache()
     self.config = config
Example #27
0
 def __init__(self, token):
     self.client = SlackClient(token)
Example #28
0
from slackclient import SlackClient


import os

b_token = app.config['BOT_TOKEN']
u_token = app.config['USER_TOKEN']
veri = app.config['VERIFICATION_TOKEN']
oauth_scope = app.config['OAUTH_SCOPE']
client_id = app.config['CLIENT_ID']
client_secret = app.config['CLIENT_SECRET']


# Global reference for the Slack Client tokens
sc = SlackClient(b_token)
sc_user = SlackClient(u_token)


# Main index page
@app.route("/index")
@app.route("/")
@login_required
def index():

    return render_template('index.html')


# login page
@app.route('/login', methods=['GET', 'POST'])
def login():
Example #29
0
lastMatchKey = ""
modifiedSince = 0

# sample sheet
SHEET_URL = 'https://docs.google.com/spreadsheets/d/1ahzHfDmDL5Id-toAyaCf5d1LAiDygfJPGKz1R1jrfRo/edit?ts=5c2c5962#gid' \
            '=1876596371 '

SHEET_NAME = "Calendar"
# it's REMIND TIME Y'ALL
REMIND_TIME = "18:00"
REMIND_DAYS_AHEAD = 2

# save TBA token as system variable 'TBA_API_TOKEN' and slack as 'SLACK_API_TOKEN'
SLACK_TOKEN = os.environ['SLACK_API_TOKEN']

sc = SlackClient(SLACK_TOKEN)

DEBUG_MODE = False

SHIFTS = {
    "Default": ["6pm-10pm"],
    "Saturday": ["8am-12pm", "12pm-5pm", "5pm-10pm"]
}
SHIFTS_FORMAT = {}

for key, arr in SHIFTS.items():
    SHIFTS_FORMAT[key] = {}
    for index, value in enumerate(arr):
        SHIFTS_FORMAT[key][value] = []
PEOPLE_FORMAT = {
    "Design/Build": {},
Example #30
0
from flask_login import LoginManager, login_required, login_user, current_user, logout_user
import challonge
from slackclient import SlackClient
import uuid

app = Flask(__name__)
app.secret_key = FLASK_SECRET_KEY
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
app.app_context().push()

login_manager = LoginManager()
login_manager.init_app(app)

db.init_app(app)
challonge.set_credentials(CHALLONGE_USERNAME, CHALLONGE_API_KEY)
sc = SlackClient(SLACK_VERIFICATION_TOKEN)


@login_manager.user_loader
def user_loader(id):
    return User.query.filter_by(id=id).first()


@app.route("/")
def hello():
    return render_template('pages/home.html', title='home')


@app.route("/slack_auth", methods=['GET', 'POST'])
def slack_login():
    #TODO error handling and rewrite func