Skip to content
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
wants to merge 30 commits into from
Closed
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
b25c109
Initial commit
Jun 13, 2019
faf06fc
Don't use relative imports
Jun 13, 2019
644b52a
Specifying bot OAuth token should be user-developer's concern
Jun 13, 2019
9dc5122
Unify image interface
Jun 13, 2019
8e9dcc8
Further simplify image interface
Jun 14, 2019
f2fb60b
Modify import
Jun 17, 2019
fc6e146
Use single name field and use property for message
Jun 17, 2019
4057d6d
Fix bug in msg getter
Jun 17, 2019
2afabb7
Added comments
Jun 17, 2019
b94d489
Added comment regarding asynchronous functionality.
Jun 18, 2019
b6e7b01
Refactor send function
Jun 19, 2019
82bd9dc
Better error handling and notification dialogs in controller.
Jun 19, 2019
40bcab8
Refactor logic and introduce logging.
Jun 20, 2019
a5471da
Improve comments
Jun 20, 2019
2a304a8
Use HasRequiredTraits
Jun 21, 2019
beb3813
Add tests.
Jun 21, 2019
7c407d7
Bugfix in example
Jun 21, 2019
40f47fd
Use custom style for Description field
Jun 21, 2019
b7da2c2
PEP8 compliance
Jun 21, 2019
0db10aa
Put error dialog test in a helper function.
Jun 24, 2019
f60992c
Compress image inside send function.
Jun 25, 2019
1a61255
Fix incorrect syntax for metadata dependence.
Jun 25, 2019
b34a768
Add test to ensure files_upload is called correctly
Jun 27, 2019
ef1a643
Remove trailing _
Jun 27, 2019
1ee8f74
Remove trailing _
Jun 27, 2019
d7ffe07
Move example file
Jun 27, 2019
e659e49
Add comments + fix typos
Jun 27, 2019
133a35f
Add README
Jun 28, 2019
12691b6
Fix typos in README
Jun 28, 2019
d651bf8
Fixed typo in function name
Jun 28, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions apptools/feedback/feedbackbot/README.md
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.
97 changes: 97 additions & 0 deletions apptools/feedback/feedbackbot/model.py
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
109 changes: 109 additions & 0 deletions apptools/feedback/feedbackbot/tests/test_model.py
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):
Copy link
Contributor

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 mocking slack.WebClient.files_upload and checking that the right information is passed.


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()
Loading