├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.rst ├── docs ├── Makefile ├── conf.py ├── index.rst └── reference │ └── api.rst ├── example.py ├── requirements.txt ├── setup.py ├── slouch ├── __init__.py ├── _version.py └── testing.py └── tests ├── conftest.py ├── context.py ├── test_example_bot.py ├── test_handle_long_response.py └── test_send_message.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # PyInstaller 26 | # Usually these files are written by a python script from a template 27 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 28 | *.manifest 29 | *.spec 30 | 31 | # Installer logs 32 | pip-log.txt 33 | pip-delete-this-directory.txt 34 | 35 | # Unit test / coverage reports 36 | htmlcov/ 37 | .tox/ 38 | .coverage 39 | .cache 40 | nosetests.xml 41 | coverage.xml 42 | 43 | # Translations 44 | *.mo 45 | *.pot 46 | 47 | # Django stuff: 48 | *.log 49 | 50 | # Sphinx documentation 51 | docs/_build/ 52 | 53 | # PyBuilder 54 | target/ 55 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - '2.7' 4 | install: 5 | - python setup.py sdist --formats=zip -k 6 | - find ./dist -iname "*.zip" -print0 | xargs -0 pip install 7 | - make init 8 | script: make test 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Venmo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VERSION=$(shell cat slouch/_version.py | cut -d'"' -f2) 2 | 3 | init: 4 | pip install -r requirements.txt 5 | 6 | test: 7 | py.test tests 8 | 9 | release: 10 | python setup.py sdist upload 11 | git tag -a $(VERSION) 12 | git push origin $(VERSION) 13 | git push 14 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | slouch 2 | ====== 3 | 4 | *[not actively supported outside of internal Venmo usage]* 5 | 6 | Slouch is a lightweight Python framework for building cli-inspired Slack bots. 7 | 8 | Here's an example bot built with Slouch: 9 | 10 | .. code-block:: python 11 | 12 | from slouch import Bot, help 13 | 14 | class PingBot(Bot): 15 | pass 16 | 17 | @PingBot.command 18 | def pingme(opts, bot, event): 19 | """Usage: pingme [--message=] 20 | 21 | Respond with an at-mention to the sender. 22 | 23 | Pass _message_ to include a message in the response. 24 | """ 25 | 26 | sender_slack_id = event['user'] 27 | message = opts[''] 28 | response = "" 29 | 30 | if message is not None: 31 | response = message 32 | 33 | return "<@%s> %s" % (sender_slack_id, response) 34 | 35 | And here's a test for that bot: 36 | 37 | .. code-block:: python 38 | 39 | from slouch import testing 40 | 41 | class TestPingBot(CommandTestCase): 42 | 43 | bot_class = PingBot 44 | 45 | def test_ping(self): 46 | response = self.send_message('pingme', user='123') 47 | self.assertEqual(response, '<@123> ') 48 | 49 | 50 | 51 | Install with ``pip install slouch``. 52 | Run tests with ``py.test tests``. 53 | 54 | For more details, check out the docs at https://slouch.readthedocs.io or see a `full example bot `__. 55 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/slouch.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/slouch.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/slouch" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/slouch" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # slouch documentation build configuration file, created by 4 | # sphinx-quickstart on Fri Mar 6 12:12:50 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | from slouch import __version__ 16 | 17 | # -- General configuration ------------------------------------------------ 18 | 19 | # If your documentation needs a minimal Sphinx version, state it here. 20 | #needs_sphinx = '1.0' 21 | 22 | # Add any Sphinx extension module names here, as strings. They can be 23 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 24 | # ones. 25 | extensions = [ 26 | 'sphinx.ext.autodoc', 27 | 'sphinx.ext.viewcode', 28 | ] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'slouch' 44 | copyright = u'2015, Simon Weber' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = __version__ 52 | # The full version, including alpha/beta/rc tags. 53 | release = __version__ 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = ['_build'] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all 70 | # documents. 71 | #default_role = None 72 | 73 | # If true, '()' will be appended to :func: etc. cross-reference text. 74 | #add_function_parentheses = True 75 | 76 | # If true, the current module name will be prepended to all description 77 | # unit titles (such as .. function::). 78 | #add_module_names = True 79 | 80 | # If true, sectionauthor and moduleauthor directives will be shown in the 81 | # output. They are ignored by default. 82 | #show_authors = False 83 | 84 | # The name of the Pygments (syntax highlighting) style to use. 85 | pygments_style = 'sphinx' 86 | 87 | # A list of ignored prefixes for module index sorting. 88 | #modindex_common_prefix = [] 89 | 90 | # If true, keep warnings as "system message" paragraphs in the built documents. 91 | #keep_warnings = False 92 | 93 | 94 | # -- Options for HTML output ---------------------------------------------- 95 | 96 | # The theme to use for HTML and HTML Help pages. See the documentation for 97 | # a list of builtin themes. 98 | html_theme = 'default' 99 | 100 | # Theme options are theme-specific and customize the look and feel of a theme 101 | # further. For a list of options available for each theme, see the 102 | # documentation. 103 | #html_theme_options = {} 104 | 105 | # Add any paths that contain custom themes here, relative to this directory. 106 | #html_theme_path = [] 107 | 108 | # The name for this set of Sphinx documents. If None, it defaults to 109 | # " v documentation". 110 | #html_title = None 111 | 112 | # A shorter title for the navigation bar. Default is the same as html_title. 113 | #html_short_title = None 114 | 115 | # The name of an image file (relative to this directory) to place at the top 116 | # of the sidebar. 117 | #html_logo = None 118 | 119 | # The name of an image file (within the static path) to use as favicon of the 120 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 121 | # pixels large. 122 | #html_favicon = None 123 | 124 | # Add any paths that contain custom static files (such as style sheets) here, 125 | # relative to this directory. They are copied after the builtin static files, 126 | # so a file named "default.css" will overwrite the builtin "default.css". 127 | html_static_path = ['_static'] 128 | 129 | # Add any extra paths that contain custom files (such as robots.txt or 130 | # .htaccess) here, relative to this directory. These files are copied 131 | # directly to the root of the documentation. 132 | #html_extra_path = [] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'slouchdoc' 177 | 178 | 179 | # -- Options for LaTeX output --------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, 194 | # author, documentclass [howto, manual, or own class]). 195 | latex_documents = [ 196 | ('index', 'slouch.tex', u'slouch Documentation', 197 | u'Simon Weber', 'manual'), 198 | ] 199 | 200 | # The name of an image file (relative to this directory) to place at the top of 201 | # the title page. 202 | #latex_logo = None 203 | 204 | # For "manual" documents, if this is true, then toplevel headings are parts, 205 | # not chapters. 206 | #latex_use_parts = False 207 | 208 | # If true, show page references after internal links. 209 | #latex_show_pagerefs = False 210 | 211 | # If true, show URL addresses after external links. 212 | #latex_show_urls = False 213 | 214 | # Documents to append as an appendix to all manuals. 215 | #latex_appendices = [] 216 | 217 | # If false, no module index is generated. 218 | #latex_domain_indices = True 219 | 220 | 221 | # -- Options for manual page output --------------------------------------- 222 | 223 | # One entry per manual page. List of tuples 224 | # (source start file, name, description, authors, manual section). 225 | man_pages = [ 226 | ('index', 'slouch', u'slouch Documentation', 227 | [u'Simon Weber'], 1) 228 | ] 229 | 230 | # If true, show URL addresses after external links. 231 | #man_show_urls = False 232 | 233 | 234 | # -- Options for Texinfo output ------------------------------------------- 235 | 236 | # Grouping the document tree into Texinfo files. List of tuples 237 | # (source start file, target name, title, author, 238 | # dir menu entry, description, category) 239 | texinfo_documents = [ 240 | ('index', 'slouch', u'slouch Documentation', 241 | u'Simon Weber', 'slouch', 'One line description of project.', 242 | 'Miscellaneous'), 243 | ] 244 | 245 | # Documents to append as an appendix to all manuals. 246 | #texinfo_appendices = [] 247 | 248 | # If false, no module index is generated. 249 | #texinfo_domain_indices = True 250 | 251 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 252 | #texinfo_show_urls = 'footnote' 253 | 254 | # If true, do not generate a @detailmenu in the "Top" node's menu. 255 | #texinfo_no_detailmenu = False 256 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | slouch: build cli-inspired Slack bots 2 | ===================================== 3 | 4 | Here's an example Slack bot built with slouch: 5 | 6 | .. code-block:: python 7 | 8 | from slouch import Bot, help 9 | 10 | class PingBot(Bot): 11 | pass 12 | 13 | @PingBot.command 14 | def pingme(opts, bot, event): 15 | """Usage: pingme [--message=] 16 | 17 | Respond with an at-mention to the sender. 18 | 19 | Pass _message_ to include a message in the response. 20 | """ 21 | 22 | sender_slack_id = event['user'] 23 | message = opts[''] 24 | response = "" 25 | 26 | if message is not None: 27 | response = message 28 | 29 | return "<@%s> %s" % (sender_slack_id, response) 30 | 31 | And here's a test for that bot: 32 | 33 | .. code-block:: python 34 | 35 | from slouch import testing 36 | 37 | class TestPingBot(CommandTestCase): 38 | 39 | bot_class = PingBot 40 | 41 | def test_ping(self): 42 | response = self.send_message('pingme', user='123') 43 | self.assertEqual(response, '<@123> ') 44 | 45 | For more details, see the :ref:`api reference ` or the `full example bot `__. 46 | -------------------------------------------------------------------------------- /docs/reference/api.rst: -------------------------------------------------------------------------------- 1 | .. _api: 2 | .. currentmodule:: slouch 3 | 4 | 5 | Slouch api 6 | ========== 7 | 8 | .. autoclass:: Bot 9 | 10 | .. autoinstanceattribute:: Bot.config 11 | :annotation: 12 | .. autoinstanceattribute:: Bot.id 13 | :annotation: 14 | .. autoinstanceattribute:: Bot.log 15 | :annotation: 16 | .. autoinstanceattribute:: Bot.name 17 | :annotation: 18 | .. autoinstanceattribute:: Bot.my_mention 19 | :annotation: 20 | .. autoinstanceattribute:: Bot.slack 21 | :annotation: 22 | .. autoinstanceattribute:: Bot.ws 23 | :annotation: 24 | 25 | .. automethod:: Bot.__init__ 26 | .. automethod:: Bot.prepare_bot 27 | .. automethod:: Bot.prepare_connection 28 | .. automethod:: Bot.run_forever 29 | .. automethod:: Bot.command 30 | .. automethod:: Bot.help_text 31 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | TimerBot can manage multiple stopwatch-style timers from Slack. 5 | 6 | Usage: 7 | timerbot [--start_fmt=] [--stop_fmt=] 8 | timerbot --help 9 | 10 | Options: 11 | --start_fmt= Format string for start responses (given a datetime) [default: {}] 12 | --stop_fmt= Format string for start responses (given a timedelta) [default: {}] 13 | --help Show this screen. 14 | """ 15 | 16 | import datetime 17 | import logging 18 | import sys 19 | 20 | from docopt import docopt 21 | from slouch import Bot, help 22 | 23 | # You might also be interested in this bot's tests: 24 | # https://github.com/venmo/slouch/blob/master/tests/test_example_bot.py 25 | 26 | 27 | class TimerBot(Bot): 28 | def prepare_bot(self, config): 29 | # It's fine to start implementation-specific state directly on the bot. 30 | self.start_fmt = config['start_fmt'] 31 | self.stop_fmt = config['stop_fmt'] 32 | self.timers = {} 33 | 34 | 35 | # This is optional; it provides a help command that lists and gives details on other commands. 36 | TimerBot.command(help) 37 | 38 | 39 | @TimerBot.command 40 | def start(opts, bot, event): 41 | """Usage: start [--name=] 42 | 43 | Start a timer. 44 | 45 | Without _name_, start the default timer. 46 | To run more than one timer at once, pass _name_ to start and stop. 47 | """ 48 | 49 | name = opts['--name'] 50 | 51 | now = datetime.datetime.now() 52 | bot.timers[name] = now 53 | 54 | return bot.start_fmt.format(now) 55 | 56 | 57 | @TimerBot.command 58 | def stop(opts, bot, event): 59 | """Usage: stop [--name=] [--notify=] 60 | 61 | Stop a timer. 62 | 63 | _name_ works the same as for `start`. 64 | If given _slack_username_, reply with an at-mention to the given user. 65 | """ 66 | 67 | name = opts['--name'] 68 | slack_username = opts['--notify'] 69 | 70 | now = datetime.datetime.now() 71 | delta = now - bot.timers.pop(name) 72 | 73 | response = bot.stop_fmt.format(delta) 74 | 75 | if slack_username: 76 | mention = '' 77 | 78 | # The slack api (provided by https://github.com/os/slacker) is available on all bots. 79 | users = bot.slack.users.list().body['members'] 80 | for user in users: 81 | if user['name'] == slack_username: 82 | mention = "<@%s>" % user['id'] 83 | break 84 | response = "%s: %s" % (mention, response) 85 | 86 | return response 87 | 88 | if __name__ == '__main__': 89 | args = docopt(__doc__) 90 | slack_token = args[''] 91 | config = { 92 | 'start_fmt': args['--start_fmt'], 93 | 'stop_fmt': args['--stop_fmt'], 94 | } 95 | 96 | log = logging.getLogger('slouch') 97 | log.setLevel(logging.DEBUG) 98 | console_handler = logging.StreamHandler(sys.stdout) 99 | console_handler.setFormatter(logging.Formatter( 100 | fmt=('%(asctime)s %(name)s' 101 | ' (%(filename)s:%(lineno)s)' 102 | ' %(levelname)s:' 103 | ' %(message)s'), 104 | datefmt='%H:%M:%S')) 105 | log.addHandler(console_handler) 106 | 107 | bot = TimerBot(slack_token, config) 108 | bot.run_forever() 109 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | contextdecorator==0.10.0 2 | docopt-unicode==0.6.1 3 | funcsigs==1.0.2 4 | libfaketime==0.5.0 5 | mock==2.0.0 6 | pbr==1.10.0 7 | py==1.4.31 8 | pytest==2.9.2 9 | python-dateutil==2.5.3 10 | requests==2.11.0 11 | six==1.10.0 12 | slacker==0.9.24 13 | websocket-client==0.37.0 14 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | try: 4 | from setuptools import setup 5 | except ImportError: 6 | from distutils.core import setup 7 | 8 | requires = [ 9 | 'docopt-unicode == 0.6.1', # https://github.com/docopt/docopt/pull/220 10 | 'mock', 11 | 'requests', 12 | 'slacker >= 0.5.1', 13 | 'websocket-client', 14 | ] 15 | 16 | with open('README.rst') as f: 17 | readme = f.read() 18 | 19 | # This hack is from http://stackoverflow.com/a/7071358/1231454; 20 | # the version is kept in a seperate file and gets parsed - this 21 | # way, setup.py doesn't have to import the package. 22 | 23 | VERSIONFILE = 'slouch/_version.py' 24 | 25 | version_line = open(VERSIONFILE).read() 26 | version_re = r"^__version__ = ['\"]([^'\"]*)['\"]" 27 | match = re.search(version_re, version_line, re.M) 28 | if match: 29 | version = match.group(1) 30 | else: 31 | raise RuntimeError("Could not find version in '%s'" % VERSIONFILE) 32 | 33 | setup( 34 | name='slouch', 35 | version=version, 36 | description='A lightweight framework for building cli-inspired Slack bots.', 37 | long_description=readme, 38 | author='Simon Weber', 39 | author_email='simon@venmo.com', 40 | url='https://github.com/venmo/slouch', 41 | packages=['slouch'], 42 | include_package_data=True, 43 | install_requires=requires, 44 | license='MIT', 45 | zip_safe=False, 46 | classifiers=[ 47 | 'Development Status :: 4 - Beta', 48 | 'Intended Audience :: Developers', 49 | 'License :: OSI Approved :: MIT License', 50 | 'Programming Language :: Python', 51 | 'Programming Language :: Python :: 2.7', 52 | ], 53 | ) 54 | -------------------------------------------------------------------------------- /slouch/__init__.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import inspect 3 | import json 4 | import logging 5 | import pprint 6 | import sys 7 | import traceback 8 | 9 | from docopt import docopt, DocoptExit 10 | from slacker import Slacker 11 | import websocket 12 | 13 | from . import testing # noqa 14 | from ._version import __version__ # noqa 15 | 16 | # Message server will reject a message longer than 16kbs 17 | # or 4000 characters. See https://api.slack.com/rtm#limits 18 | SLACK_MESSAGE_LIMIT = 4000 19 | 20 | def _dual_decorator(func): 21 | """This is a decorator that converts a paramaterized decorator for 22 | no-param use. 23 | 24 | source: http://stackoverflow.com/questions/3888158 25 | """ 26 | 27 | @functools.wraps(func) 28 | def inner(*args, **kwargs): 29 | if ((len(args) == 1 and not kwargs and callable(args[0]) 30 | and not (type(args[0]) == type and issubclass(args[0], BaseException)))): 31 | return func()(args[0]) 32 | elif len(args) == 2 and inspect.isclass(args[0]) and callable(args[1]): 33 | return func(args[0], **kwargs)(args[1]) 34 | else: 35 | return func(*args, **kwargs) 36 | return inner 37 | 38 | 39 | def help(opts, bot, _): 40 | """Usage: help [] 41 | 42 | With no arguments, print the form of all supported commands. 43 | With an argument, print a detailed explanation of a command. 44 | """ 45 | command = opts[''] 46 | if command is None: 47 | return bot.help_text() 48 | 49 | if command not in bot.commands: 50 | return "%r is not a known command" % command 51 | 52 | return bot.commands[command].__doc__ 53 | 54 | 55 | class _CommandMeta(type): 56 | """ 57 | If the commands dict is a class field on Bot, then all subclasses will share one registry. 58 | 59 | This metaclass initializes a separate registry on each class. 60 | """ 61 | 62 | def __new__(cls, name, bases, dct): 63 | new_cls = super(_CommandMeta, cls).__new__(cls, name, bases, dct) 64 | new_cls.commands = {} 65 | 66 | return new_cls 67 | 68 | 69 | class Bot(object): 70 | """ 71 | A Bot connects to Slack using the `RTM API `__ 72 | and responds to public messages that are directed to it with username- 73 | or at-mentions. 74 | 75 | Manage the Bot's channels in Slack itself with the `/join` command. 76 | A Bot can be in multiple Slack channels (though state is not isolated by channel). 77 | """ 78 | 79 | __metaclass__ = _CommandMeta 80 | 81 | @classmethod 82 | @_dual_decorator 83 | def command(cls, name=None): 84 | """ 85 | A decorator to convert a function to a command. 86 | 87 | A command's docstring must be a docopt usage string. 88 | See docopt.org for what it supports. 89 | 90 | Commands receive three arguments: 91 | 92 | * opts: a dictionary output by docopt 93 | * bot: the Bot instance handling the command (eg for storing state between commands) 94 | * event: the Slack event that triggered the command (eg for finding the message's sender) 95 | 96 | Additional options may be passed in as keyword arguments: 97 | 98 | * name: the string used to execute the command (no spaces allowed) 99 | 100 | They must return one of three things: 101 | 102 | * a string of response text. It will be sent via the RTM api to the channel where 103 | the bot received the message. Slack will format it as per https://api.slack.com/docs/message-formatting. 104 | * None, to send no response. 105 | * a dictionary of kwargs representing a message to send via https://api.slack.com/methods/chat.postMessage. 106 | Use this to send more complex messages, such as those with custom link text or DMs. 107 | For example, to respond with a DM containing custom link text, return 108 | `{'text': '', 'channel': event['user'], 'username': bot.name}`. 109 | Note that this api has higher latency than the RTM api; use it only when necessary. 110 | """ 111 | # adapted from https://github.com/docopt/docopt/blob/master/examples/interactive_example.py 112 | 113 | def decorator(func): 114 | 115 | @functools.wraps(func) 116 | def _cmd_wrapper(rest, *args, **kwargs): 117 | try: 118 | usage = _cmd_wrapper.__doc__.partition('\n')[0] 119 | opts = docopt(usage, rest) 120 | except (SystemExit, DocoptExit) as e: 121 | # opts did not match 122 | return str(e) 123 | 124 | return func(opts, *args, **kwargs) 125 | 126 | cls.commands[name or func.__name__] = _cmd_wrapper 127 | 128 | return _cmd_wrapper 129 | return decorator 130 | 131 | @classmethod 132 | def help_text(cls): 133 | """Return a slack-formatted list of commands with their usage.""" 134 | docs = [cmd_func.__doc__ for cmd_func in cls.commands.values()] 135 | 136 | # Don't want to include 'usage: ' or explanation. 137 | usage_lines = [doc.partition('\n')[0] for doc in docs] 138 | terse_lines = [line[len('Usage: '):] for line in usage_lines] 139 | terse_lines.sort() 140 | return '\n'.join(['Available commands:\n'] + terse_lines) 141 | 142 | def __init__(self, slack_token, config): 143 | """ 144 | Do not override this to perform implementation-specific setup; 145 | use :func:`prepare_bot` instead. 146 | 147 | No IO will be done until :func:`run_forever` is called (unless :func:`prepare_bot` 148 | is overridden to perform some). 149 | 150 | :param slack_token: a Slack api token. 151 | :param config: an arbitrary dictionary for implementation-specific configuration. 152 | The same object is stored as the `config` attribute and passed to prepare methods. 153 | """ 154 | #: the same config dictionary passed to init. 155 | self.config = config 156 | self._current_message_id = 0 157 | 158 | #: a Logger (``logging.getLogger(__name__)``). 159 | self.log = logging.getLogger(__name__) 160 | 161 | # This doesn't perform IO. 162 | #: a `Slacker `__ instance created with `slack_token`. 163 | self.slack = Slacker(slack_token) 164 | 165 | #: the bot's Slack id. 166 | #: Not available until :func:`prepare_connection`. 167 | self.id = None 168 | 169 | #: the bot's Slack name. 170 | #: Not available until :func:`prepare_connection`. 171 | self.name = None 172 | 173 | #: the bot's Slack mention, equal to ``<@%s> % self.id`` . 174 | #: Not available until :func:`prepare_connection`. 175 | self.my_mention = None 176 | 177 | #: a `WebSocketApp `__ instance. 178 | #: Not available until :func:`prepare_connection`. 179 | self.ws = None 180 | 181 | self.prepare_bot(self.config) 182 | 183 | def prepare_bot(self, config): 184 | """ 185 | Override to perform implementation-specific setup. 186 | 187 | This is called once by :func:`__init__` and is not called on connection restarts. 188 | """ 189 | pass 190 | 191 | def prepare_connection(self, config): 192 | """ 193 | Override to perform per-connection setup. 194 | 195 | This is called by run_forever and on connection restarts. 196 | """ 197 | pass 198 | 199 | def run_forever(self): 200 | """Run the bot, blocking forever.""" 201 | res = self.slack.rtm.start() 202 | self.log.info("current channels: %s", 203 | ','.join(c['name'] for c in res.body['channels'] 204 | if c['is_member'])) 205 | self.id = res.body['self']['id'] 206 | self.name = res.body['self']['name'] 207 | self.my_mention = "<@%s>" % self.id 208 | 209 | self.ws = websocket.WebSocketApp( 210 | res.body['url'], 211 | on_message=self._on_message, 212 | on_error=self._on_error, 213 | on_close=self._on_close, 214 | on_open=self._on_open) 215 | self.prepare_connection(self.config) 216 | self.ws.run_forever() 217 | 218 | def _bot_identifier(self, message): 219 | """Return the identifier used to address this bot in this message. 220 | If one is not found, return None. 221 | 222 | :param message: a message dict from the slack api. 223 | """ 224 | 225 | text = message['text'] 226 | 227 | formatters = [ 228 | lambda identifier: "%s " % identifier, 229 | lambda identifier: "%s:" % identifier, 230 | ] 231 | my_identifiers = [formatter(identifier) for identifier in [self.name, self.my_mention] for formatter in formatters] 232 | 233 | for identifier in my_identifiers: 234 | if text.startswith(identifier): 235 | self.log.debug("sent to me:\n%s", pprint.pformat(message)) 236 | return identifier 237 | 238 | return None 239 | 240 | def _handle_command_response(self, res, event): 241 | """Either send a message (choosing between rtm and postMessage) or ignore the response. 242 | 243 | :param event: a slacker event dict 244 | :param res: a string, a dict, or None. 245 | See the command docstring for what these represent. 246 | """ 247 | 248 | response_handler = None 249 | 250 | if isinstance(res, basestring): 251 | response_handler = functools.partial(self._send_rtm_message, event['channel']) 252 | elif isinstance(res, dict): 253 | response_handler = self._send_api_message 254 | 255 | if response_handler is not None: 256 | response_handler(res) 257 | 258 | def _handle_long_response(self, res): 259 | """Splits messages that are too long into multiple events 260 | :param res: a slack response string or dict 261 | """ 262 | 263 | is_rtm_message = isinstance(res, basestring) 264 | is_api_message = isinstance(res, dict) 265 | 266 | if is_rtm_message: 267 | text = res 268 | elif is_api_message: 269 | text = res['text'] 270 | 271 | message_length = len(text) 272 | 273 | if message_length <= SLACK_MESSAGE_LIMIT: 274 | return [res] 275 | 276 | remaining_str = text 277 | responses = [] 278 | 279 | while remaining_str: 280 | less_than_limit = len(remaining_str) < SLACK_MESSAGE_LIMIT 281 | 282 | if less_than_limit: 283 | last_line_break = None 284 | else: 285 | last_line_break = remaining_str[:SLACK_MESSAGE_LIMIT].rfind('\n') 286 | 287 | if is_rtm_message: 288 | responses.append(remaining_str[:last_line_break]) 289 | elif is_api_message: 290 | template = res.copy() 291 | template['text'] = remaining_str[:last_line_break] 292 | responses.append(template) 293 | 294 | if less_than_limit: 295 | remaining_str = None 296 | else: 297 | remaining_str = remaining_str[last_line_break:] 298 | 299 | self.log.debug("_handle_long_response: splitting long response %s, returns: \n %s", 300 | pprint.pformat(res), pprint.pformat(responses)) 301 | return responses 302 | 303 | def _send_rtm_message(self, channel_id, text): 304 | """Send a Slack message to a channel over RTM. 305 | 306 | :param channel_id: a slack channel id. 307 | :param text: a slack message. Serverside formatting is done 308 | in a similar way to normal user message; see 309 | `Slack's docs `__. 310 | """ 311 | 312 | message = { 313 | 'id': self._current_message_id, 314 | 'type': 'message', 315 | 'channel': channel_id, 316 | 'text': text, 317 | } 318 | self.ws.send(json.dumps(message)) 319 | self._current_message_id += 1 320 | 321 | def _send_api_message(self, message): 322 | """Send a Slack message via the chat.postMessage api. 323 | 324 | :param message: a dict of kwargs to be passed to slacker. 325 | """ 326 | 327 | self.slack.chat.post_message(**message) 328 | self.log.debug("sent api message %r", message) 329 | 330 | # Websocket callbacks. 331 | def _on_message(self, ws, raw_event): 332 | try: 333 | event = json.loads(raw_event) 334 | if 'type' not in event or event['type'] != 'message': 335 | return 336 | 337 | if 'text' not in event: 338 | # These are mostly changed messages, which we don't respond to right now. 339 | return 340 | 341 | identifier = self._bot_identifier(event) 342 | if not identifier: 343 | return 344 | 345 | body = event['text'].partition(identifier)[2].strip() 346 | cmd, _, rest = body.partition(' ') 347 | 348 | if cmd in self.commands: 349 | try: 350 | res = self.commands[cmd](rest, self, event) 351 | except Exception as e: 352 | self.log.exception("%s while handling %r", e, body) 353 | 354 | # Send the exception and the final line of the traceback. 355 | # TODO this doesn't always pick out the right line. 356 | t, v, tb = sys.exc_info() 357 | res = ''.join(traceback.format_exception_only(t, v)) 358 | tb_entries = traceback.extract_tb(tb, 3) 359 | res += ''.join(traceback.format_list(tb_entries[2:])) 360 | else: 361 | res = "Unrecognized command.\n%s" % self.help_text() 362 | 363 | self.log.debug("received command response %r", res) 364 | responses = self._handle_long_response(res) 365 | for r in responses: 366 | self._handle_command_response(r, event) 367 | 368 | except Exception as e: 369 | # websocket-client swallows exceptions in callbacks 370 | self.log.exception("%s during _on_message. event:\n%s", e, pprint.pformat(raw_event)) 371 | 372 | def _on_error(self, ws, error): 373 | self.log.error(error) 374 | 375 | def _on_close(self, ws, code, reason): 376 | self.log.warning("websocket closed. code: %r, reason: %r", code, reason) 377 | 378 | # Attempt to reconnect. 379 | # No need to reset _current_message_id: slack just requires ids that are unique per session. 380 | self.run_forever() 381 | 382 | def _on_open(self, ws): 383 | self.log.info("websocket opened") 384 | -------------------------------------------------------------------------------- /slouch/_version.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.5.0" 2 | -------------------------------------------------------------------------------- /slouch/testing.py: -------------------------------------------------------------------------------- 1 | import json 2 | from unittest import TestCase 3 | 4 | from mock import Mock, patch, create_autospec 5 | 6 | 7 | class CommandTestCase(TestCase): 8 | """A TestCase for unit testing bot requests and responses. 9 | 10 | To use it: 11 | 12 | * provide your bot in *bot_class* (and optionally a config). 13 | * use self.send_message inside your test cases. 14 | It returns what your command returns. 15 | """ 16 | 17 | bot_class = None 18 | config = {} 19 | 20 | def setUp(self): 21 | self.bot = self.bot_class('slack_token', self.config.copy()) 22 | self.bot.name = str(self.bot_class) 23 | self.bot.my_mention = None # we'll just send test messages by name, not mention. 24 | 25 | # This patch is introspected to find command responses (and also prevents interaction with slack). 26 | self.bot._handle_command_response = create_autospec(self.bot._handle_command_response) 27 | 28 | self.ws = Mock() 29 | 30 | self.slack_patcher = patch.object(self.bot, 'slack', autospec=True) 31 | self.slack_mock = self.slack_patcher.start() 32 | 33 | def tearDown(self): 34 | self.slack_patcher.stop() 35 | 36 | def send_message(self, command, message_delimiter=':', **event): 37 | """Return the bot's response to a given command. 38 | 39 | :param command: the message to the bot. 40 | Do not include the bot's name, just the part after the colon. 41 | :param event: kwargs that will override the event sent to the bot. 42 | Useful when your bot expects message from a certain user or channel. 43 | """ 44 | 45 | _event = { 46 | 'type': 'message', 47 | 'text': "%s%s%s" % (self.bot.name, message_delimiter, command), 48 | 'channel': None, 49 | } 50 | 51 | self.assertTrue(_event['text'].startswith("%s%s" % (self.bot.name, message_delimiter))) 52 | 53 | _event.update(event) 54 | 55 | self.bot._on_message(self.ws, json.dumps(_event)) 56 | 57 | args, _ = self.bot._handle_command_response.call_args 58 | return args[0] 59 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from libfaketime import reexec_if_needed 4 | 5 | 6 | def pytest_configure(): 7 | reexec_if_needed() 8 | logging.getLogger('slouch').addHandler(logging.NullHandler()) 9 | -------------------------------------------------------------------------------- /tests/context.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) 5 | 6 | import slouch # noqa 7 | from example import TimerBot # noqa 8 | -------------------------------------------------------------------------------- /tests/test_example_bot.py: -------------------------------------------------------------------------------- 1 | from libfaketime import fake_time 2 | 3 | import context 4 | 5 | 6 | class TestExample(context.slouch.testing.CommandTestCase): 7 | 8 | bot_class = context.TimerBot 9 | config = {'start_fmt': '{:%Y}', 'stop_fmt': '{.days}'} 10 | 11 | def test_help(self): 12 | res = self.send_message('help') 13 | self.assertEqual( 14 | res, 15 | '\n'.join(['Available commands:', 16 | '', 17 | 'help []', 18 | 'start [--name=]', 19 | 'stop [--name=] [--notify=]', 20 | ])) 21 | 22 | def test_default_timer(self): 23 | with fake_time('2016'): 24 | res = self.send_message('start') 25 | self.assertEqual(res, '2016') 26 | 27 | with fake_time('2017'): 28 | res = self.send_message('stop') 29 | self.assertEqual(res, '365') 30 | 31 | def test_named_timer(self): 32 | with fake_time('2016'): 33 | res = self.send_message('start --name=mytimer') 34 | self.assertEqual(res, '2016') 35 | 36 | with fake_time('2017'): 37 | res = self.send_message('stop --name=mytimer') 38 | self.assertEqual(res, '365') 39 | 40 | def test_missing_timer(self): 41 | res = self.send_message('stop --name=mytimer') 42 | self.assertTrue(res.startswith("KeyError: u'mytimer'"), res) 43 | 44 | def test_notify(self): 45 | res = self.send_message('start') 46 | 47 | self.bot.slack.users.list().body = {'members': [{'name': 'user', 'id': 'U123'}]} 48 | res = self.send_message('stop --notify=user') 49 | self.assertTrue(res.startswith('<@U123>'), res) 50 | -------------------------------------------------------------------------------- /tests/test_handle_long_response.py: -------------------------------------------------------------------------------- 1 | import context 2 | 3 | class TestHandleLongResponse(context.slouch.testing.CommandTestCase): 4 | bot_class = context.TimerBot 5 | config = {'start_fmt': '{:%Y}', 'stop_fmt': '{.days}'} 6 | normal_text = ( 7 | "@genericmention: this is generic mention message contains a URL " 8 | "\n@genericmention: this generic mention message contains a :fast_parrot: and :nyancat_big:" 9 | "\n" 10 | ) 11 | over_limit_text = normal_text * 50 # 8550 chars 12 | 13 | 14 | def test_handle_long_message_api(self): 15 | _res = { 16 | 'type': 'message', 17 | 'text': self.normal_text, 18 | 'channel': None, 19 | } 20 | responses = self.bot._handle_long_response(_res) 21 | self.assertEqual(len(responses), 1) 22 | self.assertEqual(responses, [{ 23 | 'type': 'message', 24 | 'text': self.normal_text, 25 | 'channel': None 26 | }]) 27 | 28 | def test_handle_long_message_over_limit_api(self): 29 | 30 | _res = { 31 | 'type': 'message', 32 | 'text': self.over_limit_text, 33 | 'channel': None, 34 | } 35 | responses = self.bot._handle_long_response(_res) 36 | self.assertEqual([len(r['text']) for r in responses], [3932, 3933, 685]) 37 | self.assertEqual(len(responses), 3) 38 | 39 | def test_handle_long_message_rtm(self): 40 | responses = self.bot._handle_long_response(self.normal_text) 41 | self.assertEqual(responses, [self.normal_text]) 42 | self.assertEqual(len(responses), 1) 43 | 44 | def test_handle_long_message_over_limit_rtm(self): 45 | responses = self.bot._handle_long_response(self.over_limit_text) 46 | 47 | self.assertEqual([len(r) for r in responses], [3932, 3933, 685]) 48 | self.assertEqual(len(responses), 3) 49 | 50 | 51 | -------------------------------------------------------------------------------- /tests/test_send_message.py: -------------------------------------------------------------------------------- 1 | import context 2 | 3 | 4 | class TestSendMessage(context.slouch.testing.CommandTestCase): 5 | 6 | bot_class = context.TimerBot 7 | config = {'start_fmt': '{:%Y}', 'stop_fmt': '{.days}'} 8 | 9 | def test_message_colon_delimiter(self): 10 | res = self.send_message('help start') 11 | self.assertIn('Start a timer.', res) 12 | 13 | def test_message_space_delimiter(self): 14 | res = self.send_message('help start', message_delimiter=' ') 15 | self.assertIn('Start a timer.', res) 16 | --------------------------------------------------------------------------------