Skip to content

Instantly share code, notes, and snippets.

@allquantor
Created July 14, 2023 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allquantor/401b2e9f37b84199294c39b56e9a24b7 to your computer and use it in GitHub Desktop.
Save allquantor/401b2e9f37b84199294c39b56e9a24b7 to your computer and use it in GitHub Desktop.
import json
import urllib
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
from django.urls import reverse
from django.utils import timezone
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from slack import WebClient
from slackbot import tasks, router
from slackbot.permissions import RequestFormatPermission
from slackbot.serializers import SlackOauthResponseSerializer
from slackbot.services import team_service
from slackbot.tasks import ProcessEvent
from slackbot.utils import join_all_public_channels
from whocanbot_app.cloud_logging import logging
from whocanbot_app.models import Team, Expert
class LandingView(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'slackbot/landing.html'
def get(self, request):
slack_base_url = 'https://slack.com/oauth/v2/authorize'
scopes_list = ['app_mentions:read', 'channels:history', 'channels:join', 'channels:read', 'chat:write',
'commands', 'groups:history', 'groups:write', 'im:history', 'im:write', 'mpim:history',
'mpim:read', 'mpim:write', 'reactions:read', 'team:read',
'users.profile:read', 'users:read', 'users:read.email']
query_args = {
'scope': ','.join(scopes_list),
'user_scope': '',
'redirect_uri': urllib.parse.urljoin(settings.GOOGLE_CLOUD_TASKS_ENDPOINT, reverse('slackbot:oauth-done')),
'client_id': settings.SLACK_CLIENT_ID,
}
url = f'{slack_base_url}?{urllib.parse.urlencode(query_args)}'
return Response({'url': url})
class OauthDoneView(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'common/install_result.html'
def get(self, request):
request_code = request.GET.get('code')
slack_raw_response = WebClient().oauth_v2_access(client_id=settings.SLACK_CLIENT_ID,
client_secret=settings.SLACK_CLIENT_SECRET,
code=request_code)
serializer = SlackOauthResponseSerializer(data=slack_raw_response.data)
if not serializer.is_valid():
return Response({'ok': False})
team = None
slack_data = None
try:
slack_data = serializer.validated_data
team, _ = Team.objects.update_or_create(
team_id=slack_data['team']['id'],
defaults={
'name': slack_data['team']['name'],
'bot_access_token': slack_data['access_token'],
'bot_user_id': slack_data['bot_user_id'],
'bot_version': settings.BOT_VERSION,
'bot_updated_at': timezone.now()
}
)
if team.status == Team.Status.STOPPED:
logging.info(f"Team [{team.team_id}] [{team.name}] has reinstalled whocanbot")
team.status = Team.Status.EVERYONE
logging.info(f'OAuth. Bot was successfully added to [{team.team_id}] [{team.name}]')
except Exception as error:
logging.exception(f'OAuth. Failed to extract data from [{slack_data}]\n{error}')
domain = None
try:
domain = team.client.team_info()['team']['domain']
team.domain = domain
logging.info(f'OAuth. Assign team domain [{domain}] for team id = [{team.id}]')
except Exception as error:
logging.exception(f'OAuth. Failed to assign team domain [{domain}] for team id = [{team.id}]\n{error}')
join_all_public_channels(team)
expert = Expert.objects.create_or_update_expert(team, slack_data['authed_user']['id'])
team.installed_by = expert
team.save()
team_service.start_onboarding_if_needed(expert)
tasks.reload_team_experts_async(team.id)
return HttpResponseRedirect(redirect_to=settings.OAUTH_REDIRECT_URL)
# Handles slack events and commands.
class SlackEventView(APIView):
permission_classes = [RequestFormatPermission]
# To disable CSRF this list must be empty.
authentication_classes = []
def post(self, request):
if 'event' in request.data:
# immediately confirm receiving the event
# handle the event asynchronously
ProcessEvent().delay(event=request.data)
return HttpResponse(headers={'X-Slack-Powered-By': 'WhoCanBot/1', 'Content-Type': 'application/json'})
elif 'command' in request.data:
value = ''
try:
value = router.SlackRequestRouter(request.data).route()
except Exception as error:
logging.exception(f'Exception during handling command event: {error}')
return HttpResponse(json.dumps(value) if value else '', headers={'X-Slack-Powered-By': 'WhoCanBot/1',
'Content-Type': 'application/json'})
elif 'challenge' in request.data:
return HttpResponse(request.data['challenge'])
return HttpResponseBadRequest
# Handles other interactive slack events.
class SlackInteractivityView(APIView):
permission_classes = [RequestFormatPermission]
# To disable CSRF this list must be empty.
authentication_classes = []
def post(self, request):
payload = json.loads(request.data['payload'])
if payload['type'] != 'block_suggestion':
# immediately confirm receiving the event
# handle the event asynchronously
ProcessEvent().delay(event=payload)
return HttpResponse(headers={'X-Slack-Powered-By': 'WhoCanBot/1', 'Content-Type': 'application/json'})
try:
value = router.SlackRequestRouter(payload).route()
value = json.dumps(value) if value else ''
logging.debug(f'Response for block suggestion request: {value}')
return HttpResponse(value,
headers={'X-Slack-Powered-By': 'WhoCanBot/1', 'Content-Type': 'application/json'})
except Exception as error:
logging.exception(f'Exception during handling block suggestion request: {error}')
return HttpResponseBadRequest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment