├── .gitignore ├── README.md ├── app.py ├── config.example.json ├── phony.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | config.json 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | gitlab-discord-bridge 2 | ===================== 3 | 4 | A super simple GitLab>Discord bridge that I made because the only other option is a node.js thing, and nobody should be forced to use node.js. 5 | 6 | Usage 7 | ----- 8 | 9 | After setup (see below), the webhook URL is "http://<ip>:25431/<discord channel id>" to support posting in any channel. The bot user will need to be added to the server by an administrator before attempting to post. 10 | 11 | Instructions 12 | ------------ 13 | 14 | Tested on Ubuntu 16.10 and OS X El Capitan (with Homebrew) 15 | 16 | 1. Install Python 3.5/3.6 (and Pip if not installed automatically): https://www.python.org/downloads/ or `brew install python3` 17 | 2. Clone or download the repository using the green button above. 18 | 3. Run the script once to generate the config file. This will be saved at `~/.config/gitlab_discord_bridge.json` on linux, `~/Library/Preferences/gitlab_discord_bridge.json` on mac, `AppData\Local\gitlab_discord_bridge.json` on Windows 19 | * "secret" should be an arbitrary secret token that you'll be giving to Gitlab to make sure incoming requests to this bridge aren't from an attacker. 20 | * "token" should be a bot login token acquired after creating an application at https://discordapp.com/developers/applications/ and giving it a bot user. 21 | * If running the application directly instead of via gunicorn, the host and port parameters can be set. These will be ignored if running in wsgi. 22 | 4. Install the required libraries: `sudo pip3 install -r requirements.txt` **appdirs now required** 23 | 5. Run the application with `python3 app.py`. 24 | * If you want to run it in the background with more worker threads, I use gunicorn: `sudo pip3 install gunicorn` `gunicorn -w 4 -b 0.0.0.0:25431 app:app` 25 | * You may need to forward port 25431 (TCP) if the server is behind a router. If the bridge and Gitlab are on the same machine or LAN disregard this. 26 | 6. In Gitlab, go into the desired repository's Webhooks settings and add "http://<ip>:25431/<discord channel ID>" as the webhook address. Set "Secret Token" to the same token as you set in config.json. 27 | * You can get the channel ID in the desktop client by opening User Settings > Appearance > Enable Developer Mode, then right clicking on the channel you want the bot to interact with and pressing "Copy ID". If using the browser client, the channel ID is the second string of numbers in the URL separated by forward slashes. 28 | * The bridge can currently handle these event types: push, tag push, issue, note, merge request and wiki page. The author doesn't use pipelines but would like to add support for them to the bot; if you use pipelines, enable that checkbox in Webhook settings and, after triggering a pipeline event, send the author the log from the server. All responses are treated as confidential and will be used to add pipeline support to future releases. 29 | 7. Test the webhook. You should see a message corresponding to the last event on the repository! 30 | 31 | If you need assistance please [create an issue](https://github.com/blha303/gitlab-discord-bridge/issues). 32 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from flask import * 3 | from requests import post 4 | from json import load, dump 5 | from re import sub 6 | from appdirs import user_config_dir 7 | from os.path import join 8 | from sys import exit 9 | 10 | config = {"secret": "gitlab secret token", "token": "bot login token", "port": 25431, "listen": "0.0.0.0"} 11 | config_path = join(user_config_dir(), "gitlab_discord_bridge.json") 12 | 13 | try: 14 | with open(config_path) as f: 15 | config = json.load(f) 16 | if config["token"] == "bot login token": 17 | print("Please update {} with discord bot token".format(config_path)) 18 | exit(2) 19 | except: 20 | with open(config_path, "w") as f: 21 | json.dump(config, f) 22 | print("Please update {} with discord bot token".format(config_path)) 23 | exit(2) 24 | 25 | 26 | app = Flask(__name__) 27 | 28 | def handle_push(body): 29 | """ Handle GitLab push event webhook 30 | https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/user/project/integrations/webhooks.md#push-events """ 31 | tcc = body["total_commits_count"] 32 | commitfmt = "`{id:.7}` **{author[name]}**: {message}" 33 | body.update({"branch": body["ref"].split("/")[-1], 34 | "number": tcc if tcc > 1 else "a", 35 | "cmt_plural": "s" if tcc != 1 else "", 36 | "commits": "\n".join(commitfmt.format(**c) for c in body["commits"]) 37 | }) 38 | return """:round_pushpin: <{project[web_url]}/commits/{branch}> 39 | **{user_name}** pushed {number} commit{cmt_plural}: 40 | {commits}""".format(**body) 41 | 42 | def handle_tag(body): 43 | """ Handle GitLab tag push event webhook 44 | https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/user/project/integrations/webhooks.md#tag-events """ 45 | body.update({"tag": body["ref"].split("/")[-1]}) 46 | return """:label: <{project[web_url]}/tree/{tag}> 47 | **{user_name}** pushed a tag: {tag}""".format(**body) 48 | 49 | def handle_issue(body): 50 | """ Handle GitLab issue event webhook 51 | https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/user/project/integrations/webhooks.md#issues-events """ 52 | try: 53 | a = body["object_attributes"]["action"] 54 | except KeyError: 55 | return False 56 | if a == "update": 57 | return False 58 | body.update({"action": (a + "d") if a[-1] == "e" else (a + "ed")}) 59 | return """:page_facing_up: <{project[web_url]}/issues/{object_attributes[id]}> 60 | **{user[name]}** {action} an issue: {object_attributes[title]}""".format(**body) 61 | 62 | def handle_note(body): 63 | """ Handle GitLab comment (note) event webhook 64 | https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/user/project/integrations/webhooks.md#comment-events """ 65 | def convert(type): 66 | s1 = sub('(.)([A-Z][a-z]+)', r'\1 \2', type) 67 | return sub('([a-z0-9])([A-Z])', r'\1 \2', s1).lower() 68 | body.update({"type": convert(body["object_attributes"]["noteable_type"]) }) 69 | return """:notepad_spiral: <{object_attributes[url]}> 70 | **{user[name]}** commented on a {type}: 71 | {object_attributes[note]}""".format(**body) 72 | 73 | def handle_merge(body): 74 | """ Handle GitLab merge request event webhook 75 | https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/user/project/integrations/webhooks.md#merge-request-events """ 76 | if not "url" in body["object_attributes"]: 77 | body["object_attributes"]["url"] = body["project"]["web_url"] + "/merge_requests" 78 | return """:arrows_counterclockwise: <{object_attributes[url]}> 79 | **{user[name]}** {object_attributes[state]} a merge request: {object_attributes[source_branch]}->{object_attributes[target_branch]} **{object_attributes[title]}**""".format(**body) 80 | 81 | def handle_wiki(body): 82 | """ Handle GitLab wiki page event webhook 83 | https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/user/project/integrations/webhooks.md#wiki-page-events """ 84 | return """:notebook: <{object_attributes[url]}> 85 | **{user[name]}** created a wiki page: {object_attributes[title]}""".format(**body) 86 | 87 | def handle_pipeline(body): 88 | """ Handle GitLab pipeline event webhook 89 | https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/user/project/integrations/webhooks.md#pipeline-events """ 90 | if body["object_attributes"]["status"] == "pending": 91 | return """:bathtub: {project[web_url]}/pipelines/{object_attributes[id]} 92 | **{object_attributes[ref]}**: Pipeline created by **{user[name]}**""".format(**body) 93 | if body["object_attributes"]["status"] == "success": 94 | return """:bathtub: {project[web_url]}/pipelines/{object_attributes[id]} 95 | **{object_attributes[ref]}**: Pipeline finished after **{object_attributes[duration]:.0f}** seconds""".format(**body) 96 | if body["object_attributes"]["status"] == "running": 97 | return """:bathtub: {project[web_url]}/pipelines/{object_attributes[id]} 98 | **{object_attributes[ref]}**: Pipeline started""".format(**body) 99 | return """:bathtub: {project[web_url]}/pipelines/{object_attributes[id]} 100 | **{object_attributes[ref]}**: Pipeline {object_attributes[status]} after **{object_attributes[duration]:.0f}** seconds""".format(**body) 101 | 102 | 103 | def handle_build(body): 104 | """ Handle GitLab pipeline event webhook 105 | https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/user/project/integrations/webhooks.md#build-events """ 106 | if body["build_status"] == "created": 107 | return False 108 | if body["build_status"] == "running": 109 | body.update({"build_status": "started"}) 110 | return """:robot: <{repository[homepage]}/-/jobs/{build_id}> 111 | Job **{build_name}** **{build_status}**""".format(**body) 112 | if body["build_status"] == "success": 113 | body.update({"build_status": "finished"}) 114 | return """:ok_hand: <{repository[homepage]}/-/jobs/{build_id}> 115 | Job **{build_name}** **{build_status}** after **{build_duration:.0f}** seconds""".format(**body) 116 | return """:poop: <{repository[homepage]}/-/jobs/{build_id}> 117 | Job **{build_name}** **{build_status}** after **{build_duration:.0f}** seconds""".format(**body) 118 | 119 | def post_to_discord(channel, text): 120 | """ Posts to Discord like a boss """ 121 | if text is False: 122 | return "cool" 123 | print(text) 124 | d = post("https://discordapp.com/api/channels/{}/messages".format(channel), 125 | json={"content": text}, 126 | headers={"Authorization": "Bot " + config["token"], 127 | "User-Agent": "gitlab-discord-bridge by blha303" 128 | }).json() 129 | return "cool" 130 | 131 | @app.route('/', methods=['GET', 'POST']) 132 | def index(channelid): 133 | if request.method != "POST": 134 | return make_response("Method Not Allowed", 405) 135 | if ("host" in config and request.remote_addr != config["host"]) or request.headers.get("X-Gitlab-Token", "") != config["secret"]: 136 | return make_response("Not Authorized", 403) 137 | try: 138 | body = request.get_json() 139 | except BadRequest: 140 | return make_response("Bad Request", 400) 141 | 142 | handlers = {"push": handle_push, 143 | "tag_push": handle_tag, 144 | "issue": handle_issue, 145 | "note": handle_note, 146 | "merge_request": handle_merge, 147 | "wiki_page": handle_wiki, 148 | "pipeline": handle_pipeline, 149 | "build": handle_build 150 | } 151 | if body["object_kind"] in handlers: 152 | return make_response(post_to_discord(channelid, handlers[body["object_kind"]](body) ), 200) 153 | return make_response("Not Implemented", 501) 154 | 155 | if __name__ == "__main__": 156 | app.run(debug=False, port=config.get("port", 25431), host=config.get("listen", "0.0.0.0")) 157 | -------------------------------------------------------------------------------- /config.example.json: -------------------------------------------------------------------------------- 1 | {"secret": "secret token", "token": "bot login token"} 2 | -------------------------------------------------------------------------------- /phony.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from discord import Client 3 | from json import load 4 | 5 | with open("config.json") as f: 6 | config = load(f) 7 | 8 | client = Client() 9 | 10 | client.run(config["token"]) 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==0.11.1 2 | requests>=2.20.0 3 | discord.py 4 | appdirs 5 | --------------------------------------------------------------------------------