Skip to content

Commit

Permalink
Copies from austinpray/kizuna and pkg for pypi
Browse files Browse the repository at this point in the history
  • Loading branch information
austinpray committed Sep 8, 2018
0 parents commit 25d3b8f
Show file tree
Hide file tree
Showing 9 changed files with 309 additions and 0 deletions.
106 changes: 106 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/

21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Austin Pray

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
7 changes: 7 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.PHONY: build publish

build:
python setup.py sdist bdist_wheel

publish:
twine upload dist/*
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# python-slacktools

A toolbelt for working with the [Slack][] APIs in python.

[Slack]: https://api.slack.com/
51 changes: 51 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import io
import os
import re


def read(*names, **kwargs):
with io.open(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get("encoding", "utf8")
) as fp:
return fp.read()


long_description = read('README.md')


def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")


setup(name='slacktools',
version=find_version('slacktools', 'version.py'),
description='Toolbelt for Slack API clients for Web API and RTM API',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/austinpray/python-slacktools',
author='Austin Pray',
author_email='[email protected]',
license='MIT',
classifiers=[
#'Development Status :: 5 - Production/Stable',
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Topic :: Communications :: Chat',
'Topic :: System :: Networking',
'Topic :: Office/Business',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
keywords='slack slack-web slack-rtm slacktools chat chatbots bots chatops',
packages=find_packages(exclude=['docs', 'tests']),
install_requires=[
# ayy
])
1 change: 1 addition & 0 deletions slacktools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .verify import verify_request
79 changes: 79 additions & 0 deletions slacktools/slack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import re
from argparse import ArgumentParser
from functools import partial

from kizuna.models import User


def format_slack_mention(slack_id: str):
return f"<@{slack_id}>"


user_id_regex = '^<@(U[A-Za-z0-9]{8,})>$'


def extract_mentions(text):
return set(re.findall(r"<@(\S+)>", text, re.DOTALL))


def get_user_id_from_mention(m: str):
match = re.match(user_id_regex, m)
if not match:
return None

return match.group(1)


def is_user_mention(s: str) -> bool:
"""user mentions should be in format <@UXXXXXXXX>"""

if not s or not re.match(user_id_regex, s):
return False

return True


def send(slack_client, channel, text):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)


def reply(slack_client, message, text):
return slack_client.api_call("chat.postMessage",
channel=message['channel'],
text=f"{format_slack_mention(message['user'])} {text}",
as_user=True)


def send_factory(slack_client, channel):
return partial(send, slack_client, channel)


def send_ephemeral(slack_client, channel, user, text):
if isinstance(user, User):
user = user.slack_id

return slack_client.api_call("chat.postEphemeral",
channel=channel,
user=user,
text=text,
as_user=True)


def send_ephemeral_factory(slack_client, channel, user):
return partial(send_ephemeral, slack_client, channel, user)


class SlackArgumentParserException(Exception):
pass


class SlackArgumentParser(ArgumentParser):
def error(self, message):
raise SlackArgumentParserException(message)


def slack_link(text, url):
return '<{}|{}>'.format(url, text)
37 changes: 37 additions & 0 deletions slacktools/verify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from time import time
import hmac
from hashlib import sha256

class SignatureVersionException(ValueError): pass

def verify_request(slack_signing_secret: str, timestamp: int, body: str, slack_signature: str):
"""https://api.slack.com/docs/verifying-requests-from-slack"""

if not slack_signing_secret:
raise ValueError('slack_signing_secret not provided')
if not timestamp or not isinstance(timestamp, int):
raise ValueError('timestamp is not good int')
if not body:
raise ValueError('body not provided')
if not slack_signature:
raise ValueError('signature not provided')
if not slack_signature.startswith('v0'):
raise SignatureVersionException(f"expected the signature to be version 'v0' but got '{slack_signature[:2]}'")

if abs(time() - timestamp) > 60 * 5:
# The request timestamp is more than five minutes from local time.
# It could be a replay attack, so let's ignore it.
return False

sig_basestring = f"v0:{timestamp}:{body}"

my_signature = 'v0=' + hmac.new(
slack_signing_secret.encode(),
sig_basestring.encode(),
sha256
).hexdigest()

print(slack_signature)
print(my_signature)

return hmac.compare_digest(my_signature, slack_signature)
2 changes: 2 additions & 0 deletions slacktools/version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# see: http://legacy.python.org/dev/peps/pep-0440/#public-version-identifiers
__version__ = '0.0.2'

0 comments on commit 25d3b8f

Please sign in to comment.