Port from Hubot to Probot

This commit is contained in:
Pedro Pombeiro 2018-01-22 14:48:57 +01:00
parent ad60e09633
commit 943bf12e0e
No known key found for this signature in database
GPG Key ID: A65DEB11E4BBC647
14 changed files with 7740 additions and 2 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'

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules/

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,2 +1,59 @@
# status-github-bot
A bot for github
# statusbot
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!
[probot]: https://probot.github.io/docs/deployment/
## What does the bot do?
Right now the bot has two sets of capabilities:
- 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 `/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. 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`).
## Restart the bot
You may want to get comfortable with `heroku logs` and `heroku restart` if
you're having issues.

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/

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/
}

7212
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

31
package.json Normal file
View File

@ -0,0 +1,31 @@
{
"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": {
"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": ">= 7.7.0",
"npm": ">= 4.0.0"
},
"standard": {
"env": [
"jest"
]
}
}

View File

@ -0,0 +1,107 @@
// Description:
// Script that listens to new GitHub pull requests
// and assigns them to the REVIEW column on the "Pipeline for QA" project
//
// Dependencies:
// github: "^13.1.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; }
// A new PR was opened
await assignPullRequestToReview(context, robot);
});
};
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.log(`assignPullRequestToReview - Handling Pull Request #${prNumber} on repo ${ownerName}/${repoName}`);
// Fetch repo projects
// TODO: The repo project and project column info should be cached
// in order to improve performance and reduce roundtrips
try {
ghprojects = await github.projects.getRepoProjects({
owner: ownerName,
repo: repoName,
state: "open"
});
// Find "Pipeline for QA" project
const projectBoardName = config['new-pull-requests']['project-board'].name;
const project = ghprojects.data.find(function(p) { return p.name === projectBoardName });
if (!project) {
robot.log.error(`Couldn't find project ${projectBoardName} in repo ${ownerName}/${repoName}`);
return;
}
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 = config['new-pull-requests']['project-board']['review-column-name'];
const column = ghcolumns.data.find(function(c) { return c.name === reviewColumnName });
if (!column) {
robot.log.error(`Couldn't find ${reviewColumnName} column in project ${project.name}`);
return;
}
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: payload.pull_request.id
});
robot.log.debug(`Created card: ${ghcard.data.url}`, ghcard.data.id);
// Send message to Slack
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.log.error(`Couldn't create project card for the PR: ${err}`, column.id, payload.pull_request.id);
}
} catch (err) {
robot.log.error(`Couldn't fetch the github columns for project: ${err}`, ownerName, repoName, project.id);
}
} catch (err) {
robot.log.error(`Couldn't fetch the github projects for repo: ${err}`, ownerName, repoName);
}
};

View File

@ -0,0 +1,106 @@
// Description:
// Script that listens to new labels on GitHub issues
// and assigns the issues to the bounty-awaiting-approval column on the "Status SOB Swarm" project
//
// Dependencies:
// github: "^13.1.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('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(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 = config['bounty-awaiting-approval']['project-board'].name;
const project = ghprojects.data.find(function(p) { return p.name === projectBoardName });
if (!project) {
robot.log.error(`Couldn't find project ${projectBoardName} in ${orgName} org`);
return;
}
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 = config['bounty-awaiting-approval']['project-board']['approval-column-name'];
const column = ghcolumns.data.find(function(c) { return c.name === approvalColumnName });
if (!column) {
robot.log.error(`Couldn't find ${approvalColumnName} column in project ${project.name}`);
return;
}
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: payload.issue.id
});
robot.log.debug(`Created card: ${ghcard.data.url}`, ghcard.data.id);
// Send message to Slack
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.log.error(`Couldn't create project card for the issue: ${err}`, column.id, payload.issue.id);
}
} catch (err) {
robot.log.error(`Couldn't fetch the github columns for project: ${err}`, ownerName, repoName, project.id);
}
} catch (err) {
robot.log.error(`Couldn't fetch the github projects for repo: ${err}`, ownerName, repoName);
}
};

View File

@ -0,0 +1,83 @@
// Description:
// Script that listens to new GitHub pull requests
// and greets the user if it is their first PR on the repo
//
// Dependencies:
// github: "^13.1.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; }
// A new PR was opened
await greetNewContributor(context, robot);
});
};
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: payload.pull_request.user.login
})
const userPullRequests = ghissues.data.filter(issue => issue.pull_request);
if (userPullRequests.length === 1) {
try {
await github.issues.createComment({
owner: ownerName,
repo: repoName,
number: prNumber,
body: welcomeMessage
})
// Send message to Slack
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.log.error(`Couldn't create comment on PR: ${err}`, ownerName, repoName);
}
}
} else {
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.log.error(`Couldn't fetch the user's github issues for repo: ${err}`, ownerName, repoName);
}
};