Skip to content

Commit 9f63c9b

Browse files
Update slackbot.py
1 parent 82cb4a9 commit 9f63c9b

File tree

1 file changed

+179
-109
lines changed

1 file changed

+179
-109
lines changed

0.1 SlackBot/slackbot.py

Lines changed: 179 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -1,83 +1,83 @@
1-
import requests
2-
from slack_bolt import App
3-
from flask import Flask, jsonify
1+
# import requests
2+
# from slack_bolt import App
3+
# from flask import Flask, jsonify
44

5-
SLACK_APP_TOKEN = os.environ.get['SLACK_APP_TOKEN'] # basic info -app level token - add scope
6-
SLACK_BOT_TOKEN = os.environ.get['SLACK_BOT_TOKEN] # oauth bot token
7-
SLACK_USER_TOKEN = os.environ.get['SLACK_USER_TOKEN'] #oauth user token
5+
# SLACK_APP_TOKEN = os.environ.get['SLACK_APP_TOKEN'] # basic info -app level token - add scope
6+
# SLACK_BOT_TOKEN = os.environ.get['SLACK_BOT_TOKEN] # oauth bot token
7+
# SLACK_USER_TOKEN = os.environ.get['SLACK_USER_TOKEN'] #oauth user token
88

9-
app = Flask(__name__)
9+
# app = Flask(__name__)
1010

1111

1212

13-
@app.route('/')
14-
def home():
15-
return "Hello"
13+
# @app.route('/')
14+
# def home():
15+
# return "Hello"
1616

1717

18-
# take user_id as a url-parameter and returns user's channels
18+
# # take user_id as a url-parameter and returns user's channels
1919

20-
@app.route('/user/<user_id>')
21-
def find_user_id(user_id):
22-
headers = {
23-
'Authorization': 'Bearer SLACK_USER_TOKEN'}
24-
params = {'user': user_id}
25-
data = requests.get(url='https://slack.com/api/users.conversations', headers=headers, params=params).json()
26-
# print(data)
27-
channels = data['channels']
28-
channel_id = []
29-
channel_name = []
30-
for channel in channels:
31-
channel_id.append(channel['id'])
32-
channel_name.append(channel['name'])
33-
print(channel_id)
34-
print(channel_name)
35-
return jsonify(user=user_id, channels=channel_name)
20+
# @app.route('/user/<user_id>')
21+
# def find_user_id(user_id):
22+
# headers = {
23+
# 'Authorization': 'Bearer SLACK_USER_TOKEN'}
24+
# params = {'user': user_id}
25+
# data = requests.get(url='https://slack.com/api/users.conversations', headers=headers, params=params).json()
26+
# # print(data)
27+
# channels = data['channels']
28+
# channel_id = []
29+
# channel_name = []
30+
# for channel in channels:
31+
# channel_id.append(channel['id'])
32+
# channel_name.append(channel['name'])
33+
# print(channel_id)
34+
# print(channel_name)
35+
# return jsonify(user=user_id, channels=channel_name)
3636

3737

3838

39-
#2 Add new user to all of hl's channels via url parameter using hl and new user's id
39+
# #2 Add new user to all of hl's channels via url parameter using hl and new user's id
4040

41-
@app.route('/add/<user_id>/<member_id>')
42-
def add_member(user_id, member_id):
43-
# channels = ['C03JZJLDY7R', 'C03KE4UAWM9', 'C03KE9G8W9G', 'C03L3V5MVEU', 'C03L3VBK03A', 'C03LJJ37SVD', 'C03LZ6BA63U']
41+
# @app.route('/add/<user_id>/<member_id>')
42+
# def add_member(user_id, member_id):
43+
# # channels = ['C03JZJLDY7R', 'C03KE4UAWM9', 'C03KE9G8W9G', 'C03L3V5MVEU', 'C03L3VBK03A', 'C03LJJ37SVD', 'C03LZ6BA63U']
4444

45-
# getting all the channels of the HL
46-
headers = {
47-
'Authorization': 'Bearer SLACK_USER_TOKEN'}
48-
params = {'user': user_id}
49-
data = requests.get(url='https://slack.com/api/users.conversations', headers=headers, params=params).json()
50-
# print(data)
51-
channels = data['channels']
52-
channel_id = []
53-
channel_name = []
54-
for channel in channels:
55-
channel_id.append(channel['id'])
56-
channel_name.append(channel['name'])
57-
# added channels to channel list
58-
print(channel_id)
59-
print(channel_name)
45+
# # getting all the channels of the HL
46+
# headers = {
47+
# 'Authorization': 'Bearer SLACK_USER_TOKEN'}
48+
# params = {'user': user_id}
49+
# data = requests.get(url='https://slack.com/api/users.conversations', headers=headers, params=params).json()
50+
# # print(data)
51+
# channels = data['channels']
52+
# channel_id = []
53+
# channel_name = []
54+
# for channel in channels:
55+
# channel_id.append(channel['id'])
56+
# channel_name.append(channel['name'])
57+
# # added channels to channel list
58+
# print(channel_id)
59+
# print(channel_name)
6060

61-
# Adding user to the channels
62-
for (channel, channel_name) in zip(channel_id[5:], channel_name[5:]):
63-
params = {'channel': f'{channel}', 'users': ['U03LT7U5DBP']}
64-
add = requests.post(url='https://slack.com/api/conversations.invite', headers=headers, params=params).json()
65-
# if added, json response will be {'ok': True}, if already in group the json response would be {'ok': False, 'error': 'already_in_channel'}
66-
# print(add)
67-
# print("\n")
68-
# print(add['ok'])
69-
if add['ok'] == True:
70-
print((f"Successfully added to the channel {channel_name}"))
71-
# return (f"Successfully added to the channel {channel_name}")
72-
elif add['ok'] == False:
73-
print(f"Already in {channel_name}")
74-
# return (f"Already in {channel_name}")
61+
# # Adding user to the channels
62+
# for (channel, channel_name) in zip(channel_id[5:], channel_name[5:]):
63+
# params = {'channel': f'{channel}', 'users': ['U03LT7U5DBP']}
64+
# add = requests.post(url='https://slack.com/api/conversations.invite', headers=headers, params=params).json()
65+
# # if added, json response will be {'ok': True}, if already in group the json response would be {'ok': False, 'error': 'already_in_channel'}
66+
# # print(add)
67+
# # print("\n")
68+
# # print(add['ok'])
69+
# if add['ok'] == True:
70+
# print((f"Successfully added to the channel {channel_name}"))
71+
# # return (f"Successfully added to the channel {channel_name}")
72+
# elif add['ok'] == False:
73+
# print(f"Already in {channel_name}")
74+
# # return (f"Already in {channel_name}")
7575

76-
return ("Added Successfully")
76+
# return ("Added Successfully")
7777

7878

79-
if __name__ == '__main__':
80-
app.run(debug=True, port=8080)
79+
# if __name__ == '__main__':
80+
# app.run(debug=True, port=8080)
8181

8282

8383

@@ -87,61 +87,131 @@ def add_member(user_id, member_id):
8787

8888

8989

90-
#testing slack api's
90+
# #testing slack api's
9191

9292

93-
#1. Getting channels of a user
93+
# #1. Getting channels of a user
9494

95-
# headers = {
96-
# 'Authorization': 'Bearer SLACK_USER_TOKEN'}
97-
# params = {'user': 'member_id_goes_here'}
98-
# data = requests.get(url='https://slack.com/api/users.conversations', headers=headers, params=params).json()
99-
# # print(data)
100-
# channels = data['channels']
101-
# channel_id = []
102-
# channel_name = []
103-
# for channel in channels:
104-
# channel_id.append(channel['id'])
105-
# channel_name.append(channel['name'])
106-
# added channels to channel list
107-
# print(channel_id)
108-
# print(channel_name)
95+
# # headers = {
96+
# # 'Authorization': 'Bearer SLACK_USER_TOKEN'}
97+
# # params = {'user': 'member_id_goes_here'}
98+
# # data = requests.get(url='https://slack.com/api/users.conversations', headers=headers, params=params).json()
99+
# # # print(data)
100+
# # channels = data['channels']
101+
# # channel_id = []
102+
# # channel_name = []
103+
# # for channel in channels:
104+
# # channel_id.append(channel['id'])
105+
# # channel_name.append(channel['name'])
106+
# # added channels to channel list
107+
# # print(channel_id)
108+
# # print(channel_name)
109109

110110

111111

112-
# 2. Add new user to the public channels the HL is a part of
113-
# import requests
114-
# headers = {'Authorization': 'Bearer SLACK_USER_TOKEN'}
115-
# channels = ['C03JZJLDY7R', 'C03KE4UAWM9', 'C03KE9G8W9G', 'C03L3V5MVEU', 'C03L3VBK03A', 'C03LJJ37SVD', 'C03LZ6BA63U']
116-
# for channel in channels[5:] :
117-
# params = {'channel': f'{channel}', 'users':['U03LT7U5DBP']}
118-
# add = requests.post(url='https://slack.com/api/conversations.invite',headers=headers,params=params).json()
119-
120-
# #if added, json response will be {'ok': True},
121-
# if already in group the json response would be {'ok': False, 'error': 'already_in_channel'}
122-
123-
# if add['ok'] == True :
124-
# print (f"Successfully added to the channel {channel}")
125-
# elif add['ok'] == False :
126-
# print(f"Already in {channel}")
112+
# # 2. Add new user to the public channels the HL is a part of
113+
# # import requests
114+
# # headers = {'Authorization': 'Bearer SLACK_USER_TOKEN'}
115+
# # channels = ['C03JZJLDY7R', 'C03KE4UAWM9', 'C03KE9G8W9G', 'C03L3V5MVEU', 'C03L3VBK03A', 'C03LJJ37SVD', 'C03LZ6BA63U']
116+
# # for channel in channels[5:] :
117+
# # params = {'channel': f'{channel}', 'users':['U03LT7U5DBP']}
118+
# # add = requests.post(url='https://slack.com/api/conversations.invite',headers=headers,params=params).json()
119+
120+
# # #if added, json response will be {'ok': True},
121+
# # if already in group the json response would be {'ok': False, 'error': 'already_in_channel'}
122+
123+
# # if add['ok'] == True :
124+
# # print (f"Successfully added to the channel {channel}")
125+
# # elif add['ok'] == False :
126+
# # print(f"Already in {channel}")
127127

128128

129129

130-
#3. Handling Slash Commands
131-
#use slash commands
132-
# @app.route('/slash',methods=["GET","POST"])
133-
# def slash():
134-
# #sents all the dictionary key val pair
135-
# if request.method == "POST" :
136-
# data = request.form
137-
# user_id = data.get('user_id')
138-
# channel_id = data.get('channel_id')
139-
# #client.chat_postmessage(channel=channel_id,text="I got the command")
140-
# return Response(),200
141-
# return ("Simple get request")
130+
# #3. Handling Slash Commands
131+
# #use slash commands
132+
# # @app.route('/slash',methods=["GET","POST"])
133+
# # def slash():
134+
# # #sents all the dictionary key val pair
135+
# # if request.method == "POST" :
136+
# # data = request.form
137+
# # user_id = data.get('user_id')
138+
# # channel_id = data.get('channel_id')
139+
# # #client.chat_postmessage(channel=channel_id,text="I got the command")
140+
# # return Response(),200
141+
# # return ("Simple get request")
142142

143143

144144

145-
#extracting userid from /slash command payload
146-
#data = ImmutableMultiDict([('token', 'qrxsSTRiBNwmHkpBbg4Y20T6'), ('team_id', 'T03KB9JUJ77'), ('team_domain', 'slackbottest-jc28549'), ('channel_id', 'C03L3VBK03A'), ('channel_name', 'test'), ('user_id', 'U03JZJFT1N3'), ('user_name', 'fahadmohammed299299'), ('command', '/slash'), ('text', '<@U03LT7U5DBP|fahadbiznes>'), ('api_app_id', 'A03KSSHPL65'), ('is_enterprise_install', 'false'), ('response_url', 'https://hooks.slack.com/commands/T03KB9JUJ77/3814495845920/rXxVNnnOFFVPt2ZTXgZksDWw'), ('trigger_id', '3784130504694.3657324970245.070398f317dae4af941ee5066c022027')]).to_dict()
147-
#userid = data['text'].split('|')[0].split('@')[1]
145+
# #extracting userid from /slash command payload
146+
# #data = ImmutableMultiDict([('token', 'qrxsSTRiBNwmHkpBbg4Y20T6'), ('team_id', 'T03KB9JUJ77'), ('team_domain', 'slackbottest-jc28549'), ('channel_id', 'C03L3VBK03A'), ('channel_name', 'test'), ('user_id', 'U03JZJFT1N3'), ('user_name', 'fahadmohammed299299'), ('command', '/slash'), ('text', '<@U03LT7U5DBP|fahadbiznes>'), ('api_app_id', 'A03KSSHPL65'), ('is_enterprise_install', 'false'), ('response_url', 'https://hooks.slack.com/commands/T03KB9JUJ77/3814495845920/rXxVNnnOFFVPt2ZTXgZksDWw'), ('trigger_id', '3784130504694.3657324970245.070398f317dae4af941ee5066c022027')]).to_dict()
147+
# #userid = data['text'].split('|')[0].split('@')[1]
148+
149+
150+
151+
152+
153+
154+
155+
156+
import pytest
157+
from app import app
158+
159+
@pytest.fixture
160+
def client():
161+
with app.test_client() as client:
162+
yield client
163+
164+
def test_find_user_channels_valid_user_id(client):
165+
user_id = 'valid_user_id'
166+
response = client.get(f'/find-user-channels/{user_id}')
167+
assert response.status_code == 200
168+
# Assert the expected response based on the valid user ID
169+
170+
def test_find_user_channels_invalid_user_id(client):
171+
user_id = 'invalid_user_id'
172+
response = client.get(f'/find-user-channels/{user_id}')
173+
assert response.status_code == 400
174+
# Assert the error response based on the invalid user ID
175+
176+
def test_find_user_channels_error_communicating_with_server(client, monkeypatch):
177+
def mock_get(*args, **kwargs):
178+
raise Exception("Error communicating with the server")
179+
180+
monkeypatch.setattr('requests.get', mock_get)
181+
182+
user_id = 'valid_user_id'
183+
response = client.get(f'/find-user-channels/{user_id}')
184+
assert response.status_code == 500
185+
# Assert the error response when there is an error communicating with the server
186+
187+
def test_add_member_success(client):
188+
user_id = 'valid_user_id'
189+
channel_id = 'valid_channel_id'
190+
response = client.post(f'/add-member/{user_id}/{channel_id}')
191+
assert response.status_code == 200
192+
# Assert the expected response based on the successful addition of a user to a channel
193+
194+
def test_add_member_error_communicating_with_server(client, monkeypatch):
195+
def mock_post(*args, **kwargs):
196+
raise Exception("Error communicating with the server")
197+
198+
monkeypatch.setattr('requests.post', mock_post)
199+
200+
user_id = 'valid_user_id'
201+
channel_id = 'valid_channel_id'
202+
response = client.post(f'/add-member/{user_id}/{channel_id}')
203+
assert response.status_code == 500
204+
# Assert the error response when there is an error communicating with the server
205+
206+
def test_find_user_all_channels_helper_valid_user_id():
207+
user_id = 'valid_user_id'
208+
result = find_user_all_channels_helper(user_id)
209+
assert result is not None
210+
# Assert the expected result based on the valid user ID
211+
212+
def test_find_user_all_channels_helper_invalid_user_id():
213+
user_id = 'invalid_user_id'
214+
result = find_user_all_channels_helper(user_id)
215+
assert result is None
216+
# Assert the expected result based on the invalid user ID
217+

0 commit comments

Comments
 (0)