Пример #1
0
def slackusers(bot, event, *args):
    slack_sink = bot.get_config_option('slack')
    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:
            slackkey = sinkConfig["key"]
            channel = sinkConfig["channel"]
            convlist = sinkConfig["synced_conversations"]

            if event.conv_id in convlist:
                try:
                    client = SlackClient(slackkey, verify=True)
                except TypeError:
                    client = SlackClient(slackkey)

                chan_id = client.channel_name_to_id(channel)
                slack_api_params = {'channel': chan_id}
                info = client._make_request('channels.info', slack_api_params)
                msg =  "Slack channel {}: {}".format(info['channel']['name'],
                                                       info['channel']['topic']['value'])
                users = {}
                for uid in info['channel']['members']:
                    slack_api_params = {'user': uid}
                    user = client._make_request('users.info', slack_api_params)
                    if user["ok"] and user['user']:
                        username = user['user']['name']
                        realname = user['user'].get('real_name', "No real name")
                        users[username] = realname

                msg += "\n{} members:".format(len(users))

                for username, realname in sorted(users.items()):
                    msg += "\n  {}: {}".format(username, realname)

                yield from bot.coro_send_message(event.conv, msg)
Пример #2
0
def _handle_slackout(bot, event, command):
    if "_slack_no_repeat" in dir(event) and event._slack_no_repeat:
        return
    """forward messages to slack over webhook"""

    slack_sink = bot.get_config_option('slack')

    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:

            try:
                slackkey = sinkConfig["key"]
                channel = sinkConfig["channel"]
                convlist = sinkConfig["synced_conversations"]

                if event.conv_id in convlist:
                    fullname = event.user.full_name
                    response = yield from bot._client.getentitybyid(
                        [event.user_id.chat_id])
                    try:
                        photo_url = "http:" + response.entities[
                            0].properties.photo_url
                    except Exception as e:
                        logger.exception(
                            "FAILED to acquire photo_url for {}".format(
                                fullname))
                        photo_url = None

                    try:
                        client = SlackClient(slackkey, verify=True)
                    except TypeError:
                        client = SlackClient(slackkey)

                    slack_api_params = {
                        'username': fullname,
                        'icon_url': photo_url
                    }

                    if "link_names" not in sinkConfig or sinkConfig[
                            "link_names"]:
                        logger.debug("slack api link_names is active")
                        slack_api_params["link_names"] = 1

                    client.chat_post_message(channel, event.text,
                                             **slack_api_params)

            except Exception as e:
                logger.exception(
                    "Could not handle slackout with key {} between {} and {}."
                    " Is config.json properly configured?".format(
                        slackkey, channel, convlist))
Пример #3
0
def _handle_slackout(bot, event, command):
    if "_slack_no_repeat" in dir(event) and event._slack_no_repeat:
        return
    """forward messages to slack over webhook"""

    slack_sink = bot.get_config_option('slack')

    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:

            try:
                slackkey = sinkConfig["key"]
                channel = sinkConfig["channel"]
                convlist = sinkConfig["synced_conversations"]

                if event.conv_id in convlist:
                    fullname = event.user.full_name
                    response = yield from bot._client.getentitybyid(
                        [event.user_id.chat_id])
                    try:
                        photo_url = "http:" + response.entities[
                            0].properties.photo_url
                    except Exception as e:
                        print("Slack: Could not pull avatar for {}".format(
                            fullname))

                    client = SlackClient(slackkey)
                    client.chat_post_message(channel,
                                             event.text,
                                             username=fullname,
                                             icon_url=photo_url)
            except Exception as e:
                print(
                    "Could not handle slackout with key {} between {} and {}. is config.json properly configured?"
                    .format(slackkey, channel, convlist))
Пример #4
0
class Logger:

    def __init__(self, verbosity=1, reporting=1):
        '''
        Logger util for relevant data and errors.

        Args:
            verbosity: 0 silences logger in console, 1 prints output.
                Logging to file is active at any level.
            reporting: 0 silences reporting, 1 logs into logfile,
                2 sends Slack message only,
                3 sends email only,
                4 sends both Slack and email messages.
                Both 2, 3 and 4 also print to logfile.
        '''
        self.verbosity = verbosity
        self.reporting = reporting

        self.__setup_file_logging()

        try:
            self.email = smtplib.SMTP(
                settings.EMAIL_SMTP_SERVER, settings.EMAIL_SMTP_PORT
            )
        except gaierror, e:
            self.__error_to_file(e)

        self.slack = SlackClient(settings.SLACK_API_KEY)
Пример #5
0
def _handle_slackout(bot, event, command):
    """forward messages to slack over webhook"""

    slack_sink = bot.get_config_option('slack')

    if isinstance(slack_sink, list):
        for sinkConfig in slack_sink:

            try:
                slackkey = sinkConfig["key"]
                channel = sinkConfig["channel"]
                convlist = sinkConfig["synced_conversations"]

                if event.conv_id in convlist:
                    fullname = event.user.full_name
                    response = yield from bot._client.getentitybyid(
                        [event.user_id.chat_id])
                    try:
                        photo_url = "http:" + response['entity'][0][
                            'properties']['photo_url']
                    except Exception as e:
                        print("Slack: Could not pull avatar for {}".format(
                            fullname))

                    client = SlackClient(slackkey)
                    client.chat_post_message(channel,
                                             event.text,
                                             username=fullname,
                                             icon_url=photo_url)
            except Exception as e:
                print(
                    "Could not handle slackout, is config.json properly configured?"
                )
def main(argv=sys.argv):
    import getopt
    short_args = "hp:e:at:c:"
    long_args = [
        "help",
        "program=",
        "event=",
        "any",
        "token="
        "channel=",
        ]
    arguments = argv[1:]
    try:
        opts, args = getopt.getopt(arguments, short_args, long_args)
    except:
        usage()

    programs = []
    events = []
    any = False
    channel = ''
    token = ''

    for option, value in opts:

        if option in ('-h', '--help'):
            usage()

        if option in ('-p', '--program'):
            programs.append(value)

        if option in ('-e', '--event'):
            events.append(value)

        if option in ('-a', '--any'):
            any = True

        if option in ('-t', '--token'):
            token = value

        if option in ('-c', '--channel'):
            channel = value

    if not events:
        events = config.events.keys()

    if 'SUPERVISOR_SERVER_URL' not in os.environ:
        sys.stderr.write('slack must be run as a supervisor event '
                         'listener\n')
        sys.stderr.flush()
        return

    sys.stderr.flush()
    slackClient = SlackClient(token)

    prog = SlackNotifier(slackClient, programs, any, events, channel)
    prog.runforever()
Пример #7
0
def _slack_send(bot, sinkConfig, message, chat_id, passthru):

    _response = yield from bot._client.get_entity_by_id(
        hangups.hangouts_pb2.GetEntityByIdRequest(
            request_header=bot._client.get_request_header(),
            batch_lookup_spec=[
                hangups.hangouts_pb2.EntityLookupSpec(gaia_id=chat_id)
            ]))

    try:
        photo_url = "http:" + _response.entity[0].properties.photo_url
    except Exception as e:
        logger.exception("FAILED to acquire photo_url for {}".format(fullname))
        photo_url = None

    if "original_request" in passthru:
        message = passthru["original_request"]["message"]
        if isinstance(passthru["original_request"]["user"], str):
            fullname = passthru["original_request"]["user"]
        else:
            fullname = _response.entity[0].properties.display_name

    try:
        try:
            client = SlackClient(sinkConfig["key"], verify=True)
        except TypeError:
            client = SlackClient(sinkConfig["key"])

        slack_api_params = {'username': fullname, 'icon_url': photo_url}

        if "link_names" not in sinkConfig or sinkConfig["link_names"]:
            logger.debug("slack api link_names is active")
            slack_api_params["link_names"] = 1

        client.chat_post_message(sinkConfig["channel"], message,
                                 **slack_api_params)
    except Exception as e:
        logger.exception(
            "Could not handle slackout with key {} between {} and {}. "
            "Is config.json properly configured?".format(slackkey, channel))
Пример #8
0
def main():
    global LAST_UPDATE_ID

    parser = argparse.ArgumentParser(description=BOT_DESCRIPTION)
    parser.add_argument("--logfile",
                        type=str,
                        default='log',
                        help="Path to log file")
    parser.add_argument("--dbfile",
                        type=str,
                        default='proofspace.sqlite',
                        help="Path to sqlite DB file")
    args = parser.parse_args()

    botDB.bind('sqlite', args.dbfile, create_db=True)
    botDB.generate_mapping(create_tables=True)

    # TODO: use it
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',
                               ca_certs=certifi.where())

    telegram_token = open('.telegram_token').readline().strip()
    slack_token = open('.slack_token').readline().strip()
    bot = telegram.Bot(telegram_token)
    slackbot = SlackClient(slack_token)

    try:
        LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
    except IndexError:
        LAST_UPDATE_ID = None

    while True:
        try:
            run(bot, args.logfile, slackbot)
        except telegram.TelegramError as error:
            print "TelegramError", error
            time.sleep(1)
        #except urllib2.URLError as error:
        #    print "URLError", error
        #    time.sleep(1)
        except:
            traceback.print_exc()
            try:
                bot.sendMessage(chat_id=CHAT_ID_ALARM, text=MESSAGE_ALARM)
            except:
                pass
            time.sleep(100)  # 100 seconds
Пример #9
0
def talk_to_slack():
    # this function sends the same output of the files to slack
    get_last_data()
    token_dir = os.path.expanduser('~/.packages/conf/conf.txt')
    client = None
    if os.path.exists(token_dir):
        with open(token_dir, 'r') as fp:
            client = SlackClient(fp.readlines()[0].strip())
    with open(LOG_FILE_DIR, 'a+') as fp:
        fp.write(last_data + '\n')
    if client is not None:
        client.chat_post_message('#mail-tracker-notif',
                                 last_data,
                                 username='******')
    sys.exit(0)
Пример #10
0
    def post(self, request):
        serializer = SlackChatSerializer(data=request.data)
        client = SlackClient(
            'xoxp-4254176702-8269771440-11734785028-c59bdd6fab')
        if serializer.is_valid():
            try:
                message_construct = serializer.data['message_construct']
                chat_message = client.chat_post_message('#help',
                                                        message_construct,
                                                        username='******')
                content = {'data': chat_message}
                return Response(content)

            except ObjectDoesNotExist:
                raise Http404
Пример #11
0
    def __init__(self, connect=True):
        # Lets get set up
        botPass = {}
        if botData.token_id:
            self.client = SlackClient(botData.token_id)
        if connect is True:
            req = self.client._make_request('rtm.start', {})
            socket_url = req['url']
            self.ws = websocket.WebSocket()
            self.ws.connect(socket_url)
        else:
            self.ws = websocket.WebSocket()

        # Compile regex triggers and url regex
        self.triggers = {}
        for key, val in self.hooks.iteritems():
            self.triggers[key] = re.compile(val)

        self.urlChecker = re.compile(self.urlFixer)

        # For Python 2.x
        self.html_parser = HTMLParser.HTMLParser()
Пример #12
0
    async def _send_to_external_chat(self, config, event):
        conv_id = config["trigger"]
        relay_channels = config["config.json"][self.configkey]

        user = event.passthru["original_request"]["user"]
        message = event.passthru["original_request"]["message"]

        if not message:
            message = ""

        # XXX: rudimentary conversion of html to markdown
        message = re.sub(r"</?b>", "*", message)
        message = re.sub(r"</?i>", "_", message)
        message = re.sub(r"</?pre>", "`", message)

        bridge_user = self._get_user_details(user, { "event": event })

        try:
            client = SlackClient(config["config.json"]["key"], verify=True)
        except TypeError:
            client = SlackClient(config["config.json"]["key"])

        slack_api_params = { 'username': bridge_user["preferred_name"],
                             'icon_url': bridge_user["photo_url"] }

        if "link_names" not in config["config.json"] or config["config.json"]["link_names"]:
            slack_api_params["link_names"] = 1

        """XXX: deferred image sending

        this plugin leverages existing storage in hangouts - since there isn't a direct means
        to acquire the public url of a hangups-upload file we need to wait for other handlers to post
        the image in hangouts, which generates the public url, which we will send in a deferred post.

        handlers.image_uri_from() is packaged as a task to wait for an image link to be associated with
        an image id that this handler sees
        """

        if( "image_id" in event.passthru["original_request"]
                and event.passthru["original_request"]["image_id"] ):

            if( "conv_event" in event
                    and "attachments" in event.conv_event
                    and len(event.conv_event.attachments) == 1 ):

                message = "shared an image: {}".format(event.conv_event.attachments[0])
            else:
                # without attachments, create a deferred post until the public image url becomes available
                image_id = event.passthru["original_request"]["image_id"]

                loop = asyncio.get_event_loop()
                task = loop.create_task(
                    self.bot._handlers.image_uri_from(
                        image_id,
                        self._send_deferred_photo,
                        relay_channels,
                        client,
                        slack_api_params ))

        """standard message relay"""

        for relay_channel in relay_channels:
            client.chat_post_message(relay_channel,  message, **slack_api_params)
Пример #13
0
LOGBOOK_PATH = "/usr/local/elog/logbooks"
BOTNAME = "ELOG"
DEFAULT_DESTINATION = "#elog"
DESTINATIONS = {
    "Operations_IT": "#operations_it",
    "Operations_FR": "#operations_fr",
    #    'Qualification': '#elog',
    #    'DOM_Integration': '#elog',
    #    'DU_Integration': '#elog',
    #    'DAQ_Readout': '#elog',
    #    'Electronics': '#elog',
    #    'Analysis': '#elog',
    "Computing and Software": "#software",
}

slack = SlackClient("YOUR_SLACK_API_TOKEN_HERE")


class ElogEntry(object):
    def __init__(self, logbook, msg_id=None):
        self.logbook = logbook
        self.id = msg_id
        self.header = {}
        self.content = ""

    @property
    def author(self):
        return self._lookup("Author")

    @property
    def type(self):
Пример #14
0
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash

from pyslack import SlackClient

# the number of days of inactivity after which we begin to decay
DECAY_AFTER = 3
SEGMENT = [98, 101, 110]
CLOSURE = [103, 105, 108, 98, 101, 114, 116]
ENCODING = [70, 111, 108, 108, 111, 119, 32, 109, 121, 32, 112, 111, 100, 99, 97, 115, 116, 33]

app = Flask(__name__)
scheduler = BackgroundScheduler()
slack_client = SlackClient(os.environ['SLACK_API_TOKEN'])

# Utility functions

def stdev(arr):
    if len(arr) < 2:
        raise ValueError("To calculate stdev, length ")
    mean = float(sum(arr)) / len(arr)
    deltas = [abs(a - mean)**2 for a in arr]
    return math.sqrt(float(sum(deltas)) / len(deltas))

def security_flag(segment, closure):
    return segment.lower() == ''.join([chr(x) for x in SEGMENT]) and closure.lower() == ''.join([chr(x) for x in CLOSURE])

def connect_db():
    rv = sqlite3.connect(app.config['DATABASE'])
Пример #15
0
 def __init__(self):
     settings = sublime.load_settings("SubSlack.sublime-settings")
     token = settings.get('token')
     self.bot = settings.get('bot_name')
     self.room = '#%s' % settings.get('default_chat')
     self.client = SlackClient(token)
Пример #16
0
    return sub_expire


# Main
salt_root = "/salt/"
pillar_filelist = []

for root, dirs, files in os.walk(salt_root):
    for f in files:
        if "/pillar/" in root:
            pillar_filelist.append(os.path.join(root, f))

report_data = extract_certs(pillar_filelist)

for entry in report_data:
    slack_client = SlackClient(slack_api_key)
    slack_message = ""
    subject = report_data[entry][0]
    expire_after = report_data[entry][1]

    if (expire_after - timedelta(days=30)) < datetime.now():
        slack_message = "*ACTION REQUIRED:* A certificate found in `{}`, with a subject of `{}`, is expired/will expire on *{}*.".format(
            entry, subject, expire_after)
    elif (expire_after - timedelta(days=60)) < datetime.now():
        slack_message = "*Warning:* A certificate found in `{}`, with a subject of `{}`, will expire on *{}*.".format(
            entry, subject, expire_after)
    if slack_message:
        slack_client.chat_post_message(slack_channel,
                                       slack_message,
                                       username=slack_username)
Пример #17
0
# https://api.slack.com/community
# https://api.slack.com/community#python
# v1 avec ce client :
# https://github.com/loisaidasam/pyslack
from pyslack import SlackClient

# https://api.slack.com/apps

botUserOAuthAccessToken = input("Bot User OAuth Access Token ? ")

print("Bot User OAuth Access Token : ", botUserOAuthAccessToken)

client = SlackClient(botUserOAuthAccessToken)

client.chat_post_message('#dev', "Hello ", username='******')
Пример #18
0
from pyslack import SlackClient
import os

token = os.environ['SLACK_TOKEN']

if token == '':
    print('Could not get SLACK_TOKEN')
    exit(1)

client = SlackClient(token)
client.chat_post_message('#log',
                         "Posted from post.py: hello!",
                         username='******')
Пример #19
0
 def __init__(self, token, user, send_to):
     self.client = SlackClient(token)
     self.user = user
     self.send_to = send_to
Пример #20
0
import requests
import config
import json
from pymongo import MongoClient
from pyslack import SlackClient
from datetime import datetime

mongo = MongoClient(config.mongo_string)
db = mongo.slack
mongo_messages = db.messages

slack = SlackClient(config.token)

channels = slack.channel_listing('public_channel,private_channel')

mongo_docs = []

created_date = datetime.utcnow()
messagecount = 0
for channel in channels:
    messages = slack.message_listing(channel['id'])
    print(channel['name'] + ' ' + str(len(messages)))
    messagecount = messagecount + len(messages)
    for message in messages:
        doc = message
        ts = float(message['ts'])
        timestamp = int(ts)
        doc['channel'] = channel['name']
        doc['channelid'] = channel['id']
        doc['messagedate'] = datetime.utcfromtimestamp(timestamp).strftime(
            '%Y-%m-%d %H:%M:%S')
Пример #21
0
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CLOSE_WRITE

URL = 'http://elog.whatever.com'
LOGBOOK_PATH = '/usr/local/elog/logbooks'
BOTNAME = 'ELOG'
PREVIEW_LENGTH = 150
FALLBACK_DESTINATION = '#elog'
DESTINATIONS = {
    'Analysis': '#analysis',
    'Computing and Software': '#software',
    'Whatever': '@tgal',
    }

slack = SlackClient('YOUR-SLACK-API-TOKEN')


class ElogEntry(object):
    def __init__(self, logbook, msg_id=None):
        self.logbook = logbook
        self.id = msg_id
        self.header = {}
        self.content = ''

    @property
    def author(self):
        return self._lookup('Author')

    @property
    def type(self):
Пример #22
0
#asterisk AMI login
server = "ASTRISKSERVERNAME"
port = 5038
username = "******"
secret = "PASSWORD"
extensions = {"SIP/200": "YOU", "SIP/201": "Someone else"}

log = logging.getLogger("server")

timeouttask = None
timeoutping = 5
timeoutloop = 120

slack_api_token = 'ENTERTOKEN'

client = SlackClient(slack_api_token)


def sendToSlack(msg):
    client.chat_post_message('#phone', msg, username='******')


class callMeFactory(AMIFactory):
    cbconnect = None

    def __init__(self):
        AMIFactory.__init__(self, username, secret)

    def connect(self):
        print 'connecting'
        df = self.login(server, port)
Пример #23
0
 def __init__(self, token, channel):
     self.slack = SlackClient(token)
     self.channel = channel