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

Add example Apps in additional languages - Python #352

Merged
merged 8 commits into from
Aug 22, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
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
18 changes: 18 additions & 0 deletions examples/python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
### Pre-requisite
- Have python installed, preferably `>=3.0`
- Install the requirements mentioned in the `requirement.txt` with `pip3 install -r requirements.txt`
- Configure the following environment variables to run the app on custom port/url
```
export PORT=8080
export ROOT_URL=http://localhost:8080
export HOST=0.0.0.0
```
- To run with `ngrok`
1. Start the ngrok server on 8080 port, `ngrok http 8080`
2. Export the ngrok url. (replace the ngrok url)
```
export ROOT_URL=https://4492-103-161-231-165.in.ngrok.io
```

#### RUN the app
* `python3 hello-world.py`
2 changes: 2 additions & 0 deletions examples/python/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
requests
flask
199 changes: 199 additions & 0 deletions examples/python/src/hello-world.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import logging
import os
from posixpath import join

import requests
from flask import Flask, request

logging.basicConfig(level=logging.DEBUG)

app = Flask(__name__, static_url_path='/static', static_folder='./static')

default_port = 8080
default_host = 'localhost'
default_root_url = 'http://localhost:8080'
form = {
'title': 'I am a form!',
'icon': 'icon.png',
'fields': [
{
'type': 'text',
'name': 'message',
'label': 'message',
'position': 1,
}
],
'submit': {
'path': '/submit',
},
}


@app.route('/manifest.json')
def manifest() -> dict:
return {
'app_id': 'hello-world',
'display_name': 'Hello world app',
'homepage_url': 'https://github.com/mattermost/mattermost-plugin-apps/tree/master/examples/python/hello-world',
'app_type': 'http',
'icon': 'icon.png',
'requested_permissions': ['act_as_bot'],
'on_install': {
'path': '/install',
'expand': {
'app': 'all',
},
},
'bindings': {
'path': '/bindings',
},
'requested_locations': [
'/channel_header',
'/command'
],
'root_url': os.environ.get('ROOT_URL', default_root_url),
}


@app.route('/submit', methods=['POST'])
def on_form_submit():
print(request.json)
return {'type': 'ok', 'text': f'Hello form got submitted. Form data: {request.json["values"]}'}


@app.route('/bindings', methods=['GET', 'POST'])
def on_bindings() -> dict:
print(f'bindings called with {request.data}')
return {
'type': 'ok',
'data': [
{
# binding for a command
'location': '/command',
'bindings': [
{
'description': 'test command',
'hint': '[This is testing command]',
# this will be the command displayed to user as /first-command
'label': 'first-command',
'icon': 'icon.png',
'submit': {
'path': '/first_command',
# expand block is optional. This is more of metadata like which channel, team this command
# was called from
'expand': {
'app': 'all',
# if you want to expand team & channel, ensure that bot is added to the team & channel
# else command will fail to expand the context
# 'team': 'all',
# 'channel': 'all',
},
Comment on lines +84 to +90
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you want to expand team & channel, ensure that bot is added to the team & channel
else command will fail to expand the context

The bot must be a member of the team and channel, otherwise the expand fails and the request is never sent to the App? It seems that we shouldn't show the command to the user in this case. cc @levb

Copy link
Contributor Author

@dsharma522 dsharma522 Jul 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@levb @mickmister ,

I am able to get the app in the context without even adding the bot to the team/channel. And as expected expansion of team , channel failed as it is not the part of any team/channel currently.


Steps to reproduce

  1. install the app via /apps install http <url> (use the same app binding as in the current PR)
  2. run the command /first-command and press enter to submit. The command will succeed and won't show any error.

Sharing raw response from ngrok for ref, if needed.

{
    "path": "/first_command",
    "expand": {
        "app": "all"
    },
    "context": {
        "app_id": "hello-world",
        "location": "/command/first-command",
        "user_agent": "webapp",
        "track_as_submit": true,
        "mattermost_site_url": "http://localhost:8066",
        "developer_mode": true,
        "app_path": "/plugins/com.mattermost.apps/apps/hello-world",
        "bot_user_id": "3xxj6snbwby19npr1tca3ys9zo",
        "bot_access_token": "3mf1popcwjnzxyeps9kqsqeuoc",
        "app": {
            "app_id": "hello-world",
            "webhook_secret": "zrp5e37iejgtixpfqtjt43ibua",
            "bot_user_id": "3xxj6snbwby19npr1tca3ys9zo",
            "bot_username": "hello-world",
            "remote_oauth2": {}
        },
        "acting_user": {
            "id": "kredsjwqwbrp9r41c86b69akno",
            "delete_at": 0,
            "username": "",
            "auth_service": "",
            "email": "",
            "nickname": "",
            "first_name": "",
            "last_name": "",
            "position": "",
            "roles": "",
            "locale": "",
            "timezone": null,
            "disable_welcome_email": false
        },
        "oauth2": {}
    },
    "raw_command": "/first-command "
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay so when you say "command will fail to expand the context", it's sort of a silent error, and the app still receives the request. It's just not the full request with all values. I think this is due to new changes to expand (optional vs required), depending on which version of the App framework you're working with.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No actually "command will fail to expand the context" mean is that command will fail in the UI itself and not silent failure. And app won't receive the request.

Screenshot 2022-07-25 at 10 34 52 PM

},
},
{ # command with embedded form
'description': 'test command',
'hint': '[This is testing command]',
# this will be the command displayed to user as /second-command
'label': 'second-command',
'icon': 'icon.png',
'bindings': [
{
'location': 'send',
'label': 'send',
'form': form
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we have a comment explaining that this is how you make a subcommand /second-command send? Mainly because there are already plenty of comments explaining things around this area, and this is an important concept to understand imo. Also maybe a comment mentioning that we are including the form here

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also I know I said that form shouldn't be capitalized, but maybe to make it stand out more, we can make it say SHARED_FORM

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

],
}
],
},
{
'location': '/channel_header',
'bindings': [
{
'location': 'send-button',
'icon': 'icon.png',
'label': 'send hello message',
'form': form,
},
],
},
],
}


@app.route('/ping', methods=['POST'])
def on_ping() -> dict:
logging.debug('ping...')
return {'type': 'ok'}


@app.route('/install', methods=['GET', 'POST'])
def on_install() -> dict:
print(f'on_install called with payload , {request.args}, {request.data}', flush=True)
_subscribe_team_join(request.json['context'])
return {'type': 'ok', 'data': []}


@app.route('/first_command', methods=['POST'])
def on_first_command():
print(f'/first_command called ')
response_message = 'Hello! response from /first_command'
return {'type': 'ok', 'text': response_message}


@app.route('/bot_joined_team', methods=['GET', 'POST'])
def on_bot_joined_team() -> dict:
context = request.json['context']
logging.info(
f'bot_joined_team event received for site:{context["mattermost_site_url"]}, '
f'team:{context["team"]["id"]} name:{context["team"]["name"]} '
f'{request.args} {request.data}'
)
# Here one can subscribe to channel_joined/left events as these required team_id now to be subscribed,
# hence use the team_id received in the event and make a call for subscribing to channel_joined/left events.
Comment on lines +154 to +155
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The framework should make sure these subscriptions are removed when the bot is removed from this team cc @levb for discussion

# Also supply {'team_id': team_id} in the request body of the subscription
# {
# 'subject': 'bot_joined_team',
# 'call': {
# 'path': '/bot_joined_team',
# 'expand': {
# 'app': 'all',
# 'team': 'all'
# }
# },
# 'team_id': 'team_id' # get this team_id when bot_joined_team event occurs
# }
return {'type': 'ok', 'data': []}


# Subscribing to events. For example, Subscribe to 'bot_joined_team' event
def _subscribe_team_join(context: dict) -> None:
site_url = context['mattermost_site_url']
bot_access_token = context['bot_access_token']
url = join(site_url, 'plugins/com.mattermost.apps/api/v1/subscribe')
logging.info(f'Subscribing to team_join for {site_url}')
headers = {'Authorization': f'BEARER {bot_access_token}'}
body = {
'subject': 'bot_joined_team',
'call': {
'path': '/bot_joined_team',
'expand': {
'app': 'all',
'team': 'all'
}
},
}
res = requests.post(url, headers=headers, json=body)
if res.status_code != 200:
logging.error(f'Could not subscribe to team_join event for {site_url}')
else:
logging.debug(f'subscribed to team_join event for {site_url}')


if __name__ == '__main__':
app.run(
debug=True,
host=os.environ.get('HOST', default_host),
port=int(os.environ.get('PORT', default_port)),
use_reloader=False,
)
Binary file added examples/python/src/static/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.