-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[WIP] Add a feedback dialog box #93
Closed
Closed
Changes from all commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
b25c109
Initial commit
faf06fc
Don't use relative imports
644b52a
Specifying bot OAuth token should be user-developer's concern
9dc5122
Unify image interface
8e9dcc8
Further simplify image interface
f2fb60b
Modify import
fc6e146
Use single name field and use property for message
4057d6d
Fix bug in msg getter
2afabb7
Added comments
b94d489
Added comment regarding asynchronous functionality.
b6e7b01
Refactor send function
82bd9dc
Better error handling and notification dialogs in controller.
40bcab8
Refactor logic and introduce logging.
a5471da
Improve comments
2a304a8
Use HasRequiredTraits
beb3813
Add tests.
7c407d7
Bugfix in example
40f47fd
Use custom style for Description field
b7da2c2
PEP8 compliance
0db10aa
Put error dialog test in a helper function.
f60992c
Compress image inside send function.
1a61255
Fix incorrect syntax for metadata dependence.
b34a768
Add test to ensure files_upload is called correctly
ef1a643
Remove trailing _
1ee8f74
Remove trailing _
d7ffe07
Move example file
e659e49
Add comments + fix typos
133a35f
Add README
12691b6
Fix typos in README
d651bf8
Fixed typo in function name
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
Model and GUI logic for a Feedback/Bugs dialog box. The comments in this | ||
[example app](https://github.com/enthought/apptools/tree/master/examples/feedback) | ||
demonstrate how the dialog box can be incorporated in any TraitsUI app. | ||
|
||
### Requirements: | ||
- python3 | ||
- numpy | ||
- PIL | ||
- python-slackclient | ||
|
||
### Slack setup | ||
|
||
Create a Slack app and install it to the Slack workspace. Then, add a bot user | ||
to the app (detailed instructions are provided | ||
[here](https://api.slack.com/bot-users)). | ||
|
||
#### Tokens, authentication, and security | ||
|
||
Requests to the Slack API have to be authenticated with an authorization token. | ||
A token for the bot-user will be created automatically when the bot is added to | ||
the Slack app. This token must be provided to the model class when an instance | ||
is created. | ||
|
||
The bearer of a bot token has a pretty broad set of permissions. For instance, | ||
they can upload files to a channel, lookup a user with an email address, and | ||
even get the entire conversation history of a channel (see this | ||
[link](https://api.slack.com/bot-users#methods) for a full list of functions | ||
accessible with a bot token). Needless to say, tokens must be secured and never | ||
revealed publicly. The responsibility of transmitting tokens securely lies with the | ||
developer of the app incorporating this dialog box. Refer to the [Slack API | ||
documentation](https://api.slack.com/docs/oauth-safety) | ||
for security best-practices. |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
""" | ||
This module implements a class that provides logic for a simple plugin | ||
for sending messages to a developer team's slack channel. | ||
""" | ||
|
||
import io | ||
import logging | ||
|
||
import slack | ||
from PIL import Image | ||
|
||
from traits.api import ( | ||
HasRequiredTraits, Str, Property, Array, String) | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class FeedbackMessage(HasRequiredTraits): | ||
""" Model for the feedback message. | ||
|
||
Notes | ||
----- | ||
The user-developer must specify the slack channel that the message must be | ||
sent to, as well as provide raw screenshot data. | ||
|
||
""" | ||
|
||
#: Name of the client user | ||
name = Str(msg_meta=True) | ||
|
||
#: Name of the client organization. | ||
organization = Str(msg_meta=True) | ||
|
||
# TODO: Slack supports some markdown in messages, provide | ||
# some details here. | ||
#: Main body of the feedback message. | ||
description = Str(msg_meta=True) | ||
|
||
#: The target slack channel that the bot will post to, must start with # | ||
# and must be provided by the user-developer. | ||
channels = String(minlen=2, regex='#.*', required=True) | ||
|
||
#: OAuth token for the slackbot, must be provided by the user-developer. | ||
token = Str(required=True) | ||
|
||
#: The final message that gets posted to Slack. | ||
msg = Property(Str, depends_on='+msg_meta') | ||
|
||
#: 3D numpy array to hold three channel (RGB) screenshot pixel data. | ||
img_data = Array(shape=(None, None, 3), dtype='uint8', required=True) | ||
|
||
def _get_msg(self): | ||
|
||
feedback_template = 'Name: {name}\n' \ | ||
+ 'Organization: {org}\nDescription: {desc}' | ||
|
||
return feedback_template.format( | ||
name=self.name, | ||
org=self.organization, | ||
desc=self.description) | ||
|
||
def send(self): | ||
""" Send feedback message and screenshot to Slack. """ | ||
|
||
# Set up object that talks to Slack's API. Note that the run_async | ||
# flag is False. This ensures that each HTTP request is blocking. More | ||
# precisely, the WebClient sets up an event loop with just a single | ||
# HTTP request in it, and ensures that the event loop runs to | ||
# completion before returning. | ||
client = slack.WebClient(token=self.token, | ||
timeout=5, | ||
ssl=True, | ||
run_async=False) | ||
|
||
logger.info("Attempting to send message: <%s> to channel: <%s>", | ||
self.msg, self.channels) | ||
|
||
# Compress screenshot into PNG format using an in-memory buffer. | ||
compressed_img_buf = io.BytesIO() | ||
|
||
Image.fromarray(self.img_data).save(compressed_img_buf, 'PNG') | ||
|
||
compressed_img_buf.seek(0) | ||
|
||
# Send message. | ||
response = client.files_upload( | ||
channels=self.channels, | ||
initial_comment=self.msg, | ||
filetype='png', | ||
filename='screenshot.png', | ||
file=compressed_img_buf) | ||
|
||
logger.info("Message sent." | ||
+ " Slack responded with OK : {ok_resp}".format( | ||
ok_resp=response['ok'])) | ||
|
||
return response |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
""" | ||
Tests for FeedbackMessage model. | ||
""" | ||
|
||
import numpy as np | ||
import unittest | ||
from unittest.mock import patch | ||
from PIL import Image | ||
|
||
from traits.api import TraitError | ||
from traits.testing.unittest_tools import UnittestTools | ||
|
||
from apptools.feedback.feedbackbot.model import FeedbackMessage | ||
|
||
|
||
class TestFeedbackMessage(unittest.TestCase, UnittestTools): | ||
|
||
def test_invalid_img_data_raises_error(self): | ||
""" Test that setting img_data to an incorrectly shaped array | ||
raises a TraitError. | ||
|
||
""" | ||
|
||
with self.assertRaises(TraitError): | ||
|
||
FeedbackMessage(img_data=np.empty((2, 2)), | ||
token='xoxb-123456', | ||
channels='#general') | ||
|
||
def test_invalid_channel_raises_error(self): | ||
""" Test that passing a channel name that doesn't begin with | ||
'#' raises TraitError. | ||
|
||
""" | ||
|
||
with self.assertRaises(TraitError): | ||
|
||
FeedbackMessage(img_data=np.empty((1, 1, 3)), | ||
token='xoxb-123456', | ||
channels='general') | ||
|
||
def test_send(self): | ||
""" Test that the slack client call happens with the correct arguments. | ||
|
||
""" | ||
|
||
img_data = np.array([[[1, 2, 3]]], dtype=np.uint8) | ||
|
||
token = 'xoxb-123456' | ||
|
||
channels = '#general' | ||
|
||
msg = FeedbackMessage(img_data=img_data, | ||
token=token, | ||
channels=channels) | ||
|
||
msg.name = 'Tom Riddle' | ||
msg.organization = 'Death Eather, Inc' | ||
msg.description = 'No one calls me Voldy.' | ||
|
||
expected_msg = 'Name: {}\nOrganization: {}\nDescription: {}'.format( | ||
msg.name, msg.organization, msg.description) | ||
|
||
files_upload_found = False | ||
|
||
with patch('apptools.feedback.feedbackbot.model.slack'): | ||
|
||
with patch('apptools.feedback.feedbackbot.model.slack.WebClient') \ | ||
as mock_client: | ||
|
||
msg.send() | ||
|
||
for call_ in mock_client.mock_calls: | ||
# Loop over all calls made to mock_client, including nested | ||
# function calls. | ||
|
||
# Glean function name, provided positional and keyword | ||
# arguments in call_ | ||
name, args, kwargs = call_ | ||
|
||
if name == '().files_upload': | ||
|
||
files_upload_found = True | ||
|
||
# The following lines ensure that <files_upload> is | ||
# called with the correct arguments. | ||
|
||
# There shouldn't be any positional arguments. | ||
self.assertTupleEqual((), args) | ||
|
||
# The following lines check whether keyword arguments | ||
# were passed correctly. | ||
np.testing.assert_almost_equal( | ||
img_data, np.array(Image.open(kwargs['file']))) | ||
|
||
self.assertEqual(channels, kwargs['channels']) | ||
|
||
self.assertEqual( | ||
expected_msg, kwargs['initial_comment']) | ||
|
||
if not files_upload_found: | ||
|
||
self.fail( | ||
"Call to Slack API method <files_upload> not found.") | ||
|
||
|
||
if __name__ == '__main__': | ||
|
||
unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These are essentially testing traits. It would be better to test the logic in the
send
method. This can be done by mockingslack.WebClient.files_upload
and checking that the right information is passed.