diff --git a/mattermost-giphy/Dockerfile b/mattermost-giphy/Dockerfile deleted file mode 100644 index a5dee2dd0437451bdf99c524d8e45f27f87eb48e..0000000000000000000000000000000000000000 --- a/mattermost-giphy/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM python:2.7 - -MAINTAINER Kyâne PICHOU kyane@kyane.fr - -RUN apt-get update && \ - apt-get install -y \ - python-pip \ - python-dev \ - build-essential && \ - rm -rf /var/lib/apt/lists/* /var/cache/apt/* - -RUN git clone https://github.com/numberly/mattermost-integration-giphy.git /mattermost-giphy -WORKDIR /mattermost-giphy - -RUN python setup.py install - -ENTRYPOINT python run.py - diff --git a/mattermost-integration-giphy/.gitignore b/mattermost-integration-giphy/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5b6bc6d8519541e256bcda5f6614d2fd754f2432 --- /dev/null +++ b/mattermost-integration-giphy/.gitignore @@ -0,0 +1,2 @@ +# Edit files +*.swp diff --git a/mattermost-integration-giphy/DOCKER.md b/mattermost-integration-giphy/DOCKER.md new file mode 100644 index 0000000000000000000000000000000000000000..0659173f8b81cb1ed4af46da783cf183bf672c1f --- /dev/null +++ b/mattermost-integration-giphy/DOCKER.md @@ -0,0 +1,42 @@ +## How to +The following procedure shows how to install this project using Docker. It describe procedure to easily build your custom image and deploy. + +To install this project using Docker, you will need Docker Engine install on your machine. Procedure to install Docker can be found [here](https://docs.docker.com/engine/installation/) + +Here's how to start: + +1. **Build your Docker image** + 1. Clone this GitHub repo with + - `git clone https://github.com/numberly/mattermost-integration-giphy.git` + - `cd mattermost-integration-giphy` + 2. Build and tag Docker image using the Dockerfile provided + - `docker build -t mattermost-integration-giphy .` + +2. **Set up your Mattermost slash command** + 1. Log in to your Mattermost account. Click the three dot menu at the top of the left-hand side and go to **Integrations** > **Slash Commands** + 2. Under *Add a new command*, enter `gif` into **Command Trigger Word** + 3. Paste your Web Server domain into *Callback URLs*, making sure to add `http://` to the beginning and `/new_post` to the end so it looks similar to `http://<your-web-server-domain>:<MATTERMOST_GIPHY_PORT>/new_post` and click **Add** + 4. Select `POST` method + 5. (optional) Choose a username and icon url (more details [here](https://docs.mattermost.com/developer/slash-commands.html#set-up-a-custom-command)) + 6. (optional) Check the autocomplete checkbox, add `[KEYWORD]` as the hint, `Returns a GIF from Giphy based on the keyword` as the description and `Get a GIF from Giphy` as the descriptive label + 7. Copy the *Token* from your newly created slash command that appears under the *Existing commands* section + +3. **Run the integration with Docker** + Back on your server, you only need to run your container, with some environnement variables + - `MATTERMOST_GIPHY_TOKEN=<your-token-here>` : this is the token you copied in the last section (you can specify multiple tokens which are separated by a colon) + - `MATTERMOST_GIPHY_HOST=<your-host>` : the host you want the integration (defaults to 0.0.0.0) + - `MATTERMOST_GIPHY_PORT=<your-port-number>` : the port number you want the integration to listen on (defaults to 5000) + - `GIPHY_API_KEY=<giphy-api-key>` : key to use for Giphy API. Default public one is `dc6zaTOxFJmzC` + Your container can be run with the following command : + ``` + docker run -d \ + --name mattermost-giphy \ + -p 5000:5000 \ + -e MATTERMOST_GIPHY_TOKEN=<your-token-here> \ + -e MATTERMOST_GIPHY_HOST=0.0.0.0 \ + -e MATTERMOST_GIPHY_PORT=5000 \ + -e GIPHY_API_KEY=dc6zaTOxFJmzC \ + mattermost-integration-giphy + ``` + +That's it! You should be able to type `gif: hello` or `/gif hello` into any channel and see a GIF from Giphy's translate service. diff --git a/mattermost-integration-giphy/Dockerfile b/mattermost-integration-giphy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0de88b39c01a5c608fb8f79f8ac21b55d16d15cf --- /dev/null +++ b/mattermost-integration-giphy/Dockerfile @@ -0,0 +1,10 @@ +FROM python:2.7-alpine + +MAINTAINER Kyâne PICHOU kyane@kyane.fr + +COPY . /mattermost-giphy +WORKDIR /mattermost-giphy + +RUN python setup.py install + +ENTRYPOINT ["python", "run.py"] diff --git a/mattermost-integration-giphy/HEROKU.md b/mattermost-integration-giphy/HEROKU.md new file mode 100644 index 0000000000000000000000000000000000000000..8b11f98b9c6ef678a9da5448309016306e7aa1db --- /dev/null +++ b/mattermost-integration-giphy/HEROKU.md @@ -0,0 +1,45 @@ +## How to +To install this project using Heroku, you will need: + +1. A Heroku account, available for free from [Heroku.com](http://heroku.com) +1. A Heroku CLI, available for free from [Heroku.com](https://devcenter.heroku.com/articles/heroku-cli) +2. A GitHub account, available for free from [GitHub.com](http://github.com) + +Here's how to start: + +1. **Create a copy of this project to manipulate** + 1. Log in to your GitHub account. Go to the [Github repository of this project](https://github.com/numberly/mattermost-integration-giphy/) click **Fork** in the top-right corner to create a copy of this project that you can control and manipulate + +2. **Deploy your project copy to Heroku** +```bash + $ heroku login + + $ heroku create + + $ git push heroku master +``` + +3. **Connect your project to your Mattermost account for slash commands** + 1. Log in to your Mattermost account. Click the three dot menu at the top of the left-hand side and go to **Integrations** > **Slash Commands** + 2. Under *Add a new command*, enter `gif` into **Command Trigger Word** + 3. Paste your Heroku domain into *Callback URLs* to the beginning and `/new_post` to the end so it looks similar to `http://<your-heroku-domain>/new_post` + 4. Select `POST` method + 5. (optional) Choose a username and icon url (more details [here](https://docs.mattermost.com/developer/slash-commands.html#set-up-a-custom-command)) + 6. (optional) Check the autocomplete checkbox, add `[KEYWORD]` as the hint, `Returns a GIF from Giphy based on the keyword` as the description and `Get a GIF from Giphy` as the descriptive label + 7. Copy the *Token* from your newly created slash command that appears under the *Existing commands* section + +4. **Configure your heroku app with the new token** +```bash + $ heroku config:set MATTERMOST_GIPHY_TOKEN=xxxxx +``` + +That's it! Waiting a few minutes for the Heroku process to restart you should be able to type `gif: hello` or `/gif hello` into any channel and see a GIF from Giphy's translate service. + + +## Production setup: +If you'd like to use this integration in a production envrionment, it is strongly recommended that you get a production Giphy API key from [here](http://api.giphy.com/submit). Once you have that you can configure the integration to use it: + +1. Go to your [Heroku Dashboard](https://dashboard.heroku.com/apps) and click on your app +2. Click the **Settings** tab. Under the *Config Variables* section, click **Reveal Config Vars** +3. For *KEY* type in `GIPHY_API_KEY` and for *VALUE* paste in your Giphy API key, then click **Add** +4. Wait a minute for the Heroku process to restart diff --git a/mattermost-integration-giphy/LICENSE.txt b/mattermost-integration-giphy/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..6b0b1270ff0ca8f03867efcd09ba6ddb6392b1e1 --- /dev/null +++ b/mattermost-integration-giphy/LICENSE.txt @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/mattermost-integration-giphy/LINUX.md b/mattermost-integration-giphy/LINUX.md new file mode 100644 index 0000000000000000000000000000000000000000..7df7e6dd5737fc893f57cccd03221ff6763a8ffc --- /dev/null +++ b/mattermost-integration-giphy/LINUX.md @@ -0,0 +1,52 @@ +## How to +The following procedure shows how to install this project on a Linux web server running Ubuntu 14.04. The following instructions work behind a firewall so long as the web server has access to your GitLab and Mattermost instances. + +To install this project using a Linux-based web server, you will need a Linux/Ubuntu 14.04 web server supporting Python 2.7 or a compatible version. Other compatible operating systems and Python versions should also work. + +Here's how to start: + +1. **Set up this project to run on your web server** + 1. Set up a **Linux Ubuntu 14.04** server either on your own machine or on a hosted service, like AWS. + 2. **SSH** into the machine, or just open your terminal if you're installing locally + 3. Confirm **Python 2.7** or a compatible version is installed by running: + - `python --version` If it's not installed you can find it [here](https://www.python.org/downloads/) + 4. Install **pip** and other essentials + - `sudo apt-get install python-pip python-dev build-essential` + 5. Clone this GitHub repo with + - `git clone https://github.com/numberly/mattermost-integration-giphy.git` + - `cd mattermost-integration-giphy` + 6. Install integration requirements + - `sudo python setup.py install` + +2. **Set up your Mattermost slash command** + 1. Log in to your Mattermost account. Click the three dot menu at the top of the left-hand side and go to **Integrations** > **Slash Commands** + 2. Under *Add a new command*, enter `gif` into **Command Trigger Word** + 3. Paste your Web Server domain into *Callback URLs*, making sure to add `http://` to the beginning and `/new_post` to the end so it looks similar to `http://<your-web-server-domain>:<MATTERMOST_GIPHY_PORT>/new_post` and click **Add** + 4. Select `POST` method + 5. (optional) Choose a username and icon url (more details [here](https://docs.mattermost.com/developer/slash-commands.html#set-up-a-custom-command)) + 6. (optional) Check the autocomplete checkbox, add `[KEYWORD]` as the hint, `Returns a GIF from Giphy based on the keyword` as the description and `Get a GIF from Giphy` as the descriptive label + 7. Copy the *Token* from your newly created slash command that appears under the *Existing commands* section + +3. **Run the server with the correct configuration** + 1. Back on SSH or your terminal, add the following lines to your `~/.bash_profile` + - `export MATTERMOST_GIPHY_TOKEN=<your-token-here>` This is the token you copied in the last section (you can specify multiple tokens which are separated by a colon) + - `export MATTERMOST_GIPHY_HOST=<your-host>` or `export HOST=<your-host>` The host you want the integration (defaults to 0.0.0.0) + - `export MATTERMOST_GIPHY_PORT=<your-port-number>` or `export PORT=<you-port-number>` The port number you want the integration to listen on (defaults to 5000) + 2. Source your bash profile + - `source ~/.bash_profile` + 3. Run the server + - `python run.py` + +That's it! You should be able to type `gif: hello` or `/gif hello` into any channel and see a GIF from Giphy's translate service. + + +## Production setup +If you'd like to use this integration in a production envrionment, it is strongly recommended that you get a production Giphy API key from [here](http://api.giphy.com/submit). Once you have that you can configure the integration to use it: + +1. Stop the process currently running the integration +1. Add the following lines to your `~/.bash_profile` or `~/.bashrc` + - `export GIPHY_API_KEY=<your-api-key-here>` With your Giphy API key +2. Source your bash profile + - `source ~/.bash_profile` or `source ~/.bashrc` +3. Run the server again + - `python run.py` diff --git a/mattermost-integration-giphy/Procfile b/mattermost-integration-giphy/Procfile new file mode 100644 index 0000000000000000000000000000000000000000..fe26464a881c0385620d8bf4f9ab45feb8ed91bb --- /dev/null +++ b/mattermost-integration-giphy/Procfile @@ -0,0 +1 @@ +web: python run.py diff --git a/mattermost-integration-giphy/README.md b/mattermost-integration-giphy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..88e505897ce3f8534d947f281da37129aaaf14e7 --- /dev/null +++ b/mattermost-integration-giphy/README.md @@ -0,0 +1,28 @@ +# Giphy Integration Service for Mattermost +This integrations service is used to enable an external search engine ([Giphy](https://en.wikipedia.org/wiki/Giphy)) to be queried based on commands issued in a Mattermost channel using Mattermost [outgoing webhooks](https://github.com/mattermost/platform/blob/master/doc/integrations/webhooks/Outgoing-Webhooks.md). + +Once installed, users can type `gif: keyword` to send a query to the Giphy search engine and return with a post containing one non-deterministic search result from the Giphy database of animated GIF files matching `keyword`. The animation will appear below in the posted message. + +Powered by [Giphy](http://giphy.com/). + +## Project Goal +The goal of this project is to provide a fully-functional template on which the Mattermost community can create their own integration services. Community members are invited to fork this repo to add improvements and to create new integrations. + +To have your work included on the [Mattermost integrations page](http://www.mattermost.org/community-applications/), please mail info@mattermost.com or tweet to [@MattermostHQ](https://twitter.com/mattermosthq). + +## Requirements +To run this integration you need: + +1. A **web server** supporting Python 2.7 or compatible versions. +2. A **[Mattermost account](http://www.mattermost.org/)** [where outgoing webhooks are enabled](https://github.com/mattermost/platform/blob/master/doc/integrations/webhooks/Outgoing-Webhooks.md#enabling-outgoing-webhooks) + +Many web server options will work, below we provide instructions for [**Heroku**](HEROKU.md) and a general [**Linux/Ubuntu**](LINUX.md) server. + +### Heroku-based Install +[**Here**](HEROKU.md) + +### Linux/Ubuntu 14.04 Web Server Install +[**Here**](LINUX.md) + +### Docker install +[**Here**](DOCKER.md) diff --git a/mattermost-integration-giphy/mattermost_giphy/__init__.py b/mattermost-integration-giphy/mattermost_giphy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mattermost-integration-giphy/mattermost_giphy/app.py b/mattermost-integration-giphy/mattermost_giphy/app.py new file mode 100644 index 0000000000000000000000000000000000000000..47f501fafba9b9407477633e0173871828268eee --- /dev/null +++ b/mattermost-integration-giphy/mattermost_giphy/app.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +import logging +import os +import sys +import json +from urlparse import urlsplit +from urlparse import urlunsplit + +import requests +from flask import Flask +from flask import request +from flask import Response + +from mattermost_giphy.settings import * + + +logging.basicConfig( + level=logging.INFO, format='[%(asctime)s] [%(levelname)s] %(message)s') +app = Flask(__name__) + + +@app.route('/') +def root(): + """ + Home handler + """ + + return "OK" + + +@app.route('/new_post', methods=['POST']) +def new_post(): + """ + Mattermost new post event handler + """ + try: + # NOTE: common stuff + slash_command = False + resp_data = {} + resp_data['username'] = USERNAME + resp_data['icon_url'] = ICON_URL + + data = request.form + + if not 'token' in data: + raise Exception('Missing necessary token in the post data') + + if data['token'] not in MATTERMOST_GIPHY_TOKEN: + raise Exception('Tokens did not match, it is possible that this request came from somewhere other than Mattermost') + + # NOTE: support the slash command + if 'command' in data: + slash_command = True + resp_data['response_type'] = 'in_channel' + + translate_text = data['text'] + if not slash_command: + translate_text = data['text'][len(data['trigger_word']):] + + if not translate_text: + raise Exception("No translate text provided, not hitting Giphy") + + gif_url = giphy_translate(translate_text) + if not gif_url: + raise Exception('No gif url found for `{}`'.format(translate_text)) + + resp_data['text'] = '''`{}` searched for {} + {}'''.format(data.get('user_name', 'unknown').title(), translate_text, gif_url) + except Exception as err: + msg = err.message + logging.error('unable to handle new post :: {}'.format(msg)) + resp_data['text'] = msg + finally: + resp = Response(content_type='application/json') + resp.set_data(json.dumps(resp_data)) + return resp + + +def giphy_translate(text): + """ + Giphy translate method, uses the Giphy API to find an appropriate gif url + """ + try: + params = {} + params['s'] = text + params['rating'] = RATING + params['api_key'] = GIPHY_API_KEY + + resp = requests.get('{}://api.giphy.com/v1/gifs/translate'.format(SCHEME), params=params, verify=True) + + if resp.status_code is not requests.codes.ok: + logging.error('Encountered error using Giphy API, text=%s, status=%d, response_body=%s' % (text, resp.status_code, resp.json())) + return None + + resp_data = resp.json() + + url = list(urlsplit(resp_data['data']['images']['original']['url'])) + url[0] = SCHEME.lower() + + return urlunsplit(url) + except Exception as err: + logging.error('unable to translate giphy :: {}'.format(err)) + return None diff --git a/mattermost-integration-giphy/mattermost_giphy/settings.py b/mattermost-integration-giphy/mattermost_giphy/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..4be4780cf00ec3e564133d770169e50106e359e7 --- /dev/null +++ b/mattermost-integration-giphy/mattermost_giphy/settings.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +import os + +# username the bot posts as +USERNAME = os.environ.get('USERNAME', 'giphy') + +# display picture the bot posts with +ICON_URL = os.environ.get('ICON_URL', 'https://avatars0.githubusercontent.com/u/3588525?v=3&s=200') + +# the maximum parental rating of gifs posted +RATING = os.environ.get('RATING', 'pg') + +# scheme to be used for the gif url return to mattermost +SCHEME = os.environ.get('SCHEME', 'https') + +# the is a public beta key from giphy api +GIPHY_API_KEY = os.environ.get('GIPHY_API_KEY', 'dc6zaTOxFJmzC') + +# the Mattermost token or tokens generated when you created your outgoing webhook +# multiple tokens needs to be separated by a colon +MATTERMOST_GIPHY_TOKEN = os.environ.get('MATTERMOST_GIPHY_TOKEN', '').split(':') diff --git a/mattermost-integration-giphy/requirements.txt b/mattermost-integration-giphy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ab995b8622e88cdd62e7f15a5440df4c506bcc3d --- /dev/null +++ b/mattermost-integration-giphy/requirements.txt @@ -0,0 +1,2 @@ +Flask==0.10.1 +requests==2.10.0 diff --git a/mattermost-integration-giphy/run.py b/mattermost-integration-giphy/run.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ae476c2f2a3bdf53e88d0ceda789cf727a518d --- /dev/null +++ b/mattermost-integration-giphy/run.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import sys + +from mattermost_giphy.app import app +from mattermost_giphy.settings import * + + +if __name__ == "__main__": + if not GIPHY_API_KEY: + print("GIPHY_API_KEY must be configured. Please see README.md for instructions") + sys.exit() + + if not MATTERMOST_GIPHY_TOKEN: + print("MATTERMOST_GIPHY_TOKEN must be configured. Please see README.md for instructions") + sys.exit() + + port = os.environ.get('MATTERMOST_GIPHY_PORT', None) or os.environ.get('PORT', 5000) + host = os.environ.get('MATTERMOST_GIPHY_HOST', None) or os.environ.get('HOST', '0.0.0.0') + app.run(host=str(host), port=int(port)) diff --git a/mattermost-integration-giphy/setup.py b/mattermost-integration-giphy/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..31da843acb38d8c9114f9db90c16e8e0b42bf150 --- /dev/null +++ b/mattermost-integration-giphy/setup.py @@ -0,0 +1,45 @@ +import os +import subprocess +from setuptools import setup +from setuptools import find_packages + + +def version(): + if not os.path.isdir(".git"): + print "This does not appear to be a Git repository." + return + try: + p = subprocess.Popen(["git", "describe", + "--tags", "--always"], + stdout=subprocess.PIPE) + except EnvironmentError: + print "unable to run git, leaving ecdsa/_version.py alone" + return + stdout = p.communicate()[0] + if p.returncode != 0: + print "unable to run git, leaving ecdsa/_version.py alone" + return + return stdout[:-1] + + +README = os.path.join(os.path.dirname(__file__), 'README.md') + + +setup( + name='mattermost_giphy', + version=version(), + description="Giphy Integration Service for Mattermost.", + long_description=README, + classifiers=[], + author='Lujeni', + author_email='julien.thebault@1000mercis.com', + url='https://github.com/numberly/mattermost-integration-giphy', + license='', + packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), + include_package_data=True, + zip_safe=False, + install_requires=[ + 'Flask==0.10.1', + 'requests==2.10.0', + ] +)