Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_existing_flask():
valid_flask = Flask(__name__)
valid_adapter = SlackEventAdapter("vFO9LARnLI7GflLR8tGqHgdy", "/slack/events", valid_flask)
assert isinstance(valid_adapter, SlackEventAdapter)
import pytest
from slackeventsapi import SlackEventAdapter
ADAPTER = SlackEventAdapter('vFO9LARnLI7GflLR8tGqHgdy')
def test_event_emission(client):
# Events should trigger an event
data = pytest.reaction_event_fixture
@ADAPTER.on('reaction_added')
def event_handler(event):
assert event["reaction"] == 'grinning'
res = client.post(
'/slack/events',
data=data,
content_type='application/json'
)
def test_server_not_flask():
with pytest.raises(TypeError) as e:
invalid_flask = "I am not a Flask"
SlackEventAdapter("vFO9LARnLI7GflLR8tGqHgdy", "/slack/events", invalid_flask)
assert e.value.args[0] == 'Server must be an instance of Flask'
def test_version_header(client):
# Verify [package metadata header is set
package_info = SlackEventAdapter("token").server.package_info
data = pytest.reaction_event_fixture
res = client.post(
'/slack/events',
data=data,
content_type='application/json')
assert res.status_code == 200
assert res.headers["X-Slack-Powered-By"] == package_info
def test_existing_flask():
valid_flask = Flask(__name__)
valid_adapter = SlackEventAdapter("vFO9LARnLI7GflLR8tGqHgdy", "/slack/events", valid_flask)
assert isinstance(valid_adapter, SlackEventAdapter)
# Slack
import slack
from slackeventsapi import SlackEventAdapter
# --------------------
# Slack API
# Slack Web API Client with sufficient permissions
slack_web_api_client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
# In order for our application to verify the authenticity
# of requests from Slack, we'll compare the request signature
slack_signing_secret = os.environ["SLACK_SIGNING_SECRET"]
# Create an instance of SlackEventAdapter, passing in our Flask server so it can bind the
# Slack specific routes. The `endpoint` param specifies where to listen for Slack event traffic.
slack_events_adapter = SlackEventAdapter(
slack_signing_secret,
endpoint="/slack/events"
)
# --------------------
# Google Translate API
# https://console.cloud.google.com/apis/credentials?project={project id}
# export GOOGLE_APPLICATION_CREDENTIALS=/path/to/{service-account-key}.json
translate_client = translate.Client()
# --------------------
# Load language mapping data
langcode: dict = {}
with open('./langcode.json') as langcode_file:
langcode = json.load(langcode_file)
if request.method == 'GET':
return make_response("These are not the slackbots you're looking for.", 404)
# Each request comes with request timestamp and request signature
# emit an error if the timestamp is out of range
req_timestamp = request.headers.get('X-Slack-Request-Timestamp')
if abs(time() - int(req_timestamp)) > 60 * 5:
slack_exception = SlackEventAdapterException('Invalid request timestamp')
self.emitter.emit('error', slack_exception)
return make_response("", 403)
# Verify the request signature using the app's signing secret
# emit an error if the signature can't be verified
req_signature = request.headers.get('X-Slack-Signature')
if not self.verify_signature(req_timestamp, req_signature):
slack_exception = SlackEventAdapterException('Invalid request signature')
self.emitter.emit('error', slack_exception)
return make_response("", 403)
# Parse the request payload into JSON
event_data = json.loads(request.data.decode('utf-8'))
# Echo the URL verification challenge code back to Slack
if "challenge" in event_data:
return make_response(
event_data.get("challenge"), 200, {"content_type": "application/json"}
)
# Parse the Event payload and emit the event to the event listener
if "event" in event_data:
event_type = event_data["event"]["type"]
self.emitter.emit(event_type, event_data)
def event():
# If a GET request is made, return 404.
if request.method == 'GET':
return make_response("These are not the slackbots you're looking for.", 404)
# Each request comes with request timestamp and request signature
# emit an error if the timestamp is out of range
req_timestamp = request.headers.get('X-Slack-Request-Timestamp')
if abs(time() - int(req_timestamp)) > 60 * 5:
slack_exception = SlackEventAdapterException('Invalid request timestamp')
self.emitter.emit('error', slack_exception)
return make_response("", 403)
# Verify the request signature using the app's signing secret
# emit an error if the signature can't be verified
req_signature = request.headers.get('X-Slack-Signature')
if not self.verify_signature(req_timestamp, req_signature):
slack_exception = SlackEventAdapterException('Invalid request signature')
self.emitter.emit('error', slack_exception)
return make_response("", 403)
# Parse the request payload into JSON
event_data = json.loads(request.data.decode('utf-8'))
# Echo the URL verification challenge code back to Slack
if "challenge" in event_data:
def get_package_info(self):
client_name = __name__.split('.')[0]
client_version = __version__ # Version is returned from version.py
# Collect the package info, Python version and OS version.
package_info = {
"client": "{0}/{1}".format(client_name, client_version),
"python": "Python/{v.major}.{v.minor}.{v.micro}".format(v=sys.version_info),
"system": "{0}/{1}".format(platform.system(), platform.release())
}
# Concatenate and format the user-agent string to be passed into request headers
ua_string = []
for key, val in package_info.items():
ua_string.append(val)
return " ".join(ua_string)