from slack import WebClient import os from dotenv import load_dotenv load_dotenv() slack_client = WebClient(token=os.environ['SLACK_API_TOKEN']) slack_client.chat_postMessage(channel='#web-monitor', text="Hello!") # slack_client.chat_postMessage(channel='#general', text="Hello!")
def test_timeout_issue_712(self): client = WebClient(base_url="http://localhost:8888", timeout=1) with self.assertRaises(socket.timeout): client.users_list(token="xoxb-timeout")
else: for x, y in zip(request_hash, signature): result |= ord(x) ^ ord(y) return result == 0 # --------------------- # Slack WebClient # --------------------- import os from slack import WebClient from slack.errors import SlackApiError client = WebClient(token=os.environ["SLACK_API_TOKEN"]) # --------------------- # Flask App # --------------------- # pip3 install flask from flask import Flask, request, make_response app = Flask(__name__) signing_secret = os.environ["SLACK_SIGNING_SECRET"] @app.route("/slack/events", methods=["POST"]) def slack_app(): if not verify_request(
import random from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.core.cache import caches from django.conf import settings from slack import WebClient from slack.web.classes.interactions import MessageInteractiveEvent from botcommands.views import get_lobby_block_content from actions.board_management import get_game_board from botcommands.models import Character, User, GameStage SLACK_VERIFICATION_TOKEN = getattr(settings, 'SLACK_VERIFICATION_TOKEN', None) SLACK_BOT_USER_TOKEN = getattr(settings, 'SLACK_BOT_USER_TOKEN', None) Client = WebClient(SLACK_BOT_USER_TOKEN) class Actions(APIView): def post(self, request, *args, **kwargs): try: json_data = json.loads(request.data['payload']) data = MessageInteractiveEvent(json_data) channel = data.channel.id game = caches['default'].get(channel) if not game: # Client.chat_postMessage(channel=channel, text="Can't find game?!?!") game = None else: game.player_list = game.player_list
from slack import WebClient import os from dotenv import load_dotenv load_dotenv() slack_client = WebClient(token=os.environ['SLACK_API_TOKEN']) print(slack_client.api_test()) # Fetch channels through conversation_list API conversations_list = slack_client.conversations_list( types="public_channel, private_channel" ) # PRint channels if conversations_list.get('ok'): channels_list = conversations_list['channels'] for channel in channels_list: print(channel['name'] + " (" + channel['id'] + ")")
@app.route("/",methods = ["POST"]) def test(): data = request.data.decode("utf-8") data = json.loads(data) if "challenge" in data: token = token = str(data['challenge']) return Response(token, mimetype='text/plane') return 0 """ # Create an events adapter and register it to an endpoint in the slack app for event injestion. slack_events_adapter = SlackEventAdapter(os.environ.get("SLACK_EVENTS_TOKEN"), "/slack/events", app) # Initialize a Web API client slack_web_client = WebClient(token=os.environ.get("SLACK_TOKEN")) url = os.environ.get("DB_URL") #作ったテーブル:create table news(id serial primary key, news_address text, users_id varchar(20), tag varchar(100)); @slack_events_adapter.on("message") def handle_message(event_data): message = event_data["event"] if request.headers.get("X-Slack-Retry-Num"): return {"statusCode": 200, "body": ""} if message.get("bot_id") is None: channel = message["channel"]
members = set(channel_info['members']) members.remove(my_id) if len(members) > 1: members.remove(user) reply_message = generate_reply_message(user, next_writer(members)) reply_broadcast = 'True' for mkw in mute_keywords: if mkw in text: reply_broadcast = 'False' break web_client.api_call('chat.postMessage', params={ 'channel': channel_id, 'text': reply_message, 'thread_ts': thread_ts, 'reply_broadcast': reply_broadcast, }) if __name__ == '__main__': with open(token_file, 'r') as f: slack_token = f.readline() web_client = WebClient(token=slack_token) my_id = web_client.api_call('auth.test')['user_id'] rtm_client = RTMClient(token=slack_token) print('Running...') rtm_client.start()
import os from flask import Flask from flask_pymongo import PyMongo from slack import WebClient app = Flask(__name__) app.config['MONGO_URI'] = os.environ.get('MONGO_URI') mongo = PyMongo(app) client = WebClient(token=os.environ.get('SLACK_TOKEN')) @app.route('/current-turn', methods=['POST', 'GET']) def current_turn(): backend = current_user_for('backend') frontend = current_user_for('frontend') pair = backend['name'] + ' - ' + frontend['name'] return pair @app.route('/next-turn', methods=['POST', 'GET']) def next_turn(): backend = next_user_for('backend') frontend = next_user_for('frontend') pair = backend['name'] + ' - ' + frontend['name'] assign_new_topic_on_channels(pair) return pair def next_user_for(team): current = current_user_for(team) next = find_user(team, current[team + '_id'] + 1)
def slackNotification(token, channel, text): client = WebClient(token=token) client.chat_postMessage(channel=channel, text=text, username="******", icon_emoji=":rabbit2:")
def _get_client(self, team_id: str) -> WebClient: bot_token = Team.objects.get(id=team_id).bot_token return WebClient(token=bot_token)
def main(): #Set XOXP app token as environmentable variable client = WebClient(token=os.environ['SLACK_TOKEN']) #variables to hold triage channel ID #You can get the ids of your public and private channel by calling the #conversations.list method on your Slack workspace. Make sure your bot # a member of the channels you want to receive the ids from public_Triage = 'C018PPTV8VC' #enter id of public Triage channel private_Triage = 'G018FQ033PZ' #enter id of private Triage channel def message_search(): '''search through channel message and select messages without reactions and check those with reactions if they have the ":heart:" emoji. The heart emoji states that a task has been handled by a Slack administrator''' #Get message history of the triage channel hist_Triage_Channel = client.conversations_history(channel=public_Triage) #variable to hold status of the channel if it has more messages to rotate through has_more =True #Variable list to hold messages unique ids mess_ID = [] try: while has_more: for messages in hist_Triage_Channel['messages']: emoji_List = [] '''Test to see if message has a emoji reaction''' if messages.get('reactions',0) != 0: '''if the message has an emoji reaction add them to the emoji_List list''' for emoji in messages['reactions']: emoji_List.append(emoji['name']) '''If we dont find the heart emoji the message hasn't been looked at and the team needs to be aware. If you want to use a different emoji change the name below''' if 'heart' not in emoji_List: mess_ID.append(messages['ts']) else: '''if there is no emoji in messages the post has not been addresed by the team''' mess_ID.append(messages['ts']) '''checking to see if there is more messages to search through''' if hist_Triage_Channel['has_more']: '''if true receive next set of channel messages''' hist_Triage_Channel = client.conversations_history(channel=public_Triage,cursor=\ hist_Triage_Channel['response_metadata']\ ['next_cursor']) else: '''There is no more messages to rotate through so close loop by updated the variable has_more''' has_more= False except SlackApiError as e: print(e) return mess_ID def results(message_ts_list): '''Take the results of messages search function and post messages in private triage channel of items that still need to be addressed''' #Markdown message header mkdm_msg_header = f":rotating_light:The following requests need :eyes: on them. Please see the links below :rotating_light:" mkdm_message='' try: for m in message_ts_list: while len(mkdm_message) < 2000: #Create a clickable link to the messages that need to be addressed message_link = client.chat_getPermalink(channel=public_Triage,message_ts=m) mkdm_message += '<' + str(message_link['permalink']) + '| message >' + '\n' break triage_message = triage_message = [{"type": "section","text":{"type": "mrkdwn","text": \ f'{ mkdm_msg_header } \n {mkdm_message}'}}] client.chat_postMessage(channel=private_Triage,blocks=triage_message,username='******') except Exception as e: print(e) return mkdm_message results(message_search())
DEBUG = os.getenv('DEBUG') PORT = os.getenv('PORT') REDIS_URL = os.getenv('REDIS_URL') MAX_MESSAGES = int(os.getenv('MAX_MESSAGES', 10)) MIRROR_CHANNEL = os.getenv('MIRROR_CHANNEL') SLACK_SIGNING_SECRET = os.getenv('SLACK_SIGNING_SECRET') app = Flask('slackmirror') app.logger.setLevel(os.getenv('LOG_LEVEL', 'DEBUG')) if not DEBUG: json_logging.init_flask(enable_json=True) json_logging.init_request_instrument(app) slack_client = WebClient(os.getenv('SLACK_BOT_TOKEN')) slack_events_adapter = SlackEventAdapter(SLACK_SIGNING_SECRET, "/slack/events", server=app) CORS(app) logging.getLogger('flask_cors').level = logging.DEBUG r = redis.Redis().from_url(REDIS_URL) cache = Dict(key='cache', redis=r) messages = Deque(key='messages', redis=r, maxlen=MAX_MESSAGES) def replace_slack_tags(t): t = re.sub(r'<@([a-zA-Z0-9]+)>', replace_user_id_with_name, t) t = re.sub(r':([a-zA-Z0-9_-]+)(::[a-zA-Z0-9_-])?:', replace_coloncode_to_emoji, t) t = re.sub(r'<(https?://.+?)\|([^>]+?)>', rf'<a href="\1" target="_blank">\2</a>', t) t = re.sub(r'<(https?://.+?)>', rf'<a href="\1" target="_blank">\1</a>', t) t = re.sub('<#[a-zA-Z0-9]+\|([a-zA-Z0-9æøåÅÆØäöÄÖ\-_]+)>', r"#\1", t) t = re.sub(r'\n{3,}', "\n\n", t)
class SlackService: def __init__(self, config): self.config = config self.logger = logging.getLogger(__name__) with open("slack_token.txt", "r") as slack_token: self.slack_token = slack_token.read() self.slack_client = WebClient(token=self.slack_token) self.channel = config.get_section_dict("App")["SlackChannel"] self.username = "******" self.icon_emoji = ":robot_face:" def post_message(self, msg, recipient): return self.slack_client.chat_postMessage(channel=recipient, text=msg) def post_message_to_channel(self, msg, channel): self.logger.info(f"Posting to {channel}") return self.slack_client.chat_postMessage(channel=channel, text=msg, username=self.username, parse='full') def file_upload(self, file_content, file_name, file_type, title=None): return self.slack_client.files_upload( channels=self.channel, content=file_content, filename=file_name, filetype=file_type, initial_comment='{} Log File'.format(file_name), title=title) def user_info(self, uid): return self.slack_client.users_info(user=uid, token=self.slack_token) def violation_report(self, entity_info, number): entity_id, entity_type, entity_name = entity_info['id'], entity_info[ 'type'], entity_info['name'] msg = f"We found {number} violations in {entity_id}: {entity_name} ({entity_type})" self.post_message_to_channel(msg, self.channel) def daily_report(self, entity_info, number): entity_id, entity_type, entity_name = entity_info['id'], entity_info[ 'type'], entity_info['name'] msg = f"Yesterday we found {number} violations in {entity_id}: {entity_name} ({entity_type})." self.post_message_to_channel(msg, self.channel) def occupancy_alert(self, entity_info, number, threshold): entity_id, entity_type = entity_info['id'], entity_info['type'] entity_name = entity_info['name'] msg = f"Occupancy threshold was exceeded in {entity_type} {entity_id}: {entity_name}." \ f"We found {number} people out of a capacity of {threshold}." self.post_message_to_channel(msg, self.channel) def send_global_report(self, report_type, sources, areas, sources_violations_per_hour, areas_violations_per_hour): msg = f"*{report_type.capitalize()} Report:* \n\n" msg += "*Areas:*\n" for index, area in enumerate(areas): entity_id, entity_name = area['id'], area['name'] msg += f"*{entity_id}:* {entity_name} - {sum(areas_violations_per_hour[index])} Violations\n" msg += "\n*Cameras:*\n" for index, source in enumerate(sources): entity_id, entity_name = source['id'], source['name'] msg += f"*{entity_id}:* {entity_name} - {sum(sources_violations_per_hour[index])} Violations\n" self.post_message_to_channel(msg, self.channel)
async def issue_645(): client = WebClient(base_url="http://localhost:8888", timeout=1, run_async=True) try: await client.users_list(token="xoxb-timeout") except asyncio.TimeoutError: pass
import sqlite3 from dotenv import find_dotenv, load_dotenv # pip install python-dotenv from gazpacho import Soup from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options from slack import WebClient # pip install slackclient from slack.errors import SlackApiError import pandas as pd load_dotenv(find_dotenv()) options = Options() options.headless = True slack_token = os.environ["SLACK_API_TOKEN"] client = WebClient(token=slack_token) browser = Firefox(executable_path="/usr/local/bin/geckodriver", options=options) con = sqlite3.connect("games.db") cur = con.cursor() def make_soup(): url = 'https://www.amazon.ca/hz/wishlist/ls/17CRUYWGYZ5Y2' browser.get(url) html = browser.page_source soup = Soup(html) return soup def parse_item(item): title = item.find('a', {'id': 'itemName'}, strict=False).attrs['title'] price = float(item.find('span', {'class': 'a-offscreen'}).text.split('\xa0')[-1])
from flask import jsonify from slack import WebClient from slack.signature import SignatureVerifier from dotenv import load_dotenv load_dotenv() SLACK_BOT_NAME = os.environ["SLACK_BOT_NAME"] SLACK_BOT_USER_TOKEN = os.environ["SLACK_BOT_USER_TOKEN"] SLACK_SIGNING_SECRET = os.environ["SLACK_SIGNING_SECRET"] SLACK_CLIENT_ID = os.environ["SLACK_CLIENT_ID"] SLACK_CLIENT_SECRET = os.environ["SLACK_CLIENT_SECRET"] REQUEST_TOKEN = os.environ["REQUEST_TOKEN"] MODEL_ENDPOINT = os.environ["MODEL_ENDPOINT"] STAGE = os.environ.get("STAGE", None) slack_client = WebClient(token=SLACK_BOT_USER_TOKEN) signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"]) def form_response(status_code, body): return jsonify({ "isBase64Encoded": True, "statusCode": status_code, "headers": { "Content-Type": "application/json" }, "body": body }) def handle_slack_request(request):
def setUp(self): self.logger = logging.getLogger(__name__) self.user_token = os.environ[SLACK_SDK_TEST_USER_TOKEN] self.sync_client: WebClient = WebClient(token=self.user_token, run_async=False) self.async_client: WebClient = WebClient(token=self.user_token, run_async=True)
def slack_client(self): return WebClient(self.bot_access_token)
import logging logging.basicConfig(level=logging.DEBUG) import os from slack import WebClient from slack.errors import SlackApiError from taiga.projects.models import Project, TaskStatus slack_token = os.environ["SLACK_API_TOKEN"] client = WebClient(token=slack_token) def send_slack_notification(request, obj): try: old_status = obj.status new_status_id = request.DATA.get('status', None) new_status = TaskStatus.objects.get(pk=new_status_id) task_id = obj.ref task_name = obj.subject response = client.chat_postMessage( channel="U015GFCDKBN", text= f"status for the task {task_id} - {task_name} changed from {old_status.name} to {new_status.name}" # text="hello there" ) except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response[ "error"] # str like 'invalid_auth', 'channel_not_found'
"loggers": { "django": { "handlers": ["console"], "level": env("DJANGO_LOG_LEVEL", default="INFO"), } }, } DELETE_FORBIDDEN = ["UBZ2414LW"] ERROR_ICON_URL = env("ERROR_ICON_URL", None) PRAW_CLIENT_ID = env("PRAW_CLIENT_ID") PRAW_CLIENT_SECRET = env("PRAW_CLIENT_SECRET") PRAW_USER_AGENT = env( "PRAW_USER_AGENT", default=f"turbot-slack by /u/{env('REDDIT_USERNAME', 'unknown')}") REDDIT_SUBMISSION_CACHE_COUNT = env("REDDIT_SUBMISSION_CACHE_COUNT", default=5) SLACK_CLIENT = WebClient(SLACK_API_TOKEN) NIGHT_START = parser.parse(env("NIGHT_START", default="23:00")).time() NIGHT_END = parser.parse(env("NIGHT_END", default="09:00")).time() PHOTO_FSTRING = env("PHOTO_FSTRING", default="https://picsum.photos/200") REDDIT_VALID_EXTENSION = ["jpg", "png", "gif"] TURBOT_USER_ID = env("TURBOT_USER_ID")
import sys import logging sys.path.insert(1, f"{__file__}/../../..") logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # export SLACK_API_TOKEN=xoxb-*** # echo 'Hello world!' > tmp.txt # python3 tests/samples/basic_usage/uploading_files.py import os from slack import WebClient client = WebClient(token=os.environ["SLACK_API_TOKEN"]) channels = ",".join(["#random"]) filepath = "./tmp.txt" response = client.files_upload(channels=channels, file=filepath)
from flask_sqlalchemy import SQLAlchemy from slack import WebClient from environment import SLACK_BOT_TOKEN # These are declared here rather than __init__.py to prevent circular imports. db = SQLAlchemy() client = WebClient(token=SLACK_BOT_TOKEN)
from flask import Flask from slack import WebClient from slackeventsapi import SlackEventAdapter from scipy.sparse import lil_matrix # slack 연동 정보 입력 부분 SLACK_TOKEN = os.getenv('SLACK_TOKEN') SLACK_SIGNING_SECRET = os.getenv('SLACK_SIGNING_SECRET') return_text = "" app = Flask(__name__) slack_events_adaptor = SlackEventAdapter(SLACK_SIGNING_SECRET, "/listening", app) slack_web_client = WebClient(token=SLACK_TOKEN) # Req 2-2-1. pickle로 저장된 model.clf 파일 불러오기 with open('model.clf', 'rb') as f: model = pickle.load(f) word_indices = model.get_word_indices() naive = model.get_naive_model() logi = model.get_logistic_model() knn = model.get_k_neighbors_model() # Req 2-2-2. 토큰화 및 one-hot 임베딩하는 전 처리 def preprocess(slack_str): X_test = lil_matrix((1, len(word_indices) + 1), dtype=int)
def setUp(self): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] self.sync_client: WebClient = WebClient(token=self.bot_token, run_async=False, loop=asyncio.new_event_loop()) self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True)
class TestWebClient(unittest.TestCase): def setUp(self): setup_mock_web_api_server(self) self.client = WebClient( token="xoxp-1234", base_url="http://localhost:8888", ) self.async_client = WebClient( token="xoxp-1234", run_async=True, base_url="http://localhost:8888", ) def tearDown(self): cleanup_mock_web_api_server(self) pattern_for_language = re.compile("python/(\\S+)", re.IGNORECASE) pattern_for_package_identifier = re.compile("slackclient/(\\S+)") def test_api_calls_return_a_response_when_run_in_sync_mode(self): self.client.token = "xoxb-api_test" resp = self.client.api_test() self.assertFalse(asyncio.isfuture(resp)) self.assertTrue(resp["ok"]) def test_api_calls_include_user_agent(self): self.client.token = "xoxb-api_test" resp = self.client.api_test() self.assertEqual(200, resp.status_code) @async_test async def test_api_calls_return_a_future_when_run_in_async_mode(self): self.client.token = "xoxb-api_test" self.client.run_async = True future = self.client.api_test() self.assertTrue(asyncio.isfuture(future)) resp = await future self.assertEqual(200, resp.status_code) self.assertTrue(resp["ok"]) def test_builtin_api_methods_send_json(self): self.client.token = "xoxb-api_test" resp = self.client.api_test(msg="bye") self.assertEqual(200, resp.status_code) self.assertEqual("bye", resp["args"]["msg"]) def test_requests_can_be_paginated(self): self.client.token = "xoxb-users_list_pagination" users = [] for page in self.client.users_list(limit=2): users = users + page["members"] self.assertTrue(len(users) == 4) def test_response_can_be_paginated_multiple_times(self): self.client.token = "xoxb-channels_list_pagination" # This test suite verifies the changes in #521 work as expected response = self.client.channels_list(limit=1) ids = [] for page in response: ids.append(page["channels"][0]["id"]) self.assertEqual(ids, ["C1", "C2", "C3"]) # The second iteration starting with page 2 # (page1 is already cached in `response`) self.client.token = "xoxb-channels_list_pagination2" ids = [] for page in response: ids.append(page["channels"][0]["id"]) self.assertEqual(ids, ["C1", "C2", "C3"]) def test_request_pagination_stops_when_next_cursor_is_missing(self): self.client.token = "xoxb-users_list_pagination_1" users = [] for page in self.client.users_list(limit=2): users = users + page["members"] self.assertTrue(len(users) == 2) def test_response_can_be_paginated_multiple_times_use_sync_aiohttp(self): self.client = WebClient( token="xoxp-1234", base_url="http://localhost:8888", run_async=False, use_sync_aiohttp=True, ) self.client.token = "xoxb-channels_list_pagination" # This test suite verifies the changes in #521 work as expected response = self.client.channels_list(limit=1) ids = [] for page in response: ids.append(page["channels"][0]["id"]) self.assertEqual(ids, ["C1", "C2", "C3"]) # The second iteration starting with page 2 # (page1 is already cached in `response`) self.client.token = "xoxb-channels_list_pagination2" ids = [] for page in response: ids.append(page["channels"][0]["id"]) self.assertEqual(ids, ["C1", "C2", "C3"]) def test_json_can_only_be_sent_with_post_requests(self): with self.assertRaises(err.SlackRequestError): self.client.api_call("fake.method", http_verb="GET", json={}) def test_slack_api_error_is_raised_on_unsuccessful_responses(self): self.client.token = "xoxb-api_test_false" with self.assertRaises(err.SlackApiError): self.client.api_test() self.client.token = "xoxb-500" with self.assertRaises(err.SlackApiError): self.client.api_test() def test_slack_api_rate_limiting_exception_returns_retry_after(self): self.client.token = "xoxb-rate_limited" try: self.client.api_test() except err.SlackApiError as slack_api_error: self.assertFalse(slack_api_error.response["ok"]) self.assertEqual(429, slack_api_error.response.status_code) self.assertEqual( 30, int(slack_api_error.response.headers["Retry-After"])) def test_the_api_call_files_argument_creates_the_expected_data(self): self.client.token = "xoxb-users_setPhoto" resp = self.client.users_setPhoto(image="tests/data/slack_logo.png") self.assertEqual(200, resp.status_code) def test_issue_560_bool_in_params_sync(self): self.client.token = "xoxb-conversations_list" self.client.conversations_list(exclude_archived=1) # ok self.client.conversations_list(exclude_archived="true") # ok self.client.conversations_list(exclude_archived=True) # ok @async_test async def test_issue_560_bool_in_params_async(self): self.async_client.token = "xoxb-conversations_list" await self.async_client.conversations_list(exclude_archived=1) # ok await self.async_client.conversations_list(exclude_archived="true" ) # ok await self.async_client.conversations_list(exclude_archived=True ) # TypeError def test_issue_690_oauth_v2_access(self): self.client.token = "" resp = self.client.oauth_v2_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): self.client.oauth_v2_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_issue_690_oauth_v2_access_async(self): self.async_client.token = "" resp = await self.async_client.oauth_v2_access( client_id="111.222", client_secret="secret", code="codeeeeeeeeee", ) self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): await self.async_client.oauth_v2_access( client_id="999.999", client_secret="secret", code="codeeeeeeeeee", ) def test_issue_690_oauth_access(self): self.client.token = "" resp = self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_issue_690_oauth_access_async(self): self.async_client.token = "" resp = await self.async_client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): await self.async_client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") def test_issue_705_no_param_request_pagination(self): self.client.token = "xoxb-users_list_pagination" users = [] for page in self.client.users_list(): users = users + page["members"] self.assertTrue(len(users) == 4) def test_token_param(self): client = WebClient(base_url="http://localhost:8888") with self.assertRaises(err.SlackApiError): client.users_list() resp = client.users_list(token="xoxb-users_list_pagination") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): client.users_list() @async_test async def test_token_param_async(self): client = WebClient(base_url="http://localhost:8888", run_async=True) with self.assertRaises(err.SlackApiError): await client.users_list() resp = await client.users_list(token="xoxb-users_list_pagination") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): await client.users_list() def test_timeout_issue_712(self): client = WebClient(base_url="http://localhost:8888", timeout=1) with self.assertRaises(socket.timeout): client.users_list(token="xoxb-timeout") @async_test async def test_timeout_issue_712_async(self): client = WebClient(base_url="http://localhost:8888", timeout=1, run_async=True) with self.assertRaises(asyncio.TimeoutError): await client.users_list(token="xoxb-timeout") def test_unclosed_client_session_issue_645_in_async_mode(self): def exception_handler(_, context): nonlocal session_unclosed if context["message"] == "Unclosed client session": session_unclosed = True async def issue_645(): client = WebClient(base_url="http://localhost:8888", timeout=1, run_async=True) try: await client.users_list(token="xoxb-timeout") except asyncio.TimeoutError: pass session_unclosed = False loop = asyncio.get_event_loop() loop.set_exception_handler(exception_handler) loop.run_until_complete(issue_645()) gc.collect() # force Python to gc unclosed client session self.assertFalse(session_unclosed, "Unclosed client session") def test_html_response_body_issue_718(self): client = WebClient(base_url="http://localhost:8888") try: client.users_list(token="xoxb-html_response") self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertTrue( str(e).startswith( "Failed to parse the response body: Expecting value: line 1 column 1 (char 0)" ), e) @async_test async def test_html_response_body_issue_718_async(self): client = WebClient(base_url="http://localhost:8888", run_async=True) try: await client.users_list(token="xoxb-html_response") self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertTrue( str(e).startswith( "Failed to parse the response body: Expecting value: line 1 column 1 (char 0)" ), e) def test_user_agent_customization_issue_769(self): client = WebClient( base_url="http://localhost:8888", token="xoxb-user-agent this_is test", user_agent_prefix="this_is", user_agent_suffix="test", ) resp = client.api_test() self.assertTrue(resp["ok"]) @async_test async def test_user_agent_customization_issue_769_async(self): client = WebClient( run_async=True, base_url="http://localhost:8888", token="xoxb-user-agent this_is test", user_agent_prefix="this_is", user_agent_suffix="test", ) resp = await client.api_test() self.assertTrue(resp["ok"]) def test_issue_809_filename_for_IOBase(self): self.client.token = "xoxb-api_test" file = io.BytesIO(b'here is my data but not sure what is wrong.......') resp = self.client.files_upload(file=file) self.assertIsNone(resp["error"])
def multiregion(event): """ shows information for a given user's workspace need to pass username in the event """ logger.debug("workspaces.info.multiregion() starting") configuration = event.get('configuration', {}) user_workspaces = [] for region in configuration.get('regions'): # need to get the directoryid for each region if not configuration.get('directorymap', {}).get(region): logger.error(f"Couldn't find directoryid for region '{region}' in workspaces.info.multiregion()") continue try: session = Session( region_name=region ) except Exception as ERROR: # pylint: disable=broad-except,invalid-name logger.error(f"Failed to instantiate session with region {region}: {ERROR}") return False try: client = session.client('workspaces') findworkspace = client.describe_workspaces( DirectoryId=configuration.get('directorymap', {}).get(region), UserName=event.get('username'), ) if findworkspace.get('Workspaces'): for workspace in findworkspace.get('Workspaces'): wsid = workspace.get('WorkspaceId') state = workspace.get('State') bundlename = get_bundle_name(workspace.get('BundleId')) user_workspaces.append(f"{wsid} in state {state} (Region: {region} Bundle: {bundlename})") #pylint: disable=line-too-long except Exception as e: # pylint: disable=broad-except,invalid-name logger.error(f"ERROR: {e}") return False # message the user with the results slackclient = WebClient(token=configuration.get('slacktoken')) logger.debug("Messaging user to advise...") if not user_workspaces: slackclient.chat_postEphemeral( channel=configuration.get('channel_id'), user=configuration.get('user_id'), text=f"No workspaces found for username {event.get('username')}" ) else: blocks = [ { "type": "section", "text": { "type": "mrkdwn", "text": f"Workspace information for user {event.get('username')}" } }, ] for workspace in user_workspaces: blocks.append({ "type": "section", "text": { "type": "mrkdwn", "text": f"• {workspace}" } }) logger.debug(slackclient.chat_postEphemeral( channel=configuration.get('channel_id'), user=configuration.get('user_id'), blocks=blocks, )) return True
async def test_timeout_issue_712_async(self): client = WebClient(base_url="http://localhost:8888", timeout=1, run_async=True) with self.assertRaises(asyncio.TimeoutError): await client.users_list(token="xoxb-timeout")
import os import sys from astropy.time import Time import traceback import time from penquins import Kowalski from functions_misc import make_triplet, plot_triplet, get_cutouts from functions_misc import get_dust_info, plot_lc from functions_misc import get_xmatch_clu_glade, get_bgal_ebv slack_token = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".slack_access_token.txt") with open(slack_token, "r") as f: access_token = f.read() web_client = WebClient(token=access_token) def upload_fig(fig, user, filename, channel_id): imgdata = io.BytesIO() fig.savefig(imgdata, format='png', dpi=600, transparent=True) imgdata.seek(0) #wc = WebClient(token=bot_access_token) attmpt = 0 while attmpt < 5: try: web_client.files_upload( file=imgdata.getvalue(), filename=filename, channels=channel_id, text="<@{0}>, here's the file {1} I've uploaded for you!".format(user, filename) )
import logging logging.basicConfig(level=logging.DEBUG) import os from slack import WebClient from slack.errors import SlackApiError slack_token = os.environ["SLACK_BOT_TOKEN"] client = WebClient(token=slack_token) client. try: response = client.chat_postMessage( channel="C0XXXXXX", text="Hello from your app! :tada:" ) except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' print(client.rtm_read())
from flask import Flask from slack import WebClient from slackeventsapi import SlackEventAdapter # Flaskを作ってgunicornで動くようにする app = Flask(__name__) # Events APIの準備 slack_signing_secret = os.environ["SLACK_SIGNING_SECRET"] slack_events_adapter = SlackEventAdapter(slack_signing_secret, "/slack/events", app) # Web Client APIの準備 slack_bot_token = os.environ["SLACK_BOT_TOKEN"] slack_client = WebClient(slack_bot_token) # ref:https://github.com/slackapi/python-slack-events-api/blob/main/example/example.py @slack_events_adapter.on("message") def handle_message(event_data): message = event_data["event"] # 普通のメッセージかつテキスト内に"hi"がある場合に返答する if message.get("subtype") is None and "hi" in message.get("text"): channel = message["channel"] message = "Hello <@{}>! :tada:".format(message["user"]) slack_client.chat_postMessage(channel=channel, text=message) # エラー時のイベントのハンドリング