from flask import render_template, request, redirect from decouple import config import slack from app import app SLACK_API_TOKEN = config('SLACK_API_TOKEN') SLACK_USER = config('SLACK_USER') client = slack.WebClient(SLACK_API_TOKEN) @app.route('/') def index(): return render_template('google.html', title='Home') @app.route('/login') def login(): return render_template('github.html', title='Home') @app.route('/signin') def signin(): return render_template('linkedin.html', title='Home') @app.route('/google', methods=['POST']) def google(): client.chat_postMessage(channel=SLACK_USER, text=request.form['Email'] +
import slack import certifi import ssl as ssl_lib from slackeventsapi import SlackEventAdapter from datetime import datetime, timedelta import calendar import db_processor ssl_context = ssl_lib.create_default_context(cafile=certifi.where()) client = slack.WebClient(token='', ssl=ssl_context) slack_events_adapter = SlackEventAdapter('', endpoint="/slack/events") def search_result(start, end): result = {} for item in db_processor.find_date_range(start, end): key = item['name'] if key in result.keys(): result[key].append(item['date'].date().strftime("%Y-%m-%d")) else: result[key] = [item['date'].date().strftime("%Y-%m-%d")] return result def process_content(message): channel = message['channel'] key_word = message['text'] if 'HELP' in key_word.upper(): client.chat_postMessage(channel=channel, text='Usage: \n 1. Send WFH and @me \n 2. Send REPORT and @me \n 3. Send DATE: YYYY-MM-DD to YYYY-MM-DD and @me \n')
**message_handler.get_help_message(data['user'])) @slack.RTMClient.run_on(event='message') def on_message(**payload): data = payload['data'] print(data) channel_id = data['channel'] web_client = payload['web_client'] text = data.get('text', []).lower() if f'@{bot_id.lower()}' in text: parse_comand(text, data, bot_id, web_client, channel_id) if __name__ == '__main__': isrun = False while True: try: slack_token = os.environ["SLACK_TOKEN"] rtm_client = slack.RTMClient(token=slack_token) slack_client = slack.WebClient(token=slack_token) bot_id = slack_client.api_call("auth.test")["user_id"] print("Bot started") isrun = True rtm_client.start() except TimeoutError: print("Server problems") except BaseException: print("Something wrong. Restarting")
i) time.sleep(2.5) elif i == 1: #When output from motion sensor is HIGH print( "arcturus (iothub bypass) | PIR Motion sensor : Movement detected ", datetime.datetime.now()) slack_msg = { 'text': 'arcturus (iothub bypass) | PIR Motion sensor : Movement detected ' + str(datetime.datetime.now()) } requests.post(webhook_url, data=json.dumps(slack_msg)) time.sleep(0.5) from slack import WebClient client = slack.WebClient('xoxb-yourSlackTOKENhere') TakePic = 'raspistill -o /home/pi/Scripts/Camera/77389-garage.jpg -ISO 200 -ev 10' os.system(TakePic) response = client.files_upload( channels='#cvx-iot-arcturus', file="/home/pi/Scripts/Camera/77389-garage.jpg") assert response["ok"] except: slack_msg = { 'text': 'arcturus (iothub bypass) | PIR Motion sensor : Exception occurred [TakePic]! ' + str(datetime.datetime.now()) } requests.post(webhook_url, data=json.dumps(slack_msg)) os.execv(__file__, sys.argv) #20200605 : Heal process and restart
# This script will archive all change channels import os from flask import Flask import requests import slack app = Flask(__name__) app.config.from_object(os.environ.get("FLASK_CONFIG", "app.config.DevelopmentConfig")) client = slack.WebClient(token=app.config["SLACK_TOKEN"]) response = client.conversations_list() channels = response["channels"] for channel in channels: if ( channel["name"].startswith(app.config["SLACK_CHANGE_CHANNEL_PREFIX"]) and not channel["is_archived"] ): channel_id = channel["id"] requests.post( f"https://slack.com/api/channels.archive?token={app.config['SLACK_USER_TOKEN']}&channel={channel_id}" )
def notify_tagged_user(application, userTags, project, note, category, tagger, timestamp): view_result = {} project_id = project[0] project_name = project[1] time_in_format = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S').strftime("%a %b %d %Y, %I:%M:%S %p") note_id = 'running_note_' + project_id + '_' + \ str(int((datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') - datetime.datetime.utcfromtimestamp(0)).total_seconds())) for row in application.gs_users_db.view('authorized/users'): if row.key != 'genstat_defaults': view_result[row.key.split('@')[0]] = row.key if category: category = ' - ' + category for user in userTags: if user[1] in view_result: user = user[1] option = PresetsHandler.get_user_details(application, view_result[user]).get('notification_preferences', 'Both') #Adding a slack IM to the tagged user with the running note if option == 'Slack' or option == 'Both': nest_asyncio.apply() client = slack.WebClient(token=application.slack_token) notification_text = '{} has tagged you in {}, {}!'.format(tagger, project_id, project_name) blocks = [ { "type": "section", "text": { "type": "mrkdwn", "text": ("_You have been tagged by *{}* in a running note for the project_ " "<{}/project/{}#{}|{}, {}>! :smile: \n_The note is as follows:_ \n\n\n") .format(tagger, application.settings['redirect_uri'].rsplit('/',1)[0], project_id, note_id, project_id, project_name) } }, { "type": "section", "text": { "type": "mrkdwn", "text": ">*{} - {}{}*\n>{}\n\n\n\n _(Please do not respond to this message here in Slack." " It will only be seen by you.)_".format(tagger, time_in_format, category, note.replace('\n', '\n>')) } } ] try: userid = client.users_lookupByEmail(email=view_result[user]) channel = client.conversations_open(users=userid.data['user']['id']) client.chat_postMessage(channel=channel.data['channel']['id'], text=notification_text, blocks=blocks) client.conversations_close(channel=channel.data['channel']['id']) except Exception: #falling back to email option = 'E-mail' #default is email if option == 'E-mail' or option == 'Both': msg = MIMEMultipart('alternative') msg['Subject']='[GenStat] Running Note:{}, {}'.format(project_id, project_name) msg['From']='genomics-status' msg['To'] = view_result[user] text = 'You have been tagged by {} in a running note in the project {}, {}! The note is as follows\n\ >{} - {}{}\ >{}'.format(tagger, project_id, project_name, tagger, time_in_format, category, note) html = '<html>\ <body>\ <p> \ You have been tagged by {} in a running note in the project <a href="{}/project/{}#{}">{}, {}</a>! The note is as follows</p>\ <blockquote>\ <div class="panel panel-default" style="border: 1px solid #e4e0e0; border-radius: 4px;">\ <div class="panel-heading" style="background-color: #f5f5f5; padding: 10px 15px;">\ <a href="#">{}</a> - <span>{}</span> <span>{}</span>\ </div>\ <div class="panel-body" style="padding: 15px;">\ <p>{}</p>\ </div></div></blockquote></body></html>'.format(tagger, application.settings['redirect_uri'].rsplit('/',1)[0], project_id, note_id, project_id, project_name, tagger, time_in_format, category, markdown.markdown(note)) msg.attach(MIMEText(text, 'plain')) msg.attach(MIMEText(html, 'html')) s = smtplib.SMTP('localhost') s.sendmail('*****@*****.**', msg['To'], msg.as_string()) s.quit()
import json from pymongo import MongoClient import slack import os import traceback import re import slackBotActions app.config["MONGO_URI"] = "mongodb://*****:*****@slack_events_adapter.on("member_joined_channel") def handle_message(event_data): tempMessage = slackBotActions.slackParse(event_data) if (tempMessage['unit'] == True): slack_client.chat_postMessage(channel=tempMessage['channel'], text=tempMessage['text']) @slack_events_adapter.on("reaction_added") def reaction_added(event_data): tempMessage = slackBotActions.slackParse(event_data) if (tempMessage['unit'] == True): slack_client.chat_postMessage(channel=tempMessage['channel'],
import slack import os SOCLESS_BOT_TOKEN = os.environ['SOCLESS_BOT_TOKEN'] slack_client = slack.WebClient(SOCLESS_BOT_TOKEN) def find_user(name, page_limit=1000, include_locale='false'): """ Find a user's Slack profile based on their full or display name """ name_lower = name.lower() paginate = True next_cursor = '' while paginate: resp = slack_client.users_list(cursor=next_cursor, limit=page_limit, include_locale=include_locale) data = resp.data next_cursor = resp.data['response_metadata'].get('next_cursor', '') if not next_cursor: paginate = False for user in data['members']: user_names = list( map(str.lower, [ user.get('name', ''), user.get('real_name', ''), user.get('profile', {}).get('real_name', '') ]))
def main(): args = docopt(__doc__, version=__version__) if args["slack"]: if args["bulk-invite"]: client = slack.WebClient(os.environ["SLACK_BOT_USER_TOKEN"]) channel_id = channel_name_to_id(args["<channel-name>"], client) users = list_users(client) print(f"Inviting {len(users)} to {args['<channel-name>']}") for u in tqdm(users): try: client.conversations_invite(channel=channel_id, users=[u.id]) except Exception as e: print(e) elif args["export"]: client = slack.WebClient(os.environ["SLACK_USER_TOKEN"]) if args["conversations"]: conversation_id = args["--conversation-id"] with jsonlines.open(args["--output-jsonl"], mode="w") as fp: bar = tqdm() for batch in get_message_batches(conversation_id, client): fp.write_all(batch) bar.update(len(batch)) elif args["users"]: with open(args["--output-json"], "w") as fp: users = list_users(client) json.dump([dataclasses.asdict(u) for u in users], fp) elif args["post"]: client = slack.WebClient(os.environ["SLACK_BOT_USER_TOKEN"]) if args["--text-file"]: with open(args["--text-file"]) as fp: text = fp.read() channel_id = channel_name_to_id(args["--channel-name"], client) client.chat_postMessage(channel=channel_id, text="", blocks=[{ "type": "section", "text": { "type": "mrkdwn", "text": text } }]) if args["--file"]: response = client.files_upload(channels=args["--channel-name"], file=args["--file"], initial_comment="") if args["bulk"]: with open(args["--template-file"]) as fp: template = jinja2.Template(fp.read()) with open(args["--bulk-post-config"]) as fp: bulk_items = yaml.safe_load(fp) for item in tqdm(bulk_items): variables = item.get("variables", {}) response = client.conversations_open( users=item["user-ids"]) client.chat_postMessage(channel=response["channel"]["id"], text=template.render(**variables)) if args["calendar"]: if args["report"]: email_id = args["<email-id>"] n_prev = int(args["--n-prev"]) n_next = int(args["--n-next"]) anchor_dt = get_last_sunday() delta = datetime.timedelta(days=7) start_dts = [ anchor_dt - (delta * i) for i in range(n_prev, -(n_next + 1), -1) ] headers = [ "Start", "End", "Total Hours", "Personal Block", "External", "1:1", "Rest" ] table = [] for start_time in start_dts: end_time = start_time + delta evs = parse_google_calendar(email_id, start_time, end_time) summary = report_events_summary(evs) table.append( (start_time.date(), end_time.date(), summary["total"], summary["personal"], summary["external"], summary["1:1"], summary["rest"])) print(tabulate(table, headers=headers, tablefmt="fancy_grid")) elif args["export"]: with open(args["--users-json"]) as fp: users = [SlackUser(**it) for it in json.load(fp)] n_prev = int(args["--n-prev"]) n_next = int(args["--n-next"]) today = datetime.datetime.today() anchor_dt = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0) # First day of the month start_dt = anchor_dt for _ in range(n_prev): start_dt -= datetime.timedelta( days=1) # Subtracting a day to go to past month start_dt = start_dt.replace(day=1) end_dt = get_last_day_of_month(anchor_dt) for _ in range(n_next): end_dt += datetime.timedelta(days=1) end_dt = get_last_day_of_month(end_dt) output = {} for user in tqdm(users): if user.email: events = parse_google_calendar(user.email, start_dt, end_dt) output[user.email] = events with open(args["--output-pickle"], "wb") as fp: pickle.dump(output, fp)
#MONGO #DATABASE="nestor" #COLLECTION="mensajes" #myclient = pymongo.MongoClient(host=os.environ['MONGO_HOST'], port=int(os.environ['MONGO_PORT'])) #db = myclient[DATABASE] #col = db[COLLECTION] #BOT SLACK app = Flask(__name__) slack_event_adapter = SlackEventAdapter( os.environ.get("SIGNING_SECRET"),'/slack/events',app) client = slack.WebClient(token=os.environ.get("SLACK_TOKEN")) BOT_ID = client.api_call("auth.test")['user_id'] @slack_event_adapter.on('message') def message(payload): event = payload.get('event', {}) channel_id = event.get('channel') user_id = event.get('user') text = event.get('text') if (BOT_ID != user_id): client.chat_postMessage(channel=channel_id, text=text) if (__name__ == "__main__"): app.run(debug=True, port=80)
def connectToSlack(): return slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
import boto3 import json import logging import os import slack from botocore.vendored import requests from base64 import b64decode from urllib.parse import parse_qs IMG_FLIP_USERNAME = '******' IMG_FLIP_PASSWORD = '******' ENCRYPTED_EXPECTED_TOKEN = os.environ['kmsEncryptedToken'] bot_user_id = 'BOTUSERID' expected_token = 'SLASHTOKEN' client = slack.WebClient(token='BOTTOKEN') kms = boto3.client('kms') #Python3 decrypt doesn't work like it does in python2. Working on using env variables instead of hard coded credentials. #expected_token = kms.decrypt(CiphertextBlob=b64decode(ENCRYPTED_EXPECTED_TOKEN))['Plaintext'] logger = logging.getLogger() logger.setLevel(logging.INFO) def respond(err, res=None): return { 'statusCode': '400' if err else '200', 'body': err.message if err else '', 'headers': { 'Content-Type': 'application/json'
#!/usr/bin/env python3.7 import json import os import random import pprint from datetime import datetime import slack import requests from flask import Flask, request from ctf_time import CTFTime app = Flask(__name__) SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"] client = slack.WebClient(token=SLACK_BOT_TOKEN) active_users = [] chosen_ctf = {} current_voting = {} pp = pprint.PrettyPrinter(indent=4) def get_active_users_from_channel(): pass #client.users_list() @app.route('/vote_upcoming_ctfs', methods=['POST']) def upcoming_ctfs():
#Main #------ # Globals slack_api = "https://slack.com/api" slack_bot_user_oauth_token = os.environ['SLACK_API_TOKEN'] iam_url = os.environ['IAM_URL'] iam_user = os.environ['IAM_USER'] iam_pass = os.environ['IAM_PASS'] iam_client_id = os.environ['IAM_CLIENT_ID'] iam_client_secret = os.environ['IAM_CLIENT_SECRET'] iam_realm = os.environ['IAM_REALM'] iam_ca_file = os.environ['IAM_CA_FILE'] sa_token_file_location = os.environ['SA_TOKEN_FILE_LOCATION'] vault_url = os.environ['VAULT_URL'] # https://x-vault.x-vault:8200 vault_api_version = os.environ['VAULT_API_VERSION'] # v1 vault_api_k8s_login_ep = vault_url + '/' + vault_api_version + '/' + 'auth/kubernetes/login' ssl_context = ssl_lib.create_default_context(cafile=certifi.where()) client = slack.WebClient(token=slack_bot_user_oauth_token, ssl=ssl_context) txtWait = "please wait...." txtBye = "request completed" user_id = "" callback_id = "" #------------------ # DataHolders #------------------ if __name__ == "__main__": app.run(debug=True)
import slack from credentials.keys import * tars_token = keys["slack"] tars_id = keys["tars"] tars = slack.WebClient(token=tars_token) tars.chat_postMessage(channel=tars_id, text="Request office hours.")
from flask import Flask, jsonify import slack import os slack_token = os.environ["SLACK_API_TOKEN"] client = slack.WebClient(token=slack_token, run_async=True) app = Flask(__name__) @app.route("/hide_message", methods=["POST"]) def hide_message(): client.chat_postMessage(channel='#random', ext="Hook hit!!") return jsonify({"status": "Message hidden"}) if __name__ == "__main__": app.run(port="8080")
import os import slack import config client = slack.WebClient(token=os.environ['SLACK_BOT_TOKEN']) response = client.api_call(api_method='chat.postMessage', json={ 'channel': '#test_bot', 'text': "Hello world!" }) print(response)
has_flaky_test = False failure_output = "" flaky_tests_visited = set() for k in problematic_tests.keys(): if did_test_pass(k): has_flaky_test = True failure_output += parse_xml(problematic_tests[k], flaky_tests_visited) if has_flaky_test: output_msg = "``` \n" + get_git_info( CI_TARGET) + "\n" + failure_output + "``` \n" if os.getenv("SLACK_TOKEN"): SLACKTOKEN = os.environ["SLACK_TOKEN"] ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE # Due to a weird interaction between `websocket-client` and Slack client # we need to set the ssl context. See `slackapi/python-slack-sdk/issues/334` client = slack.WebClient(token=SLACKTOKEN, ssl=ssl_context) client.chat_postMessage(channel='test-flaky', text=output_msg, as_user="******") else: print(output_msg) else: print('No flaky tests found.\n') os.remove(os.environ["TMP_OUTPUT_PROCESS_XML"])
def main(): CI_TARGET = "" if len(sys.argv) == 2: CI_TARGET = sys.argv[1] if os.getenv('TEST_TMPDIR') and os.getenv('REPO_URI') and os.getenv( "BUILD_URI"): os.environ["TMP_OUTPUT_PROCESS_XML"] = os.getenv( "TEST_TMPDIR") + "/tmp_output_process_xml.txt" else: print( "Set the env variables TEST_TMPDIR, REPO_URI, and BUILD_URI first." ) sys.exit(0) find_dir = "{}/**/**/**/**/bazel-testlogs/".format( os.environ['TEST_TMPDIR']).replace('\\', '/') if CI_TARGET == "MacOS": find_dir = '${TEST_TMPDIR}/' os.system( 'sh -c "/usr/bin/find {} -name attempt_*.xml > ${{TMP_OUTPUT_PROCESS_XML}}"' .format(find_dir)) # All output of find command should be either failed or flaky tests, as only then will # a test be rerun and have an 'attempt_n.xml' file. problematic_tests holds a lookup # table between the most recent run's xml filepath and the original attempt's failed xml # filepath. problematic_tests = {} with open(os.environ['TMP_OUTPUT_PROCESS_XML'], 'r+') as f: process_find_output(f, problematic_tests) # The logic here goes as follows: If there is a test suite that has run multiple times, # which produces attempt_*.xml files, it means that the end result of that test # is either flaky or failed. So if we find that the last run of the test succeeds # we know for sure that this is a flaky test. has_flaky_test = False failure_output = "" flaky_tests_visited = set() for k in problematic_tests.keys(): if did_test_pass(k): has_flaky_test = True failure_output += parse_xml(problematic_tests[k], flaky_tests_visited) if has_flaky_test: output_msg = "``` \n" + get_git_info( CI_TARGET) + "\n" + failure_output + "``` \n" if os.getenv("SLACK_TOKEN"): SLACKTOKEN = os.environ["SLACK_TOKEN"] ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE # Due to a weird interaction between `websocket-client` and Slack client # we need to set the ssl context. See `slackapi/python-slack-sdk/issues/334` try: client = slack.WebClient(token=SLACKTOKEN, ssl=ssl_context) client.chat_postMessage(channel='test-flaky', text=output_msg, as_user="******") except SlackApiError as e: print("Call to SlackApi failed:", e.response["error"]) print(output_msg) else: print(output_msg) else: print('No flaky tests found.\n') os.remove(os.environ["TMP_OUTPUT_PROCESS_XML"])
import os import sys import slack import argparse if __name__ == "__main__": arg_parser = argparse.ArgumentParser( formatter_class=argparse.MetavarTypeHelpFormatter) arg_parser.add_argument('--token', type=str, required=False, default=os.environ.get("SLACK_API_TOKEN", None), help='slack tocken') arg_parser.add_argument('-d', type=str, required=False, help='channel') args, unknown_args = arg_parser.parse_known_args() if args.token is None: print('SLACK_API_TOKEN is required') sys.exit(-1) msg = ' '.join(unknown_args) client = slack.WebClient(token=args.token) client.chat_postMessage(channel=args.d, text=msg) print('{} -> {}'.format(msg, args.d))
# from pyspark.sql.types import IntegerType # from pyspark.sql.types import StringType # from pyspark.sql.types import ArrayType # from pyspark.sql.types import StructType # from pyspark.sql.types import StructField # from pyspark.sql import SparkSession # from pyspark.conf import SparkConf sign_token = os.environ['SLACK_SIGN_TOKEN'] access_token = os.environ['SLACK_ACCESS_TOKEN'] user_token = os.environ['SLACK_USER_TOKEN'] # user_token = 'SLACK_USER_TOKEN' data_home = os.environ['SLACK_DATA_HOME'] ssl_context = ssl.create_default_context(cafile=certifi.where()) client = slack.WebClient(token=access_token, ssl=ssl_context) # spark = SparkSession.builder.master('local').appName('SlackBot').getOrCreate(); http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) batchtime = datetime.now() # batch = floor(batchtime.timestamp()*1000) batch = batchtime.strftime('%Y%m%d%H%M%S') def get_slackclient(): return client def dd_writemetadata(): os.makedirs(data_home + '/' + batch + '/api') os.makedirs(data_home + '/' + batch + '/csv')
def sendMessage(self, message): if self.debug: return client = slack.WebClient(token=self.slackAPIToken) response = client.chat_postMessage(channel=self.slackChannel, text=message)
import slack, os from socless import socless_bootstrap, socless_template_string SOCLESS_BOT_TOKEN = os.environ.get('SOCLESS_BOT_TOKEN') sc = slack.WebClient(token=SOCLESS_BOT_TOKEN) def find_user(name, page_limit=1000, include_locale='false'): """ Find a user's Slack profile based on their full or display name """ paginate = True next_cursor = '' while paginate: resp = sc.users_list(cursor=next_cursor, limit=page_limit, include_locale=include_locale) data = resp.data next_cursor = resp.data['response_metadata'].get('next_cursor', '') if not next_cursor: paginate = False for user in data['members']: user_names = [ user.get('name'), user.get('real_name'), user.get('profile', {}).get('real_name') ] if name in user_names: return {"found": True, "user": user}
import slack import os import sqlalchemy import time import logging logging.basicConfig(level=logging.DEBUG) # oauth_token = SLACKBOT_TOKEN # this is an environment variable on my local machine # slack_token = os.environ["SLACK_API_TOKEN"] solution to get the environ var oauth_token = "<oauth_token>" client = slack.WebClient(token=oauth_token) # response = client.chat_postMessage( # channel="botchannel", # text="testing! :-)") # Connect to the PostgreSQL container # Declare postgres config HOST = 'mypg' USERNAME = '******' PORT = '5432' DB = 'postgres' PASSWORD = '******' # Create a postgres connection and assign it to 'engine' variable engine = sqlalchemy.create_engine( f'postgres://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DB}') # Retrieve last tweet and sentiment using SQLAlchemy # SELECT * FROM tweets ORDER BY id DESC LIMIT 1; #tweet_to_bot = engine.select([tweets]).order_by(db.desc(tweets.columns.id).limit(1))
def _slack_client() -> _slack.WebClient: bot_token = _get_token() return _slack.WebClient(token=bot_token)
def sendSlack(message, channel): client = slack.WebClient(token=settings.SLACK_FRIENDBETS) response = client.chat_postMessage(channel=channel, text=message) return message
from slackbot1 import tokens as t # Emotional sentiments analyser bot # tokens Access_Token = t.getaccesstoken() Event_Token = t.getEventToken() # making a flask connection app = Flask(__name__) # slack event api connection slack_adapter = SlackEventAdapter(Event_Token, "/slack/event", app) # slack Bot connection client = slack.WebClient(token=Access_Token) Bot_id = client.api_call('auth.test')['user_id'] def sentiment_analyse(sentiment_text): score = SentimentIntensityAnalyzer().polarity_scores(sentiment_text) if score['neg'] > score['pos']: return "Negative Sentiment" elif score['neg'] < score['pos']: return "Positive Sentiment" else: return "Neutral Sentiment" # get the payload from the user
identifier = "@CT{}:".format(ctid) date = "" time_in = "" command_list = [] level = 0 # checks if new command exists and researchers needs to be notified mail_new_command = "" # stores email to be sent #EMAIL = os.getenv('HP_EMAIL') # gets slack token TOKEN = os.getenv('SLACK_TOKEN') slack_client = slack.WebClient(token=TOKEN) # filepath for MITM sessions (uses argument given) filepath = "/root/MITM_data/sessions/{}.gz".format(session) # unzips and opens session file try: with gzip.open(filepath, "rt", encoding="utf-8") as file: line = file.readline() while line: #ansi_escape = re.compile(r'\x1B[@-_][0-?]*[ -/]*[@-~]') #line = ansi_escape.sub('', line) #line = line.replace("\x08", "").replace("\x07", "").strip() if "Date: " in line: # extracts date from 8th line in YYYY-MM-DD format date = line.split(" ")[1]
def setUp(self): self.client = slack.WebClient("xoxb-abc-123", loop=asyncio.get_event_loop())
def get_my_user_id(slack_api_token): """ Get bot user id as per https://api.slack.com/methods/auth.test """ return slack.WebClient(slack_token).auth_test()['user_id']