17
17
18
18
import logging
19
19
import json
20
+ from pprint import pprint
20
21
21
22
from django .shortcuts import render
22
23
from django .http import HttpResponse
32
33
SLACK_BOT_USER_TOKEN = getattr (settings , 'SLACK_BOT_USER_TOKEN' , None )
33
34
34
35
35
- Client = WebClient (token = SLACK_BOT_USER_TOKEN )
36
- BOT_ID = Client .api_call ('auth.test' )['user_id' ]
36
+ slack_client = WebClient (token = SLACK_BOT_USER_TOKEN )
37
+ appname = "SQL Assistant"
38
+
39
+ def get_bot_id (botusername ):
40
+ response = slack_client .api_call ("users.list" )
41
+ users = response ["members" ]
42
+ for user in users :
43
+ if 'name' in user and botusername in user .get ('name' ) and not user .get ('deleted' ):
44
+ return user .get ('id' )
45
+
46
+ BOT_ID = get_bot_id (appname )
37
47
38
48
@login_notrequired
39
49
@csrf_exempt
@@ -43,32 +53,31 @@ def slack_events(request):
43
53
if slack_message ['token' ] != SLACK_VERIFICATION_TOKEN :
44
54
return HttpResponse (status = 403 )
45
55
46
- # verification challenge
56
+ # challenge verification
47
57
if slack_message ['type' ] == 'url_verification' :
48
58
response_dict = {"challenge" : slack_message .get ('challenge' )}
49
59
return JsonResponse (response_dict , status = 200 )
50
60
51
-
52
- # Bot greeting when User says "hello hue"
53
61
if 'event' in slack_message :
54
62
event_message = slack_message ['event' ]
55
-
56
- user_id = event_message .get ('user' )
57
-
58
- # ignore bot's own message
59
- if BOT_ID == user_id :
60
- return HttpResponse (status = 200 )
61
-
62
- # process user's message
63
- text = event_message .get ('text' )
64
- channel = event_message .get ('channel' )
65
-
66
- bot_text = 'Hi <@{}> :wave:' .format (user_id )
67
- if 'hello hue' in text .lower ():
68
- Client .api_call (api_method = 'chat.postMessage' , json = {'channel' : channel ,'text' : bot_text })
69
- return HttpResponse (status = 200 )
63
+ parse_events (event_message )
70
64
71
65
return HttpResponse (status = 200 )
72
66
67
+ def parse_events (event_message ):
68
+ user_id = event_message .get ('user' )
69
+ text = event_message .get ('text' )
70
+ channel = event_message .get ('channel' )
73
71
74
-
72
+ # ignore bot's own message
73
+ if BOT_ID == user_id :
74
+ return HttpResponse (status = 200 )
75
+
76
+ if 'hello hue' in text .lower ():
77
+ say_hi_user (channel , user_id )
78
+
79
+ def say_hi_user (channel , user_id ):
80
+ # App greets when user says "hello hue"
81
+ bot_message = f'Hi <@{ user_id } > :wave:'
82
+ slack_client .api_call (api_method = 'chat.postMessage' , json = {'channel' : channel , 'text' : bot_message })
83
+ return HttpResponse (status = 200 )
0 commit comments