User Guide
6.4
6.4
  • Rocket.Chat
    • Our Plans
  • Deploy
    • Deploy Rocket.Chat
      • System Requirements
      • Deploy with Docker & Docker Compose
      • Deploy with AWS
      • Deploy with Snaps
      • Updating Rocket.Chat
      • Scaling Rocket.Chat
        • Microservices
        • Running Multiple Instances
        • Automation Tools
          • Ansible
          • OpenShift
          • Vagrant
      • Additional Deployment Methods
        • Deploy with Kubernetes
        • Deploy with Digital Ocean
        • Deploy on Google Compute Engine
        • Deploy with Ubuntu
        • Deploy with CentOS
        • Deploy on Kali
        • Deploy on Debian
        • Deploy on IBM Cloud
        • Deploy on Windows 10
        • Plug-in Deployments
        • Unsupported Methods
          • OpenSUSE Leap 42.2
          • FreeBSD
            • Deploying Rocket.Chat Server Binaries on a FreeBSD system
          • Windows Server
          • Linode
          • Scalingo
          • Cloudron.io
          • Jelastic
          • Aliyun
          • Galaxy
          • Syncloud
          • OpenShift
  • Setup and Configure
    • Environment Configuration
      • Deployment Environment Variables
        • Manage Settings Using Environmental Variables
      • MongoDB Configuration
        • MongoDB URI Authentication
        • MongoDB Backup and Restore
        • Additional MongoDB Driver Options
        • Configure a Replica Set for MongoDB
        • Migrate from Built-In Meteor MongoDB to External Server
        • Migrate from mmap to WiredTiger Storage Engine
        • Supported MongoDB Versions
      • Firewall Configuration
      • Configuring SSL Reverse Proxy
      • Additional Configurations
        • Running in a sub folder with Apache
        • Univention Corporate Server (UCS)
        • Setting Up Client SSL Certificate Authentication for Rocket.Chat
        • Setting up Process Managers and Init Systems
      • Check Node.js Version
    • Installing Client Apps
      • Desktop & Mobile Apps
      • Minimum Requirements for Client Apps
    • Trials
      • Pro Trial
      • Enterprise Trial
    • License Application
    • Accessing Your Workspace
      • Rocket.Chat Setup Wizard
      • Admin Account Creation
      • Basic White-labeling
      • Inviting Users
    • Advanced workspace management
      • Google Translate Integration
      • Database Migration
      • Restoring an Admin User
      • CDN
      • Troubleshooting
      • Client Compatibility Matrix
    • Rocket.Chat Air-gapped Deployment
      • Offline Workspace Registration
      • Offline License
      • Air-gapped workspace Configuration
      • Air-gapped App Installation
    • Roles in Rocket.Chat
  • Use Rocket.Chat
    • User Guides
      • Access your workspace
      • Main Menu
      • User Panel
        • Account
        • Accessibility and appearance
        • Manage Devices
      • Rooms
        • Channels
          • Create a new Channel
          • Edit A Channel
          • Manage Channel Members
          • Search Messages in a Channel
        • Teams
          • Create a new Team
          • Edit a Team
          • Manage Team Members
          • Manage Team Channels
          • Teams Premium Plan
        • Discussions
          • Create a new Discussion
          • Edit A Discussion
          • Search Messages in Discussion
          • Manage Discussion Members
        • Direct Messages
          • Create a new Direct Message
          • Direct Message Actions
        • Threads
          • Create a New Thread
        • Room Roles
      • Messages
        • Message Actions
        • Off-the-record (OTR) Messaging User Guide
      • Notifications
      • Security Bundle
        • Data Loss Prevention User Guide
        • End to End Encryption User Guide
        • Two Factor Authentication User Guide
      • Keyboard Shortcuts
    • Workspace Administration
      • Workspace
      • Subscription
      • Registration
      • Engagement
      • Moderation
      • Federation
      • Rooms
      • Users
        • Guest Users
        • Monthly Active Contacts (MACs)
        • Add users through Identity management and authentication services
      • Invites
      • User Status
      • Permissions
        • Setting's Permission
      • Device Management
      • Email Inboxes
      • Mailer
      • Third-party Login
      • Integrations
        • AppVeyor
        • Azure Alerts
        • BitRocket
        • Dead Simple Screen Sharing
        • EasyRedmine
        • Giphy Integrations
        • GitLab
        • Google Calendar
        • GitHub
        • Graylog
        • Jenkins notifications via Rocket.Chat Marketplace
        • JFrog Xray
        • MicroBadger
        • Microsoft Teams
        • NewRelic
        • Nextcloud and WebDAV integrations
        • Nextcloud Rocket.Chat App
        • Nixstats notification
        • PagerDuty
        • Prometheus
        • Grafana
        • Review Board
        • RunDeck Job Notifications
        • Sentry
        • Simple Telegram Bot
        • TravisCI
        • Uptime Robot
        • Zapier
        • django-rocketchat-auth 1.2
        • Add Jira notifications via webhook
      • Import
        • Import from HipChat
        • Import from Slack
          • SlackBridge
        • Import CSV
      • Reports
      • Sounds
      • Emoji
      • Settings
        • Accounts
          • Custom Fields
        • Analytics
        • Assets
        • Bots
        • CAS
        • Conference Call
        • Custom Emoji Filesystem
        • Custom Sound Filesystem
        • Discussion
        • E2E Encryption
        • Email
          • Edit your Email Content
          • Direct email reply
          • Email configuration
        • Federation
          • Matrix Bridge
            • Matrix Admin Guide
              • Matrix Homeserver Setup
                • Matrix Allow/Block List
              • Matrix Bridge Configuration
            • Matrix User's Guide
              • Create federated rooms
              • Invite external users to your Rocket.Chat server
              • Communicate with a federated user
              • Search and join public channels on the Matrix network
              • Assign roles for users in federated rooms
            • Matrix Bridge FAQs
          • Rocket.Chat Basic Federation
            • Cross-server Federated Channels
        • File Upload
          • Minio
          • Recommendations for File Upload
          • File Upload FAQs
        • General
          • Net Promoter Score (NPS) survey
        • IRC Federation
        • Layout
        • LDAP
        • Logs
        • Message
        • Meta
        • Mobile
        • Omnichannel Admin's Guide
          • Queue Types (Routing Algorithm)
        • OTR
        • Outlook Calendar
        • Premium
        • Push
        • Rate Limiter
        • Retention Policy
        • SAML
        • Page
        • Search
        • Setup Wizard
        • SlackBridge
        • Smarsh
        • SMS
        • Threads
        • Troubleshoot
        • User Data Download
        • Voice Channel
        • Webdav Integration
        • WebRTC
        • OAuth
        • Device Management
    • Authentication
      • Authentication Across Plans
      • LDAP
        • Configure LDAP Connection
        • LDAP User Search
        • LDAP Data Sync Settings
        • LDAP Premium Settings
        • LDAP Setup
      • SAML
        • SAML Configuration
        • Active Directory Federation Services
        • Keycloak
      • OAuth
        • Facebook OAuth Setup
        • Google OAuth Setup
        • GitLab OAuth Setup
        • GitHub OAuth Setup
        • LinkedIn OAuth Setup
        • Nextcloud OAuth Setup
        • WordPress OAuth Setup
        • MS Office 365 Custom OAuth Setup
        • Additional OAuth Methods
      • OpenID Connect
        • Keycloak
        • Okta Identity Cloud Service
      • Iframe-based Single Sign-On
    • User Management
      • Custom Roles
      • Device Manager
        • Device Management Settings
      • Message Auditor
        • Audit Edits, Deletions, and Encrypted Communications
        • Audit Logs
    • Omnichannel
      • Current Chats
      • Omnichannel Reports
      • Analytics
      • Real-time Monitoring
      • Managers
      • Agents
      • Departments
      • Custom Fields
      • Livechat Triggers
      • Livechat Widget Installation
      • Livechat Widget Appearance
      • Webhooks
      • Business Hours
      • Monitors
      • Units
      • Canned Responses
        • Canned Responses Omnichannel Manager's Guide
      • Tags
      • SLA Policies
      • Priorities
    • Rocket.Chat Cloud
      • Create your new cloud account
      • Manage your cloud account
        • Custom domain for your Cloud-hosted workspace
        • Profile
        • Organization Settings
        • Workspaces
        • Invoices
        • Payment Methods
        • Security
        • Support
        • Contact Sales
    • Rocket.Chat Voice Channel
      • Getting Started with Voice Channel
      • Voice Channel Admin Guide
        • Configure without previously having a PBX server
          • SIP Extensions
          • Configure asterisk manager interface and users
        • Configure with an active PBX server
          • Associate agents with extensions in Rocket.Chat
      • Voice Channel Technical Specification
      • Voice Channel Agent Guides
        • How to make myself available to accept calls?
        • How to take a call in Rocket.Chat voice channel?
        • How to initiate an outbound call as an agent?
      • Voice Channel FAQs
    • Rocket.Chat Conference Call
      • Conference Call Admin Guide
        • Pexip app
        • Jitsi app
        • BigBlueButton (BBB) app
        • Google Meet app
      • Conference Call User's Guide
      • Omnichannel Video/Audio Call Configuration
    • Rocket.Chat Federation
    • Rocket.Chat Mobile
      • Rooms on Rocket.Chat Mobile
      • Messages and Threads on Mobile
      • Push Notifications
        • Secured Push Notification
        • Push Notifications User Guide
    • Omnichannel Agent's Guides
      • Omnichannel Conversation
      • Omnichannel Queue
      • Omnichannel Contact Center
        • Omnichannel Contact Manager Assignment
      • Email Inboxes
  • Extend Rocket.Chat Capabilities
    • Rocket.Chat Marketplace
      • Rocket.Chat Public Apps Guides
        • Omnichannel Apps
          • SMS
          • Telegram App
            • Telegram Agent's Guide
          • Rasa App
          • Salesforce CRM Integration
            • Salesforce CRM Agent's Guide
          • HubSpot CRM
            • HubSpot CRM Agent's Guide
          • Dialogflow App
            • Upload File To Ongoing Dialogflow Chats
          • Twitter App
            • Twitter App Agent's Guide
          • Facebook App
            • Facebook App Agent's Guide
          • WhatsApp
            • WhatsApp Agent's Guide
          • WhatsApp Sandbox
            • WhatsApp Sandbox Agent's Guide
          • Instagram Direct
            • Instagram Direct Agent's Guide
          • WhatsApp Cloud App
            • Configure Whatsapp Cloud App
            • Using WhatsApp Cloud App
        • Atlassian Apps
          • Jira Server v2.0
          • Bamboo Integration
          • Bitbucket Server
          • Confluence Server
          • Jira Server
        • Pexip App
        • Jitsi app
        • BigBlueButton (BBB) app
        • Google Meet app
        • Trello
          • Using the Trello App
        • Zoom
          • Using the Zoom App
        • Data Loss Prevention (DLP) App
        • Poll
        • Poll Plus
          • Poll Plus Features
        • Microsoft Teams Bridge
          • Using Microsoft Teams Bridge
        • GitHub App
          • Using GitHub App
        • Google Drive
          • Using the Google Drive App
        • Google Calendar
          • Using the Google Calendar App
        • Zapier App
          • Install Zapier App
          • Using Zapier App
        • ChatGPT App
          • Using the ChatGPT App
        • Mod Assist App
          • Using the Mod Assist App
        • ClamAV Integration
      • App Storage Location
    • Integrations
    • Rocket.Chat API
  • Resources
    • Frequently Asked Questions
      • Accessing your workspace FAQs
      • License FAQs
        • Trial FAQ
        • Downgrade behavior
        • Fair use allowance FAQs
      • My Account FAQs
      • Registration
      • Message Privacy
      • Localization
      • Apps FAQs
      • Update FAQs
      • WhatsApp Cloud API FAQs
      • Cloud FAQs
      • Support FAQs
      • Whatsapp Business App FAQs
      • Identity Management FAQ
      • Deployment FAQ
        • Updating Rocket.Chat FAQ
        • Snaps FAQ
      • Federation FAQs
      • Monthly Active Contacts FAQs
      • Omnichannel FAQs
    • Brand and Visual Guidelines
      • Logo
      • Typography
      • Colors
      • Patterns
      • Iconography
      • Photos
      • Brand Usage Examples
      • Media Kit
    • Developer Documentation
    • Glossary
  • Contribute to Rocket.Chat
    • Contributor Code of Conduct
    • How Can I Help?
    • Annual Contribution Programs
  • APPLICABLE TERMS
    • Customer Terms of Service
    • Additional Terms
      • Terms of Use
      • Acceptable Use Policy
      • Service-Specific Terms
        • Master Service Agreement for Professional Services
        • Cloud Services Terms
          • Marketplace and Apps
  • CUSTOMER CENTER
    • Cloud Services Center
      • Rocket.Chat Cloud Hosting Service Level Agreement (SLA)
    • Security Center
      • Security Policy
      • Compliance Resources
      • Security fixes and updates
        • cve-2022-32211
      • End-to-End Encryption Specifications
    • Support Center
      • Premium Support Plans
        • Support Prerequisites and Version Durability
        • Premium Support Channels
        • Our Support Ticket Classification System and SLAs
        • Rocket.Chat Legacy Support
      • Community Resources
    • Legal Center
      • Privacy Policy
        • Subprocessors
        • Privacy Policy Facebook Messenger
        • Privacy Notice for Air-Gapped Workspaces
      • GDPR
        • Data Processing Agreement
      • LGDP
        • Nomeação do Encarregado pelo Tratamento de Dados Pessoais
      • DMCA Policy
      • Accessibility statement
      • Code of Conduct: Services
      • Law Enforcement
        • Guidelines for Law Enforcement
        • Censorship and Harmful Content
        • Server Lookup
      • Historical Agreements and Policy Archive
Powered by GitBook
On this page
  • GitHub Rocket.Chat Integration
  • Rocket.Chat Incoming webhook with GitHub
  • Rocket.Chat GitHub Outgoing Webhook
  • Customizing your integration scripts
  1. Use Rocket.Chat
  2. Workspace Administration
  3. Integrations

GitHub

Setting up GitHub webhook integration with Rocket.Chat gives you the ability to

  1. Receive event notifications from GitHub directly in your specified Rocket.Chat room (Incoming WebHook)

  2. Send commands to GitHub and optionally receive a response (Outgoing WebHook).

These events include and are not limited to:

  • Comments

  • Issues events

  • Pull Requests

  • Merge requests

  • Deployment events

  • Comments and discussions

  • Tags, label and branch actions

  • etc.

In configuring this integration, make sure your Rocket.Chat is publicly available on a URL.

GitHub Rocket.Chat Integration

We are going to see how to create both incoming and outgoing webhook integration between Rocket.Chat and GitHub.

Rocket.Chat Incoming webhook with GitHub

To configure an incoming webhook integration between GitHub and Rocket.Chat, you need to:

The following steps explain how to do this

Creating new GitHub webhook integration

  • Go to the Administration -> Workspace -> Integrations settings on your Rocket.Chat workspace

  • Switch to the Incoming tab and create a New Integration

  • Fill in the details of your webhook including the name of the webhook, the room to post into, the user to post as and enable it

  • Enable Scripts and paste any of the following example code into the Scripts box.

GitHub Example Script 1

This script will generate notifications for the following repository events:

  • Issue events (create, edit, close, reopen, assign, label, etc)

  • Issue comment events

  • Push events (singular and multiple commits)

/* exported Script */

String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

const getLabelsField = (labels) => {
  let labelsArray = [];
  labels.forEach(function(label) {
    labelsArray.push(label.name);
  });
  labelsArray = labelsArray.join(', ');
  return {
    title: 'Labels',
    value: labelsArray,
    short: labelsArray.length <= 40
  };
};

const githubEvents = {
  ping(request) {
    return {
      content: {
        text: '_' + request.content.hook.id + '_\n' + ':thumbsup: ' + request.content.zen
      }
    };
  },

  /* NEW OR MODIFY ISSUE */
  issues(request) {
    const user = request.content.sender;

    if (request.content.action == "opened" || request.content.action == "reopened" || request.content.action == "edited") {
        var body = request.content.issue.body;
    } else if (request.content.action == "labeled") {
        var body = "Current labels: " + getLabelsField(request.content.issue.labels).value;
    } else if (request.content.action == "assigned" || request.content.action == "unassigned") {
        // Note that the issues API only gives you one assignee.
        var body = "Current assignee: " + request.content.issue.assignee.login;
    } else if (request.content.action == "closed") {
        if (request.content.issue.closed_by) {
            var body = "Closed by: " + request.content.issue.closed_by.login;
        } else {
            var body = "Closed.";
        }
    } else {
        return {
          error: {
            success: false,
            message: 'Unsupported issue action'
          }
        };
    }

    const action = request.content.action.capitalizeFirstLetter();

    const text = '_' + request.content.repository.full_name + '_\n' +
                '**[' + action + ' issue ​#' + request.content.issue.number +
                ' - ' + request.content.issue.title + '](' +
                request.content.issue.html_url + ')**\n\n' +
                body;

    return {
      content: {
        attachments: [
            {
                thumb_url: user.avatar_url,
                text: text,
                fields: []
            }
        ]
      }
    };
  },

  /* COMMENT ON EXISTING ISSUE */
  issue_comment(request) {
    const user = request.content.comment.user;

    if (request.content.action == "edited") {
        var action = "Edited comment ";
    } else {
        var action = "Comment "
    }

    const text = '_' + request.content.repository.full_name + '_\n' +
                '**[' + action + ' on issue ​#' + request.content.issue.number +
                ' - ' + request.content.issue.title + '](' +
                request.content.comment.html_url + ')**\n\n' +
                request.content.comment.body;

    return {
      content: {
        attachments: [
            {
                thumb_url: user.avatar_url,
                text: text,
                fields: []
            }
        ]
      }
    };
  },

 /* COMMENT ON COMMIT */
commit_comment(request) {
    const user = request.content.comment.user;

    if (request.content.action == "edited") {
        var action = "Edited comment ";
    } else {
        var action = "Comment "
    }

    const text = '_' + request.content.repository.full_name + '_\n' +
                '**[' + action + ' on commit id ' + request.content.comment.commit_id +
                ' - ' +  + '](' +
                request.content.comment.html_url + ')**\n\n' +
                request.content.comment.body;

    return {
      content: {
        attachments: [
            {
                thumb_url: user.avatar_url,
                text: text,
                fields: []
            }
        ]
      }
    };
  },
  /* END OF COMMENT ON COMMIT */

  /* PUSH TO REPO */
  push(request) {
    var commits = request.content.commits;
    var multi_commit = ""
    var is_short = true;
    var changeset = 'Changeset';
    if ( commits.length > 1 ) {
      var multi_commit = " [Multiple Commits]";
      var is_short = false;
      var changeset = changeset + 's';
      var output = [];
    }
    const user = request.content.sender;

    var text = '**Pushed to ' + "["+request.content.repository.full_name+"]("+request.content.repository.url+"):"
                + request.content.ref.split('/').pop() + "**\n\n";

    for (var i = 0; i < commits.length; i++) {
      var commit = commits[i];
      var shortID = commit.id.substring(0,7);
      var a = '[' + shortID + '](' + commit.url + ') - ' + commit.message;
      if ( commits.length > 1 ) {
        output.push( a );
      } else {
        var output = a;
      }
    }

    if (commits.length > 1) {
      text += output.reverse().join('\n');
    } else {
      text += output;
    }

    return {
      content: {
        attachments: [
            {
                thumb_url: user.avatar_url,
                text: text,
                fields: []
            }
        ]
      }
    };
  },  // End GitHub Push

  /* NEW PULL REQUEST */
  pull_request(request) {
    const user = request.content.sender;

   if (request.content.action == "opened" || request.content.action == "reopened" || request.content.action == "edited" || request.content.action == "synchronize") {
        var body = request.content.pull_request.body;
    } else if (request.content.action == "labeled") {
        var body = "Current labels: " + getLabelsField(request.content.pull_request.labels).value;
    } else if (request.content.action == "assigned" || request.content.action == "unassigned") {
        // Note that the issues API only gives you one assignee.
        var body = "Current assignee: " + request.content.pull_request.assignee.login;
    } else if (request.content.action == "closed") {
        if (request.content.pull_request.merged) {
            var body = "Merged by: " + request.content.pull_request.merged_by.login;
        } else {
            var body = "Closed.";
        }
    } else {
        return {
          error: {
            success: false,
            message: 'Unsupported pull request action'
          }
        };
    }

    const action = request.content.action.capitalizeFirstLetter();

    const text = '_' + request.content.repository.full_name + '_\n' +
                '**[' + action + ' pull request ​#' + request.content.pull_request.number +
                ' - ' + request.content.pull_request.title + '](' +
                request.content.pull_request.html_url + ')**\n\n' +
                body;

    return {
      content: {
        attachments: [
            {
                thumb_url: user.avatar_url,
                text: text,
                fields: []
            }
        ]
      }
    };
  },
};

class Script {
  process_incoming_request({ request }) {
    const header = request.headers['x-github-event'];
    if (githubEvents[header]) {
      return githubEvents[header](request);
    }

    return {
      error: {
        success: false,
        message: 'Unsupported method'
      }
    };
  }
}
GitHub Example Script 2

This script will generate notifications for the following repository events:

  • New and closed issue events

  • Comment events (issues only)

  • Push events (singular and multiple commits)

/* exported Script */

// Begin embedded images
const gh_cmit_svg = '<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" class="octicon octicon-git-commit" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M10.86 7c-.45-1.72-2-3-3.86-3-1.86 0-3.41 1.28-3.86 3H0v2h3.14c.45 1.72 2 3 3.86 3 1.86 0 3.41-1.28 3.86-3H14V7h-3.14zM7 10.2c-1.22 0-2.2-.98-2.2-2.2 0-1.22.98-2.2 2.2-2.2 1.22 0 2.2.98 2.2 2.2 0 1.22-.98 2.2-2.2 2.2z"></path></svg>';
const gh_pr_svg = '<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" class="octicon octicon-git-pull-request" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"></path></svg>';
const gh_iss_svg = '<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" class="octicon octicon-issue-opened" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"></path></svg>';
const svg_inline_prefix = 'data:image/svg+xml;ascii,';
// End embedded images

const getLabelsField = (labels) => {
  let labelsArray = [];
  labels.forEach(function(label) {
    labelsArray.push(label.name);
  });
  labelsArray = labelsArray.join(', ');
  return {
    title: 'Labels',
    value: labelsArray,
    short: labelsArray.length <= 40
  };
};

const githubEvents = {
  ping(request) {
    return {
      content: {
        text: ':thumbsup: ' + request.content.zen
      }
    };
  },

  issues(request) {
    const user = request.content.sender;
    const attachment = {
      author_icon: svg_inline_prefix + gh_iss_svg,
      author_name: '#' + request.content.issue.number + ' - ' + request.content.issue.title,
      author_link: request.content.issue.html_url,
      fields: []
    };

    if (request.content.issue.labels) {
      attachment.fields.push(getLabelsField(request.content.issue.labels));
    }

    if (request.content.issue.assignee) {
      attachment.fields.push({
        title: 'Assignee',
        value: request.content.issue.assignee.login,
        short: true
      });
    }

    const actions = {
      'assigned': ':inbox_tray:',
      'unassigned': ':outbox_tray:',
      'opened': ':triangular_flag_on_post:',
      'closed': ':white_check_mark:',
      'reopened': ':triangular_flag_on_post:',
      'labeled': ':label:',
      'unlabeled': ':label:',
      'edited': ':pencil:'
    };

    const text = actions[request.content.action] + ' issue';

    return {
      content: {
        icon_url: user.avatar_url,
        alias: user.login,
        text: text,
        attachments: [attachment]
      }
    };
  },

  issue_comment(request) {
    const user = request.content.comment.user;
    var attachment = {
      author_icon: svg_inline_prefix + gh_iss_svg,
      author_name: '#' + request.content.issue.number + ' - ' + request.content.issue.title,
      author_link: request.content.comment.html_url,
      fields: []
    };

    if (request.content.issue.labels) {
      attachment.fields.push(getLabelsField(request.content.issue.labels));
    }

    if (request.content.issue.assignee) {
      attachment.fields.push({
        title: 'Assignee',
        value: request.content.issue.assignee.login,
        short: true
      });
    }

    const text = ':speech_balloon: ' + request.content.comment.body;

    return {
      content: {
        icon_url: user.avatar_url,
        alias: user.login,
        text: text,
        attachments: [attachment]
      }
    };
  },

  pull_request(request) {
    const user = request.content.sender;
    const attachment = {
      author_icon: svg_inline_prefix + gh_pr_svg,
      author_name: '#' + request.content.pull_request.number + ' - ' + request.content.pull_request.title,
      author_link: request.content.pull_request.html_url
    };

    let text = 'Pull request';
    switch (request.content.action) {
      case 'assigned':
        text += ' assigned to: ' + request.content.assignee.login;
        break;
      case 'unassigned':
        text += ' unassigned of ' + request.content.assignee.login;
        break;
      case 'opened':
        text += ' opened';
        break;
      case 'closed':
        if (request.content.pull_request.merged) {
          text += ' merged';
        } else {
          text += ' closed';
        }
        break;
      case 'reopened':
        text += ' reopened';
        break;
      case 'labeled':
        text += ' added label: "' + request.content.label.name + '" ';
        break;
      case 'unlabeled':
        text += ' removed label: "' + request.content.label.name + '" ';
        break;
      case 'synchronize':
        text += ' synchronized';
    }

    return {
      content: {
        icon_url: user.avatar_url,
        alias: user.login,
        text: text,
        attachments: [attachment]
      }
    };
  },

  //// GitHub push event
  push(request) {
    var commits = request.content.commits;
    var multi_commit = ""
    var is_short = true;
    var changeset = 'Changeset';
    if ( commits.length > 1 ) {
      var multi_commit = " [Multiple Commits]";
      var is_short = false;
      var changeset = changeset + 's';
      var output = [];
    }
    const user = request.content.sender;
    const attachment = {
    author_icon: svg_inline_prefix + gh_cmit_svg,
      author_name: "Message: " + request.content.head_commit.message + multi_commit,
      author_link: request.content.compare,
      fields: []
    };

    if (request.content.repository.full_name) {
      attachment.fields.push({
        title: 'Repo',
        value: "["+request.content.repository.full_name+"]("+request.content.repository.url+")",
        short: is_short
      });
    }

    for (var i = 0; i < commits.length; i++) {
      var commit = commits[i];
      var shortID = commit.id.substring(0,7);
      if ( commits.length > 1 ) {
        output = '[' + shortID + '](' + commit.url + ') - ' + commit.message
        if (i == 0){
            attachment.fields.push({
                title: changeset,
                value: output,
                short: is_short
            });
        } else{
            attachment.fields.push({
                title: changeset,
                value: output,
                short: is_short
            });
        }
      } else {
        output = "[" + shortID + "](" + commit.url + ")"
        attachment.fields.push({
            title: changeset,
            value: output,
            short: is_short
        });
      }
    }

    const text = ':ballot_box_with_check: Pushed to ' + "["+request.content.ref.split('/').pop()+"]";

    return {
      content: {
        icon_url: user.avatar_url,
        alias: user.login,
        text: text,
        attachments: [attachment]
      }
  };
  },  // End GitHub Push
};

class Script {
  process_incoming_request({ request }) {
    const header = request.headers['x-github-event'];
    if (githubEvents[header]) {
      return githubEvents[header](request);
    }

    return {
      error: {
        success: false,
        message: 'Unsupported method'
      }
    };
  }
}
  • Save the settings

  • The Webhook URL and Token are generated after saving

  • Copy these credentials, they will be used later

GitHub Webhook Setting

After creating the new incoming webhook integration on Rocket.Chat, it is time to link it up with the GitHub repository.

  • Go to the GitHub project repository then navigate to Settings > Webhooks

  • Add webhook and fill in the URL and token you copied from the Rocket.Chat setting

  • Select the list of events you want to be notified on and Add webhook

After successful configuration, you can test the Webhook with any event trigger and see the notification in your specified Rocket.Chat room.

Rocket.Chat GitHub Outgoing Webhook

Sending outgoing webhooks only works on public repositories

  • Create a new Outgoing WebHook

  • Select the channel where you will use the commands and receive the responses

  • Set URLs as https://api.github.com/repos/User-Or-Org-Name/Repo-Name like https://api.github.com/repos/RocketChat/Rocket.Chat

  • Enable Scripts

  • Use this Script to listen for commands pr ls, pr list and help

    /* exported Script */
    /* globals Store */

    class Script {
      prepare_outgoing_request({ request }) {
        let match;

        console.log('lastCmd', Store.get('lastCmd'));

        match = request.data.text.match(/^pr last$/);
        if (match && Store.get('lastCmd')) {
          request.data.text = Store.get('lastCmd');
        }

        match = request.data.text.match(/^pr\s(ls|list)\s*(open|closed|all)?$/);
        if (match) {
          Store.set('lastCmd', request.data.text);
          let u = request.url + '/pulls';
          if (match[2]) {
            u += '?state='+match[2];
          }
          return {
            url: u,
            headers: request.headers,
            method: 'GET'
          };
        }

        match = request.data.text.match(/^help$/);
        if (match) {
          Store.set('lastCmd', request.data.text);
          return {
            message: {
              text: [
                '**GitHub commands**',
                '```',
                  '  pr ls|list [open|closed|all]  List Pull Requests',
                '```'
              ].join('\n')
            }
          };
        }
      }

      process_outgoing_response({ request, response }) {
        var text = [];
        response.content.forEach(function(pr) {
          text.push('> '+pr.state+' [#'+pr.number+']('+pr.html_url+') - '+pr.title);
        });

        return {
          content: {
            text: text.join('\n'),
            parseUrls: false
          }
        };
      }
    }
  • Save your integration

Customizing your integration scripts

The purpose of the integration script is to transform data in one format (the format provided by your incoming service, such as GitHub) into another format (the format expected by Rocket.Chat). Therefore, should you wish to customize either of the scripts presented above, you will need two resources:

Note that data comes into your script from GitHub as the request.content object.

PreviousGoogle CalendarNextGraylog

Last updated 1 year ago

You can customize your webhook integration script to suit your desire as explained .

Create a new webhook integration on Rocket.Chat
Link the GitHub repository through webhook settings
here
GitHub API specifications
Specifications for Rocket.Chat integration message objects
Create new GitHub incoming webhook
GitHub webhook url and token
GitHub webhook setting
GitHub webhook notifications