def test_installation_store_conflicts(self): store1 = FileInstallationStore() store2 = FileInstallationStore() app = AsyncApp( signing_secret="valid", oauth_settings=AsyncOAuthSettings( client_id="111.222", client_secret="valid", installation_store=store1, ), installation_store=store2, ) assert app.installation_store is store1 app = AsyncApp( signing_secret="valid", oauth_flow=AsyncOAuthFlow( settings=AsyncOAuthSettings( client_id="111.222", client_secret="valid", installation_store=store1, ) ), installation_store=store2, ) assert app.installation_store is store1 app = AsyncApp( signing_secret="valid", oauth_flow=AsyncOAuthFlow( settings=AsyncOAuthSettings(client_id="111.222", client_secret="valid",) ), installation_store=store1, ) assert app.installation_store is store1
async def test_lazy(self): async def just_ack(ack): await ack() async def async1(say): await asyncio.sleep(0.3) await say(text="lazy function 1") async def async2(say): await asyncio.sleep(0.5) await say(text="lazy function 2") app = AsyncApp( client=self.web_client, signing_secret=self.signing_secret, ) app.action("a")( ack=just_ack, lazy=[async1, async2], ) request = self.build_valid_request() response = await app.async_dispatch(request) assert response.status == 200 await asyncio.sleep(1) # wait a bit assert self.mock_received_requests["/chat.postMessage"] == 2
def test_authorize_conflicts(self): oauth_settings = AsyncOAuthSettings( client_id="111.222", client_secret="valid", installation_store=FileInstallationStore(), state_store=FileOAuthStateStore(expiration_seconds=120), ) # no error with this AsyncApp(signing_secret="valid", oauth_settings=oauth_settings) def authorize() -> AuthorizeResult: return AuthorizeResult(enterprise_id="E111", team_id="T111") with pytest.raises(BoltError): AsyncApp( signing_secret="valid", authorize=authorize, oauth_settings=oauth_settings, ) oauth_flow = AsyncOAuthFlow(settings=oauth_settings) # no error with this AsyncApp(signing_secret="valid", oauth_flow=oauth_flow) with pytest.raises(BoltError): AsyncApp(signing_secret="valid", authorize=authorize, oauth_flow=oauth_flow)
async def test_default(self): async def failing_listener(): raise Exception("Something wrong!") app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret,) app.action("a")(failing_listener) request = self.build_valid_request() response = await app.async_dispatch(request) assert response.status == 500
def test_valid_multi_auth(self): app = AsyncApp( signing_secret="valid", oauth_settings=AsyncOAuthSettings( client_id="111.222", client_secret="valid" ), ) assert app != None
def test_valid_multi_auth_secret_absence(self): with pytest.raises(BoltError): AsyncApp( signing_secret="valid", oauth_settings=AsyncOAuthSettings( client_id="111.222", client_secret=None ), )
def test_valid_multi_auth_oauth_flow(self): oauth_flow = AsyncOAuthFlow( client_id="111.222", client_secret="valid", installation_store=FileInstallationStore(), oauth_state_store=FileOAuthStateStore(expiration_seconds=120), ) app = AsyncApp(signing_secret="valid", oauth_flow=oauth_flow) assert app != None
async def test_unhandled_errors(self): app = AsyncApp( client=self.web_client, signing_secret=self.signing_secret, raise_error_for_unhandled_request=True, ) response = await app.async_dispatch(self.build_valid_request()) assert response.status == 404 assert response.body == '{"error": "unhandled request"}' @app.error async def handle_errors(error): assert isinstance(error, BoltUnhandledRequestError) return BoltResponse(status=404, body="TODO") response = await app.async_dispatch(self.build_valid_request()) assert response.status == 404 assert response.body == "TODO"
async def test_custom(self): async def error_handler(logger, payload, response): logger.info(payload) response.headers["x-test-result"] = ["1"] async def failing_listener(): raise Exception("Something wrong!") app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret,) app.error(error_handler) app.action("a")(failing_listener) request = self.build_valid_request() response = await app.async_dispatch(request) assert response.status == 500 assert response.headers["x-test-result"] == ["1"]
async def test_unhandled_errors_process_before_response_no_next(self): app = AsyncApp( client=self.web_client, signing_secret=self.signing_secret, raise_error_for_unhandled_request=True, process_before_response=True, ) @app.middleware async def broken_middleware(): pass response = await app.async_dispatch(self.build_valid_request()) assert response.status == 404 assert response.body == '{"error": "no next() calls in middleware"}' @app.error async def handle_errors(error): assert isinstance(error, BoltUnhandledRequestError) return BoltResponse(status=404, body="TODO") response = await app.async_dispatch(self.build_valid_request()) assert response.status == 404 assert response.body == "TODO"
import asyncio import logging import os import json from typing import Any from azure_notifications.config import SERVER_PORT, BOT_SERVICE_CHANNEL from azure_notifications.worker import preprocess_slack_event, work from slack_bolt.async_app import AsyncApp from slack_sdk.web.async_client import AsyncWebClient logging.basicConfig(level=os.getenv("LOG_LEVEL") or logging.INFO) save_events = False slack = AsyncApp( token=os.environ.get("SLACK_BOT_TOKEN"), signing_secret=os.environ.get("SLACK_SIGNING_SECRET"), ) @slack.event({ "type": "message", "channel": BOT_SERVICE_CHANNEL, "subtype": "file_share", "user": "******", }) async def process_azure_email(client: AsyncWebClient, event: dict[str, Any]): if save_events: with open(f"data/json/{event['event_ts']}.json", "w") as f: json.dump(event, f, indent=4, ensure_ascii=False) return
def test_valid_multi_auth_client_id_absence(self): with pytest.raises(BoltError): AsyncApp(signing_secret="valid", client_id=None, client_secret="valid")
import logging from datetime import datetime import json import asyncio import aiohttp from slack_bolt.request.async_request import AsyncBoltRequest from msg_templates import ce_request_form_template, ce_request_submission_success__template,denial_form_template from slack_bolt.async_app import AsyncApp # Initialize logging logging.basicConfig(level=logging.DEBUG) # Initializes your app with your bot token and signing secret app = AsyncApp() CHANNEL = os.environ.get("CHANNEL") international_lead = os.environ.get("INTERNATIONAL_ID") west_lead = os.environ.get("WEST_ID") east_lead = os.environ.get("EAST_ID") # @app.shortcut() decorator for allowing user to trigger a global shortcut that will open a modal with CE Request form @app.shortcut({"callback_id": "ce_request", "type": "shortcut"}) async def open_modal(ack, shortcut, client, logger): #Initializes user that triggered the shortcut event user = shortcut["user"]["username"] #Modal form layout payload msg = ce_request_form_template(user) # Acknowledge the shortcut request
def test_token_absence(self): with pytest.raises(BoltError): AsyncApp(signing_secret="valid", token=None) with pytest.raises(BoltError): AsyncApp(signing_secret="valid", token="")
def test_valid_single_auth(self): app = AsyncApp(signing_secret="valid", token="xoxb-xxx") assert app != None
def test_invalid_client_type(self): with pytest.raises(BoltError): AsyncApp(signing_secret="valid", client=WebClient(token="xoxb-xxx"))
from slack_sdk.web.async_client import AsyncWebClient from slack_bolt.authorization import AuthorizeResult from slack_bolt.async_app import AsyncApp async def authorize(enterprise_id, team_id, user_id, client: AsyncWebClient, logger): logger.info(f"{enterprise_id},{team_id},{user_id}") # You can implement your own logic here token = os.environ["MY_TOKEN"] return AuthorizeResult.from_auth_test_response( auth_test_response=await client.auth_test(token=token), bot_token=token, ) app = AsyncApp(signing_secret=os.environ["SLACK_SIGNING_SECRET"], authorize=authorize) @app.event("app_mention") async def event_test(body, say, logger): logger.info(body) await say("What's up?") @app.command("/hello-bolt-python") # or app.command(re.compile(r"/hello-.+"))(test_command) async def command(ack, body): user_id = body["user_id"] await ack(f"Hi <@{user_id}>!")
import logging # requires `pip install "aiohttp>=3,<4"` from slack_bolt.async_app import AsyncApp logging.basicConfig(level=logging.DEBUG) # export SLACK_SIGNING_SECRET=*** # export SLACK_BOT_TOKEN=xoxb-*** app = AsyncApp() from slack_bolt.async_app import AsyncApp app = AsyncApp() @app.command("/hello-bolt-python") async def command(ack, body, respond): await ack() await respond(f"Hi <@{body['user_id']}>!") # Middleware @app.middleware # or app.use(log_request) async def log_request(logger, body, next): logger.info(body) return await next() # Events API: https://api.slack.com/events-api @app.event("app_mention")
# x = { # "text": { # "type": "plain_text", # "text": cat["name"] # }, # "value": str(cat["id"]) # } # opts.append(x) # return opts OPTIONAL_INPUT_VALUE = "None" logging.basicConfig(level=logging.DEBUG) #categories = [] slack_app = AsyncApp(token=config('SLACK_BOT_TOKEN'), signing_secret=config('SLACK_SIGNING_SECRET')) app_handler = AsyncSlackRequestHandler(slack_app) #categories = get_categories() @slack_app.middleware # or app.use(log_request) async def log_request(logger, body, next): logger.debug(body) return await next() @slack_app.event("app_mention") async def event_test(body, say, logger): logger.info(body) await say("What's up yo?")
from upload_file_to_s3 import upload_file_to_s3 from get_file_from_s3 import get_file_from_s3 env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) # connections # Create CORTX connector es_client = ElasticsearchConnector( elastic_domain=os.environ.get("ELASTIC_DOMAIN"), elastic_port=os.environ.get("ELASTIC_PORT")) # Creating a Bolt app app = AsyncApp( token=os.environ.get("SLACK_BOT_TOKEN"), signing_secret=os.environ.get("SLACK_SIGNING_SECRET"), ) # Creating a CORTX S3 client s3_client = boto3.client( 's3', endpoint_url=str(os.environ.get('ENDPOINT_URL')), aws_access_key_id=str(os.environ.get('AWS_ACCESS_KEY_ID')), aws_secret_access_key=str(os.environ.get('AWS_SECRET_ACCESS_KEY'))) # Creating an AWS Textract client textract_client = boto3.client( 'textract', aws_access_key_id=str(os.environ.get('AMAZON_AWS_ACCESS_KEY_ID')), aws_secret_access_key=str(os.environ.get('AMAZON_AWS_SECRET_ACCESS_KEY')))
# ------------------------------------------------ # instead of slack_bolt in requirements.txt import sys sys.path.insert(1, "..") # ------------------------------------------------ import asyncio import logging from slack_bolt.async_app import AsyncApp logging.basicConfig(level=logging.DEBUG) app = AsyncApp() @app.middleware # or app.use(log_request) async def log_request(logger, body, next): logger.debug(body) return await next() async def ack_command(body, ack, logger): logger.info(body) await ack("Thanks!") async def post_button_message(respond): await respond( blocks=[ {
import os import requests from requests_oauthlib import OAuth2Session # Import the async app instead of the regular one from slack_bolt.async_app import AsyncApp from oAuth import slack_token, slack_signing_secret from api import slack_api, microsoft_api from utils import get_user_id from blocks import build_uifw_team, build_uifw_ooo from models import OutOfOffice, RickyBobby, setup_db, db, Employee database_url = "postgresql://localhost/diego" app = AsyncApp(name="Diego", token=slack_token, signing_secret=slack_signing_secret) # ***************** examples ************************ @app.event("app_mention") async def event_test(body, say, logger): logger.info(body) await say("What's up?") # Listens to incoming messages that contain "hello" @app.message("hello") async def message_hello(message, say, logger): try: # say() sends a message to the channel where the event was triggered await say(blocks=[{
import logging from slack_sdk.web.async_client import AsyncSlackResponse, AsyncWebClient from slack_bolt.async_app import AsyncApp, AsyncAck from slack_bolt.workflows.step.async_step import ( AsyncConfigure, AsyncUpdate, AsyncComplete, AsyncFail, ) logging.basicConfig(level=logging.DEBUG) # export SLACK_SIGNING_SECRET=*** # export SLACK_BOT_TOKEN=xoxb-*** app = AsyncApp() # https://api.slack.com/tutorials/workflow-builder-steps async def edit(ack: AsyncAck, step: dict, configure: AsyncConfigure): await ack() await configure(blocks=[ { "type": "section", "block_id": "intro-section", "text": { "type": "plain_text", "text": "Create a task in one of the listed projects. The link to the task and other details will be available as variable data in later steps.", },
from slack_sdk.oauth.state_store import FileOAuthStateStore import carmille logging.basicConfig(level=logging.INFO) oauth_settings = AsyncOAuthSettings( client_id=os.environ["SLACK_CLIENT_ID"], client_secret=os.environ["SLACK_CLIENT_SECRET"], scopes=[ "channels:history", "channels:read", "commands", "emoji:read", "reactions:read", "users:read" ], installation_store=FileInstallationStore(base_dir="./data"), state_store=FileOAuthStateStore(expiration_seconds=600, base_dir="./data")) app = AsyncApp(signing_secret=os.environ["SLACK_SIGNING_SECRET"], oauth_settings=oauth_settings) @app.command("/carmille") async def command(context, ack, body, respond): await ack() user_tz_offset = await carmille.fetch.get_tz_offset( context.client, body['user_id']) initial_end_time = time.time() + user_tz_offset # Unix seconds initial_start_time = initial_end_time - 3600 # An hour earlier ui_block = carmille.ui.datetime_selection_block # Start Times
import logging logging.basicConfig(level=logging.DEBUG) from slack_bolt.async_app import AsyncApp app = AsyncApp() @app.middleware # or app.use(log_request) async def log_request(logger, body, next): logger.debug(body) return await next() @app.event("app_mention") async def event_test(body, say, logger): logger.info(body) await say("What's up?") @app.command("/hello-bolt-python") # or app.command(re.compile(r"/hello-.+"))(test_command) async def command(ack, body): user_id = body["user_id"] await ack(f"Hi <@{user_id}>!") if __name__ == "__main__": app.start(3000)
installation_store = AsyncSQLAlchemyInstallationStore( client_id=client_id, database_url=database_url, logger=logger, ) oauth_state_store = AsyncSQLAlchemyOAuthStateStore( expiration_seconds=120, database_url=database_url, logger=logger, ) app = AsyncApp( logger=logger, signing_secret=signing_secret, installation_store=installation_store, oauth_settings=AsyncOAuthSettings( client_id=client_id, client_secret=client_secret, state_store=oauth_state_store, ), ) app_handler = AsyncSlackRequestHandler(app) @app.event("app_mention") async def handle_command(say: AsyncSay): await say("Hi!") from sanic import Sanic from sanic.request import Request
from slack_sdk.web.async_client import AsyncSlackResponse, AsyncWebClient from slack_bolt.async_app import AsyncApp, AsyncAck from slack_bolt.workflows.step.async_step import ( AsyncConfigure, AsyncUpdate, AsyncComplete, AsyncFail, AsyncWorkflowStep, ) logging.basicConfig(level=logging.DEBUG) # export SLACK_SIGNING_SECRET=*** # export SLACK_BOT_TOKEN=xoxb-*** app = AsyncApp() # https://api.slack.com/tutorials/workflow-builder-steps copy_review_step = AsyncWorkflowStep.builder("copy_review") @copy_review_step.edit async def edit(ack: AsyncAck, step: dict, configure: AsyncConfigure): await ack() await configure( blocks=[ { "type": "section", "block_id": "intro-section",
def test_non_coroutine_func_listener(self): app = AsyncApp(signing_secret="valid", token="xoxb-xxx") with pytest.raises(BoltError): app.action("a")(self.non_coro_func)
# ------------------------------------------------ # instead of slack_bolt in requirements.txt import sys sys.path.insert(1, "../..") # ------------------------------------------------ import os from slack_bolt.async_app import AsyncApp from slack_bolt.adapter.sanic import AsyncSlackRequestHandler app = AsyncApp() app_handler = AsyncSlackRequestHandler(app) @app.event("app_mention") async def handle_app_mentions(body, say, logger): logger.info(body) await say("What's up?") from sanic import Sanic from sanic.request import Request api = Sanic(name="awesome-slack-app") @api.post("/slack/events") async def endpoint(req: Request): return await app_handler.handle(req)
def test_listener_registration_error(self): app = AsyncApp(signing_secret="valid", token="xoxb-xxx") with pytest.raises(BoltError): app.action({"type": "invalid_type", "action_id": "a"})(self.simple_listener)