Merge branch 'feature/probot'

# Conflicts:
#	README.md
#	package-lock.json
#	package.json
#	scripts/assign-new-pr-to-review.js
#	scripts/assign-to-bounty-awaiting-for-approval.js
#	scripts/greet-new-contributor.js
This commit is contained in:
Pedro Pombeiro 2018-01-22 14:55:40 +01:00
commit 5358d7bde7
No known key found for this signature in database
GPG Key ID: A65DEB11E4BBC647
20 changed files with 6767 additions and 2182 deletions

16
.github/github-bot.yml vendored Normal file
View File

@ -0,0 +1,16 @@
new-pull-requests:
project-board:
name: 'Pipeline for QA'
review-column-name: 'REVIEW'
welcome-bot:
message: 'Thanks for making your first PR here!'
bounty-awaiting-approval:
project-board:
name: 'Status SOB Swarm'
approval-column-name: 'bounty-awaiting-approval'
slack:
notification:
room: 'status-hubot'

6
.travis.yml Normal file
View File

@ -0,0 +1,6 @@
sudo: false
language: node_js
node_js:
- "7.7.1"
notifications:
disabled: true

46
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at pombeirp@users.noreply.github.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

35
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,35 @@
## Contributing
[fork]: /fork
[pr]: /compare
[style]: https://standardjs.com/
[code-of-conduct]: CODE_OF_CONDUCT.md
Hi there! We're thrilled that you'd like to contribute to this project. Your help is essential for keeping it great.
Please note that this project is released with a [Contributor Code of Conduct][code-of-conduct]. By participating in this project you agree to abide by its terms.
## Submitting a pull request
1. [Fork][fork] and clone the repository
1. Configure and install the dependencies: `npm install`
1. Make sure the tests pass on your machine: `npm test`, note: these tests also apply the linter, so no need to lint seperately
1. Create a new branch: `git checkout -b my-branch-name`
1. Make your change, add tests, and make sure the tests still pass
1. Push to your fork and [submit a pull request][pr]
1. Pat your self on the back and wait for your pull request to be reviewed and merged.
Here are a few things you can do that will increase the likelihood of your pull request being accepted:
- Follow the [style guide][style] which is using standard. Any linting errors should be shown when running `npm test`
- Write and update tests.
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
- Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
Work in Progress pull request are also welcome to get feedback early on, or if there is something blocked you.
## Resources
- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
- [Using Pull Requests](https://help.github.com/articles/about-pull-requests/)
- [GitHub Help](https://help.github.com)

15
LICENSE Normal file
View File

@ -0,0 +1,15 @@
ISC License
Copyright (c) 2018, Pedro Pombeiro <pombeirp@users.noreply.github.com> (https://github.com/status-im/status-github-bot)
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@ -1 +0,0 @@
web: bin/hubot -a slack

244
README.md
View File

@ -1,243 +1,57 @@
# statusbot
statusbot is a chat bot built on the [Hubot][hubot] framework. It was
initially generated by [generator-hubot][generator-hubot], and configured to be
deployed on [Heroku][heroku] to get you up and running as quick as possible.
statusbot is a chat bot built on the [Probot][probot] framework.
This README is intended to help get you started. Definitely update and improve
to talk about your own instance, how to use and deploy, what functionality is
available, etc!
[heroku]: http://www.heroku.com
[hubot]: http://hubot.github.com
[generator-hubot]: https://github.com/github/generator-hubot
[probot]: https://probot.github.io/docs/deployment/
## What does the bot do?
Right now the bot has two sets of capabilities:
- Answering questions on Slack, such as `commit streak`. You can find all about them by going to the @hubot app in Slack and typing `help`.
- Doing background stuff in GitHub:
- Assign new PRs to the Pipeline for QA project board (REVIEW column).
- Doing background management in GitHub:
- Assign new PRs to the `Pipeline for QA` project board (`REVIEW` column).
- Assign issues that are labeled `bounty-awaiting-approval` to the `Status SOB Swarm` project board (`bounty-awaiting-approval` column).
- Welcome users who post their first PR in a project.
- New functionality will be added in the future (wishlist is being tracked [here](https://docs.google.com/document/d/19NZEJ453av-owAEBXcIPjavbGKMBFlfVcwsuQ_ORzR4/))
The project board names, column names, welcome message and other values are stored in the `.github/github-bot.yml` file. It can be overriden for each specific repository by adding a file in the same path on the respective repository (see [probot-config](https://github.com/getsentry/probot-config)).
## Creating the bot GitHub App
This bot is meant to be packaged as a GitHub App. There are two steps to it: creating the app, and installing the app. Creating a GitHub App only needs to be done once and the app can be made public to be reused for any number of repositories and organizations.
See the official [docs for deployment](https://probot.github.io/docs/deployment/).
1. Create the GitHub App:
1. In GitHub, go to `Settings/Developer settings/GitHub Apps` and click on `New GitHub App`
1. Enter the bot name in `GitHub App name`, e.g. `Status GitHub Bot`
1. In `Homepage URL`, enter the root endpoint of the service, e.g. https://5e63b0ab.ngrok.io/
1. In `Webhook URL`, enter the `/hubot/github-repo-listener` endpoint of the service, e.g. https://5e63b0ab.ngrok.io/hubot/github-repo-listener
1. ~~In `Webhook secret (optional)`, enter a string of characters that matches the value in the config.json file deployed with the service.~~
1. The app needs `Read-only` permission to `Pull requests`, `Read & write` permission to `Repository projects`.
1. The app subscribes to `Pull request` events.
1. Generate a private key, and save it in the root folder of the service, with the following file name: `status-github-bot.pem`
1. In `Homepage URL`, enter the `/ping` endpoint of the service, e.g. https://5e63b0ab.ngrok.io/ping
1. In `Webhook URL`, enter the root endpoint of the service, e.g. https://5e63b0ab.ngrok.io/
1. In `Webhook secret (optional)`, enter a string of characters that matches the value passed in the in the `WEBHOOK_SECRET` environment variable.
1. This app requires these **Permissions & events** for the GitHub App:
- Issues - **Read & Write**
- [x] Check the box for **Issue comment** events
- [x] Check the box for **Issues** events
- Pull requests - **Read & Write**
- [x] Check the box for **Pull request** events
- [x] Check the box for **Pull request review** events
- [x] Check the box for **Pull request review comment** events
- Repository projects - **Read & Write**
- Single File - **Read-only**
- Path: `.github/github-bot.yml`
1. Generate a private key pass and save it.
1. Installing the bot service:
1. Deploy the bot to the cloud.
1. Make sure the `status-github-bot.pem` file is present in the same directory as this README.md file.
1. Install redis (see below in the Persistance section) so that the bot can recover data after being restarted.
1. Set the `APP_ID` environment variable to value reported when the GitHub App was created.
1. Set the `WEBHOOK_SECRET` environment variable to the value configured in the GitHub App.
1. Set the `PRIVATE_KEY` environment variable to the contents of the `.pem` file.
1. Set the `SLACK_BOT_TOKEN` environment variable to the value reported for the bot in [Slack](https://status-im.slack.com/apps/).
1. Install the GitHub App in an account:
1. Select the repositories where the bot should work (e.g. `status-react`)
### Running statusbot Locally
You can test your hubot by running the following, however some plugins will not
behave as expected unless the [environment variables](#configuration) they rely
upon have been set.
You can start statusbot locally by running:
% bin/hubot
You'll see some start up output and a prompt:
[Sat Feb 28 2015 12:38:27 GMT+0000 (GMT)] INFO Using default redis on localhost:6379
statusbot>
Then you can interact with statusbot by typing `statusbot help`.
statusbot> statusbot help
statusbot animate me <query> - The same thing as `image me`, except adds [snip]
statusbot help - Displays all of the help commands that statusbot knows about.
...
### Configuration
A few scripts (including some installed by default) require environment
variables to be set as a simple form of configuration.
Each script should have a commented header which contains a "Configuration"
section that explains which values it requires to be placed in which variable.
When you have lots of scripts installed this process can be quite labour
intensive. The following shell command can be used as a stop gap until an
easier way to do this has been implemented.
grep -o 'hubot-[a-z0-9_-]\+' external-scripts.json | \
xargs -n1 -I {} sh -c 'sed -n "/^# Configuration/,/^#$/ s/^/{} /p" \
$(find node_modules/{}/ -name "*.coffee")' | \
awk -F '#' '{ printf "%-25s %s\n", $1, $2 }'
How to set environment variables will be specific to your operating system.
Rather than recreate the various methods and best practices in achieving this,
it's suggested that you search for a dedicated guide focused on your OS.
### Scripting
An example script is included at `scripts/example.coffee`, so check it out to
get started, along with the [Scripting Guide][scripting-docs].
For many common tasks, there's a good chance someone has already one to do just
the thing.
[scripting-docs]: https://github.com/github/hubot/blob/master/docs/scripting.md
### external-scripts
There will inevitably be functionality that everyone will want. Instead of
writing it yourself, you can use existing plugins.
Hubot is able to load plugins from third-party `npm` packages. This is the
recommended way to add functionality to your hubot. You can get a list of
available hubot plugins on [npmjs.com][npmjs] or by using `npm search`:
% npm search hubot-scripts panda
NAME DESCRIPTION AUTHOR DATE VERSION KEYWORDS
hubot-pandapanda a hubot script for panda responses =missu 2014-11-30 0.9.2 hubot hubot-scripts panda
...
To use a package, check the package's documentation, but in general it is:
1. Use `npm install --save` to add the package to `package.json` and install it
2. Add the package name to `external-scripts.json` as a double quoted string
You can review `external-scripts.json` to see what is included by default.
##### Advanced Usage
It is also possible to define `external-scripts.json` as an object to
explicitly specify which scripts from a package should be included. The example
below, for example, will only activate two of the six available scripts inside
the `hubot-fun` plugin, but all four of those in `hubot-auto-deploy`.
```json
{
"hubot-fun": [
"crazy",
"thanks"
],
"hubot-auto-deploy": "*"
}
```
**Be aware that not all plugins support this usage and will typically fallback
to including all scripts.**
[npmjs]: https://www.npmjs.com
### hubot-scripts
Before hubot plugin packages were adopted, most plugins were held in the
[hubot-scripts][hubot-scripts] package. Some of these plugins have yet to be
migrated to their own packages. They can still be used but the setup is a bit
different.
To enable scripts from the hubot-scripts package, add the script name with
extension as a double quoted string to the `hubot-scripts.json` file in this
repo.
[hubot-scripts]: https://github.com/github/hubot-scripts
## Persistence
If you are going to use the `hubot-redis-brain` package (strongly suggested),
you will need to add the Redis to Go addon on Heroku which requires a verified
account or you can create an account at [Redis to Go][redistogo] and manually
set the `REDISTOGO_URL` variable.
% heroku config:add REDISTOGO_URL="..."
If you don't need any persistence feel free to remove the `hubot-redis-brain`
from `external-scripts.json` and you don't need to worry about redis at all.
[redistogo]: https://redistogo.com/
## Adapters
Adapters are the interface to the service you want your hubot to run on, such
as Campfire or IRC. There are a number of third party adapters that the
community have contributed. Check [Hubot Adapters][hubot-adapters] for the
available ones.
If you would like to run a non-Campfire or shell adapter you will need to add
the adapter package as a dependency to the `package.json` file in the
`dependencies` section.
Once you've added the dependency with `npm install --save` to install it you
can then run hubot with the adapter.
% bin/hubot -a <adapter>
Where `<adapter>` is the name of your adapter without the `hubot-` prefix.
[hubot-adapters]: https://github.com/github/hubot/blob/master/docs/adapters.md
## Deployment
% heroku create --stack cedar
% git push heroku master
If your Heroku account has been verified you can run the following to enable
and add the Redis to Go addon to your app.
% heroku addons:add redistogo:nano
If you run into any problems, checkout Heroku's [docs][heroku-node-docs].
You'll need to edit the `Procfile` to set the name of your hubot.
More detailed documentation can be found on the [deploying hubot onto
Heroku][deploy-heroku] wiki page.
### Deploying to UNIX or Windows
If you would like to deploy to either a UNIX operating system or Windows.
Please check out the [deploying hubot onto UNIX][deploy-unix] and [deploying
hubot onto Windows][deploy-windows] wiki pages.
[heroku-node-docs]: http://devcenter.heroku.com/articles/node-js
[deploy-heroku]: https://github.com/github/hubot/blob/master/docs/deploying/heroku.md
[deploy-unix]: https://github.com/github/hubot/blob/master/docs/deploying/unix.md
[deploy-windows]: https://github.com/github/hubot/blob/master/docs/deploying/windows.md
## Campfire Variables
If you are using the Campfire adapter you will need to set some environment
variables. If not, refer to your adapter documentation for how to configure it,
links to the adapters can be found on [Hubot Adapters][hubot-adapters].
Create a separate Campfire user for your bot and get their token from the web
UI.
% heroku config:add HUBOT_CAMPFIRE_TOKEN="..."
Get the numeric IDs of the rooms you want the bot to join, comma delimited. If
you want the bot to connect to `https://mysubdomain.campfirenow.com/room/42`
and `https://mysubdomain.campfirenow.com/room/1024` then you'd add it like
this:
% heroku config:add HUBOT_CAMPFIRE_ROOMS="42,1024"
Add the subdomain hubot should connect to. If you web URL looks like
`http://mysubdomain.campfirenow.com` then you'd add it like this:
% heroku config:add HUBOT_CAMPFIRE_ACCOUNT="mysubdomain"
[hubot-adapters]: https://github.com/github/hubot/blob/master/docs/adapters.md
1. Select the repositories where the bot should work (e.g. `status-react`).
## Restart the bot

10
__tests__/index.test.js Normal file
View File

@ -0,0 +1,10 @@
// You can import your modules
// const index = require('../index')
test('that we can run tests', () => {
// your real tests go here
expect(1 + 2 + 3).toBe(6)
})
// For more information about testing with Jest see:
// https://facebook.github.io/jest/

View File

@ -1,8 +0,0 @@
#!/bin/sh
set -e
npm install
export PATH="node_modules/.bin:node_modules/hubot/node_modules/.bin:$PATH"
exec node_modules/.bin/hubot --name "statusbot" "$@"

View File

@ -1,7 +0,0 @@
@echo off
call npm install
SETLOCAL
SET PATH=node_modules\.bin;node_modules\hubot\node_modules\.bin;%PATH%
node_modules\.bin\hubot.cmd --name "statusbot" %*

View File

@ -1,14 +0,0 @@
[
"hubot-brain-inspect",
"hubot-diagnostics",
"hubot-help",
"hubot-heroku-keepalive",
"hubot-google-translate",
"hubot-maps",
"hubot-rcbrb",
"hubot-azure-brain",
"hubot-reload-scripts",
"hubot-commit-streak",
"hubot-github-webhook-listener",
"hubot-github-pr-reporter"
]

13
index.js Normal file
View File

@ -0,0 +1,13 @@
module.exports = (robot) => {
console.log('Yay, the app was loaded!')
require('./scripts/assign-new-pr-to-review.js')(robot);
require('./scripts/assign-to-bounty-awaiting-for-approval.js')(robot);
require('./scripts/greet-new-contributor.js')(robot);
// For more information on building apps:
// https://probot.github.io/docs/
// To get your app running against GitHub, see:
// https://probot.github.io/docs/development/
}

7943
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +1,31 @@
{
"name": "statusbot",
"version": "0.0.0",
"private": true,
"author": "Pedro Pombeiro <pombeirp@users.noreply.github.com>",
"description": "A simple helpful robot for your Company",
"name": "status-github-bot",
"version": "1.0.0",
"description": "",
"author": "Pedro Pombeiro <pombeirp@users.noreply.github.com> (https://github.com/status-im/status-github-bot)",
"license": "ISC",
"repository": "https://github.com/status-im/status-github-bot.git",
"scripts": {
"start": "probot run ./index.js",
"test": "jest && standard"
},
"dependencies": {
"coffee-script": "^1.12.7",
"github": "^13.1.0",
"hubot": "^2.19.0",
"hubot-azure-brain": "^1.0.0",
"hubot-brain-inspect": "0.0.1",
"hubot-commit-streak": "^1.0.7",
"hubot-diagnostics": "0.0.2",
"hubot-github-pr-reporter": "^1.1.5",
"hubot-github-webhook-listener": "^0.9.1",
"hubot-google-translate": "^0.2.1",
"hubot-help": "^0.2.2",
"hubot-heroku-keepalive": "^1.0.3",
"hubot-maps": "0.0.3",
"hubot-rcbrb": "^1.0.5",
"hubot-reload-scripts": "^0.1.4",
"hubot-scripts": "^2.17.2",
"hubot-slack": "^4.4.0",
"js-yaml": "^3.10.0",
"jwt-simple": "^0.5.1"
"probot": "^5.0.0",
"probot-config": "^0.1.0",
"probot-slack-status": "^0.2.2"
},
"devDependencies": {
"jest": "^22.1.4",
"smee-client": "^1.0.1",
"standard": "^10.0.3"
},
"engines": {
"node": "9.x.x"
"node": ">= 7.7.0",
"npm": ">= 4.0.0"
},
"standard": {
"env": [
"jest"
]
}
}

View File

@ -4,42 +4,42 @@
//
// Dependencies:
// github: "^13.1.0"
// hubot-github-webhook-listener: "^0.9.1"
// hubot-slack: "^4.4.0"
// probot-config "^0.1.0"
// probot-slack-status: "^0.2.2"
//
// Author:
// PombeirP
const getConfig = require('probot-config');
const Slack = require('probot-slack-status');
let slackClient = null;
module.exports = function(robot) {
// robot.on('slack.connected', ({ slack }) => {
Slack(robot, (slack) => {
robot.log.trace("Connected, assigned slackClient");
slackClient = slack;
});
robot.on('pull_request.opened', async context => {
// Make sure we don't listen to our own messages
if (context.isBot) { return; }
const gitHubContext = require('./github-context.js')();
return robot.on("github-repo-event", function(repo_event) {
const githubPayload = repo_event.payload;
switch(repo_event.eventType) {
case "pull_request":
// Make sure we don't listen to our own messages
if (gitHubContext.equalsRobotName(robot, githubPayload.pull_request.user.login)) { return; }
var { action } = githubPayload;
if (action === "opened") {
// A new PR was opened
return assignPullRequestToReview(gitHubContext, githubPayload, robot);
}
break;
}
// A new PR was opened
await assignPullRequestToReview(context, robot);
});
};
async function assignPullRequestToReview(gitHubContext, githubPayload, robot) {
const github = gitHubContext.api();
const githubConfig = gitHubContext.config();
const ownerName = githubPayload.repository.owner.login;
const repoName = githubPayload.repository.name;
const prNumber = githubPayload.pull_request.number;
async function assignPullRequestToReview(context, robot) {
const payload = context.payload;
const github = context.github;
const config = await getConfig(context, 'github-bot.yml')
const ownerName = payload.repository.owner.login;
const repoName = payload.repository.name;
const prNumber = payload.pull_request.number;
robot.logger.info(`assignPullRequestToReview - Handling Pull Request #${prNumber} on repo ${ownerName}/${repoName}`);
robot.log(`assignPullRequestToReview - Handling Pull Request #${prNumber} on repo ${ownerName}/${repoName}`);
// Fetch repo projects
// TODO: The repo project and project column info should be cached
@ -52,47 +52,56 @@ async function assignPullRequestToReview(gitHubContext, githubPayload, robot) {
});
// Find "Pipeline for QA" project
const projectBoardName = githubConfig['new-pull-requests']['project-board'].name;
const projectBoardName = config['new-pull-requests']['project-board'].name;
const project = ghprojects.data.find(function(p) { return p.name === projectBoardName });
if (!project) {
robot.logger.error(`Couldn't find project ${projectBoardName} in repo ${ownerName}/${repoName}`);
robot.log.error(`Couldn't find project ${projectBoardName} in repo ${ownerName}/${repoName}`);
return;
}
robot.logger.debug(`Fetched ${project.name} project (${project.id})`);
robot.log.debug(`Fetched ${project.name} project (${project.id})`);
// Fetch REVIEW column ID
try {
ghcolumns = await github.projects.getProjectColumns({ project_id: project.id });
const reviewColumnName = githubConfig['new-pull-requests']['project-board']['review-column-name'];
const reviewColumnName = config['new-pull-requests']['project-board']['review-column-name'];
const column = ghcolumns.data.find(function(c) { return c.name === reviewColumnName });
if (!column) {
robot.logger.error(`Couldn't find ${reviewColumnName} column in project ${project.name}`);
robot.log.error(`Couldn't find ${reviewColumnName} column in project ${project.name}`);
return;
}
robot.logger.debug(`Fetched ${column.name} column (${column.id})`);
robot.log.debug(`Fetched ${column.name} column (${column.id})`);
// Create project card for the PR in the REVIEW column
try {
ghcard = await github.projects.createProjectCard({
column_id: column.id,
content_type: 'PullRequest',
content_id: githubPayload.pull_request.id
content_id: payload.pull_request.id
});
robot.logger.debug(`Created card: ${ghcard.data.url}`, ghcard.data.id);
robot.log.debug(`Created card: ${ghcard.data.url}`, ghcard.data.id);
// Send message to Slack
robot.messageRoom(githubConfig.slack.notification.room, `Assigned PR to ${reviewColumnName} in ${projectBoardName} project\n${githubPayload.pull_request.html_url}`);
if (slackClient != null) {
const channel = slackClient.dataStore.getChannelByName(config.slack.notification.room);
try {
await slackClient.sendMessage(`Assigned PR to ${reviewColumnName} in ${projectBoardName} project\n${payload.pull_request.html_url}`, channel.id);
} catch(err) {
robot.log.error(`Failed to send Slack message to ${config.slack.notification.room} channel`);
}
} else {
robot.log.debug("Slack client not available");
}
} catch (err) {
robot.logger.error(`Couldn't create project card for the PR: ${err}`, column.id, githubPayload.pull_request.id);
robot.log.error(`Couldn't create project card for the PR: ${err}`, column.id, payload.pull_request.id);
}
} catch (err) {
robot.logger.error(`Couldn't fetch the github columns for project: ${err}`, ownerName, repoName, project.id);
robot.log.error(`Couldn't fetch the github columns for project: ${err}`, ownerName, repoName, project.id);
}
} catch (err) {
robot.logger.error(`Couldn't fetch the github projects for repo: ${err}`, ownerName, repoName);
robot.log.error(`Couldn't fetch the github projects for repo: ${err}`, ownerName, repoName);
}
};

View File

@ -4,96 +4,103 @@
//
// Dependencies:
// github: "^13.1.0"
// hubot-github-webhook-listener: "^0.9.1"
// hubot-slack: "^4.4.0"
// probot-config "^0.1.0"
// probot-slack-status: "^0.2.2"
//
// Author:
// PombeirP
const getConfig = require('probot-config');
const Slack = require('probot-slack-status');
let slackClient = null;
module.exports = function(robot) {
const gitHubContext = require('./github-context.js')();
return robot.on("github-repo-event", function(repo_event) {
const githubPayload = repo_event.payload;
switch(repo_event.eventType) {
case "issues":
// Make sure we don't listen to our own messages
if (gitHubContext.equalsRobotName(robot, githubPayload.issue.user.login)) { return; }
var { action } = githubPayload;
if (action === "labeled") {
// A new issue was labeled
return assignIssueToBountyAwaitingForApproval(gitHubContext, githubPayload, robot);
}
break;
}
// robot.on('slack.connected', ({ slack }) => {
Slack(robot, (slack) => {
robot.log.trace("Connected, assigned slackClient");
slackClient = slack;
});
robot.on('issues.labeled', async context => {
// Make sure we don't listen to our own messages
if (context.isBot) { return; }
// A new issue was labeled
await assignIssueToBountyAwaitingForApproval(context, robot);
});
};
async function assignIssueToBountyAwaitingForApproval(gitHubContext, githubPayload, robot) {
const github = gitHubContext.api();
const githubConfig = gitHubContext.config();
const ownerName = githubPayload.repository.owner.login;
const repoName = githubPayload.repository.name;
const issueNumber = githubPayload.issue.number;
robot.logger.info(`assignIssueToBountyAwaitingForApproval - Handling Issue #${issueNumber} on repo ${ownerName}/${repoName}`);
async function assignIssueToBountyAwaitingForApproval(context, robot) {
const github = context.github;
const payload = context.payload;
const config = await getConfig(context, 'github-bot.yml')
const ownerName = payload.repository.owner.login;
const repoName = payload.repository.name;
const issueNumber = payload.issue.number;
robot.log(`assignIssueToBountyAwaitingForApproval - Handling Issue #${issueNumber} on repo ${ownerName}/${repoName}`);
// Fetch org projects
// TODO: The org project and project column info should be cached
// in order to improve performance and reduce roundtrips
try {
const orgName = 'status-im';
ghprojects = await github.projects.getOrgProjects({
org: orgName,
state: "open"
});
// Find "Status SOB Swarm" project
const projectBoardName = githubConfig['bounty-awaiting-approval']['project-board'].name;
const projectBoardName = config['bounty-awaiting-approval']['project-board'].name;
const project = ghprojects.data.find(function(p) { return p.name === projectBoardName });
if (!project) {
robot.logger.error(`Couldn't find project ${projectBoardName} in ${orgName} org`);
robot.log.error(`Couldn't find project ${projectBoardName} in ${orgName} org`);
return;
}
robot.logger.debug(`Fetched ${project.name} project (${project.id})`);
robot.log.debug(`Fetched ${project.name} project (${project.id})`);
// Fetch bounty-awaiting-approval column ID
try {
ghcolumns = await github.projects.getProjectColumns({ project_id: project.id });
const approvalColumnName = githubConfig['bounty-awaiting-approval']['project-board']['approval-column-name'];
const approvalColumnName = config['bounty-awaiting-approval']['project-board']['approval-column-name'];
const column = ghcolumns.data.find(function(c) { return c.name === approvalColumnName });
if (!column) {
robot.logger.error(`Couldn't find ${approvalColumnName} column in project ${project.name}`);
robot.log.error(`Couldn't find ${approvalColumnName} column in project ${project.name}`);
return;
}
robot.logger.debug(`Fetched ${column.name} column (${column.id})`);
robot.log.debug(`Fetched ${column.name} column (${column.id})`);
// Create project card for the issue in the bounty-awaiting-approval column
try {
ghcard = await github.projects.createProjectCard({
column_id: column.id,
content_type: 'Issue',
content_id: githubPayload.issue.id
content_id: payload.issue.id
});
robot.logger.debug(`Created card: ${ghcard.data.url}`, ghcard.data.id);
robot.log.debug(`Created card: ${ghcard.data.url}`, ghcard.data.id);
// Send message to Slack
robot.messageRoom(githubConfig.slack.notification.room, `Assigned issue to ${approvalColumnName} in ${projectBoardName} project\n${githubPayload.issue.html_url}`);
if (slackClient != null) {
const channel = slackClient.dataStore.getChannelByName(config.slack.notification.room);
try {
await slackClient.sendMessage(`Assigned issue to ${approvalColumnName} in ${projectBoardName} project\n${payload.issue.html_url}`, channel.id);
} catch(err) {
robot.log.error(`Failed to send Slack message to ${config.slack.notification.room} channel`);
}
}
} catch (err) {
robot.logger.error(`Couldn't create project card for the issue: ${err}`, column.id, githubPayload.issue.id);
robot.log.error(`Couldn't create project card for the issue: ${err}`, column.id, payload.issue.id);
}
} catch (err) {
robot.logger.error(`Couldn't fetch the github columns for project: ${err}`, ownerName, repoName, project.id);
robot.log.error(`Couldn't fetch the github columns for project: ${err}`, ownerName, repoName, project.id);
}
} catch (err) {
robot.logger.error(`Couldn't fetch the github projects for repo: ${err}`, ownerName, repoName);
robot.log.error(`Couldn't fetch the github projects for repo: ${err}`, ownerName, repoName);
}
};

View File

@ -1,38 +0,0 @@
// Description:
// Script that handles startup tasks of the bot
//
// Dependencies:
//
// Author:
// PombeirP
let initializing = false;
module.exports = function(robot) {
robot.brain.on('loaded', async function() {
if (initializing) {
return;
}
initializing = true;
try {
const gitHubContext = require('./github-context.js')();
appID = robot.brain.get("github-app_id");
installationID = robot.brain.get("github-installation_id");
if (installationID) {
await gitHubContext.initialize(robot, appID, installationID);
robot.logger.debug("Bot ready");
} else {
robot.logger.debug("Bot waiting to be installed");
}
} catch(err) {
robot.logger.error(err);
} finally {
initializing = false;
}
})
}

View File

@ -1,173 +0,0 @@
// Description:
// Script that keeps GitHub-related context to be shared among scripts
//
// Dependencies:
// github: "^13.1.0"
//
// Author:
// PombeirP
const GitHubApi = require('github');
let cachedRobotNameRegex;
let initialized = false;
let initializing = false;
const githubAPI = new GitHubApi({
timeout: 15000,
requestMedia: 'application/vnd.github.v3+json'
});
let githubConfig = null;
module.exports = function() {
return {
api() { return githubAPI; },
config() { return githubConfig; },
async initialize(robot, integrationID, installationID) {
if (initialized || initializing) { return; }
initializing = true;
try {
if (githubConfig == null) {
githubConfig = loadConfig(robot, './github.yaml')
}
await ensureValidToken(robot, integrationID, installationID);
initialized = true;
} catch (err) {
// Do nothing
} finally {
initializing = false;
}
},
equalsRobotName(robot, str) {
return getRegexForRobotName(robot).test(str);
}
};
async function ensureValidToken(robot, integrationID, installationID) {
const token = getToken(robot);
if (token) {
process.env.HUBOT_GITHUB_TOKEN = token;
robot.logger.debug("Reused cached GitHub token");
githubAPI.authenticate({ type: 'token', token });
return;
}
const jwtLib = require('jwt-simple');
// Private key contents
let privateKey = process.env.GITHUB_PEM;
const now = Math.round(Date.now() / 1000);
// Generate the JWT
const payload = {
// issued at time
iat: now,
// JWT expiration time (10 minute maximum)
exp: now + (1 * 60),
// GitHub App's identifier
iss: integrationID
};
jwt = jwtLib.encode(payload, privateKey, 'RS256');
githubAPI.authenticate({
type: 'integration',
token: jwt
});
robot.logger.debug("Configured integration authentication with JWT", jwt);
await createAccessToken(robot, githubAPI, installationID);
}
function getRegexForRobotName(robot) {
// This comes straight out of Hubot's Robot.coffee
// - they didn't get a nice way of extracting that method though
if (!cachedRobotNameRegex) {
let namePattern;
const name = robot.name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
if (robot.alias) {
const alias = robot.alias.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
namePattern = `^\\s*[@]?(?:${alias}|${name})`;
} else {
namePattern = `^\\s*[@]?${name}`;
}
cachedRobotNameRegex = new RegExp(namePattern, 'i');
}
return cachedRobotNameRegex;
}
};
function loadConfig(robot, fileName) {
// Get document, or throw exception on error
try {
const yaml = require('js-yaml');
const fs = require('fs');
return yaml.safeLoad(fs.readFileSync(fileName, 'utf8'));
} catch (e) {
robot.logger.error(e);
}
return null;
}
function getToken(robot) {
const expiresAt = robot.brain.get('github-token-expires-at');
token = robot.brain.get('github-token');
if (expiresAt) {
expiresAt = Date.parse(expiresAt);
if (Date.now() >= expiresAt - 60 * 1000) {
robot.logger.debug("Cached GitHub token has expired");
token = null; // Token has expired
}
} else {
// If no expiration is set, assume this is an old deployment and invalidate the token
token = null;
}
return token;
}
function expireGitHubToken(robot) {
const gitHubContext = require('./github-context.js')();
robot.brain.set('github-token', null);
process.env.HUBOT_GITHUB_TOKEN = null;
appID = robot.brain.get("github-app_id");
installationID = robot.brain.get("github-installation_id");
if (installationID) {
gitHubContext.ensureValidToken(robot, appID, installationID);
}
}
async function createAccessToken(robot, github, id) {
try {
robot.logger.debug("Creating GitHub access token for installation");
response = await github.apps.createInstallationToken({ installation_id: id });
process.env.HUBOT_GITHUB_TOKEN = response.data.token;
robot.brain.set('github-token', response.data.token);
robot.brain.set('github-token-expires-at', response.data.expires_at);
expiresAt = Date.parse(response.data.expires_at);
setTimeout(expireGitHubToken, (expiresAt - 60 * 1000) - Date.now(), robot);
github.authenticate({
type: 'token',
token: response.data.token
});
robot.logger.debug(`Created GitHub access token for installation, expires at ${response.data.expires_at}`);
} catch (err) {
robot.logger.error(`Couldn't create installation token: ${err}`, id);
throw err;
}
}

View File

@ -1,63 +0,0 @@
// Description:
// Script that handles the installation of the GitHub app
//
// Dependencies:
// github: "^13.1.0"
// hubot-github-webhook-listener: "^0.9.1"
//
// Author:
// PombeirP
module.exports = function(robot) {
const gitHubContext = require('./github-context.js')();
return robot.on("github-repo-event", async function(repo_event) {
const githubPayload = repo_event.payload;
robot.logger.debug(`Received ${repo_event.eventType}/${githubPayload.action} event from GitHub`);
switch(repo_event.eventType) {
case "integration_installation":
// Make sure we don't listen to our own messages
if (gitHubContext.equalsRobotName(robot, githubPayload.sender.login)) { return; }
var { action } = githubPayload;
switch (action) {
case "created":
// App was installed on an organization
robot.logger.info(`Initializing installation for app with ID ${githubPayload.installation.app_id} and installation ID ${githubPayload.installation.id}`);
robot.brain.set('github-app_id', githubPayload.installation.app_id);
robot.brain.set('github-installation_id', githubPayload.installation.id);
await gitHubContext.initialize(robot, githubPayload.installation.app_id, githubPayload.installation.id);
var perms = githubPayload.installation.permissions;
if (perms.repository_projects !== 'write') { robot.logger.error(formatPermMessage('repository_projects', 'write')); }
if (perms.metadata !== 'read') { robot.logger.error(formatPermMessage('metadata', 'read')); }
if (perms.issues !== 'read') { robot.logger.error(formatPermMessage('issues', 'read')); }
if (perms.pull_requests !== 'write') { robot.logger.error(formatPermMessage('pull_requests', 'write')); }
if (!githubPayload.installation.events.includes('pull_request')) {
robot.logger.error("Please enable 'pull_request' events in the app configuration on github.com");
}
break;
case "deleted":
// App was uninstalled from an organization
robot.logger.info(`Removing installation for app with ID ${githubPayload.installation.app_id} and installation ID ${githubPayload.installation.id}`);
robot.brain.set('github-app_id', null);
robot.brain.set('github-installation_id', null);
robot.brain.set('github-token-expires-at', null);
robot.brain.set('github-token', null);
process.env.HUBOT_GITHUB_TOKEN = null;
break;
}
break;
}
});
};
var formatPermMessage = (permName, perm) => `Please enable '${permName}' ${perm} permission in the app configuration on github.com`;

View File

@ -4,52 +4,52 @@
//
// Dependencies:
// github: "^13.1.0"
// hubot-github-webhook-listener: "^0.9.1"
// probot-config "^0.1.0"
// probot-slack-status: "^0.2.2"
//
// Author:
// PombeirP
const getConfig = require('probot-config');
const Slack = require('probot-slack-status');
let slackClient = null;
module.exports = function(robot) {
// robot.on('slack.connected', ({ slack }) => {
Slack(robot, (slack) => {
robot.log.trace("Connected, assigned slackClient");
slackClient = slack;
});
const gitHubContext = require('./github-context.js')();
return robot.on("github-repo-event", function(repo_event) {
const githubPayload = repo_event.payload;
switch(repo_event.eventType) {
case "pull_request":
// Make sure we don't listen to our own messages
if (gitHubContext.equalsRobotName(robot, githubPayload.pull_request.user.login)) { return; }
var { action } = githubPayload;
if (action === "opened") {
// A new PR was opened
return greetNewContributor(gitHubContext, githubPayload, robot);
}
break;
}
robot.on('pull_request.opened', async context => {
// Make sure we don't listen to our own messages
if (context.isBot) { return; }
// A new PR was opened
await greetNewContributor(context, robot);
});
};
async function greetNewContributor(gitHubContext, githubPayload, robot) {
// TODO: Read the welcome message from a (per-repo?) file (e.g. status-react.welcome-msg.md)
const github = gitHubContext.api();
const githubConfig = gitHubContext.config();
const welcomeMessage = githubConfig['new-pull-requests']['welcome-bot'].message;
const ownerName = githubPayload.repository.owner.login;
const repoName = githubPayload.repository.name;
const prNumber = githubPayload.pull_request.number;
robot.logger.info(`greetNewContributor - Handling Pull Request #${prNumber} on repo ${ownerName}/${repoName}`);
async function greetNewContributor(context, robot) {
const payload = context.payload;
const github = context.github;
const config = await getConfig(context, 'github-bot.yml')
const welcomeMessage = config['new-pull-requests']['welcome-bot'].message;
const ownerName = payload.repository.owner.login;
const repoName = payload.repository.name;
const prNumber = payload.pull_request.number;
robot.log(`greetNewContributor - Handling Pull Request #${prNumber} on repo ${ownerName}/${repoName}`);
try {
ghissues = await github.issues.getForRepo({
owner: ownerName,
repo: repoName,
state: 'all',
creator: githubPayload.pull_request.user.login
creator: payload.pull_request.user.login
})
const userPullRequests = ghissues.data.filter(issue => issue.pull_request);
if (userPullRequests.length === 1) {
try {
@ -59,18 +59,25 @@ async function greetNewContributor(gitHubContext, githubPayload, robot) {
number: prNumber,
body: welcomeMessage
})
// Send message to Slack
robot.messageRoom(githubConfig.slack.notification.room, `Greeted ${githubPayload.pull_request.user.login} on his first PR in the ${repoName} repo\n${githubPayload.pull_request.html_url}`);
if (slackClient != null) {
const channel = slackClient.dataStore.getChannelByName(config.slack.notification.room);
try {
await slackClient.sendMessage(`Greeted ${payload.pull_request.user.login} on his first PR in the ${repoName} repo\n${payload.pull_request.html_url}`, channel.id);
} catch(err) {
robot.log.error(`Failed to send Slack message to ${config.slack.notification.room} channel`);
}
}
} catch (err) {
if (err.code !== 404) {
robot.logger.error(`Couldn't create comment on PR: ${err}`, ownerName, repoName);
robot.log.error(`Couldn't create comment on PR: ${err}`, ownerName, repoName);
}
}
} else {
robot.logger.debug("This is not the user's first PR on the repo, ignoring", ownerName, repoName, githubPayload.pull_request.user.login);
robot.log.debug("This is not the user's first PR on the repo, ignoring", ownerName, repoName, payload.pull_request.user.login);
}
} catch (err) {
robot.logger.error(`Couldn't fetch the user's github issues for repo: ${err}`, ownerName, repoName);
robot.log.error(`Couldn't fetch the user's github issues for repo: ${err}`, ownerName, repoName);
}
};