Today I show you how you can send notifications to Mattermost with PHP and Github Actions. There are some implementations on Github Marketplace but nothing was made with PHP, there was Javascript, Go, or Python. But PHP can be used to create command-line utilities and itβs very easy. Donβt trust me? Come Iβll show you.
First of all, create a new folder for your project, mine is action-mattermost-notify. You can do this with the command as follows.
1
mkdir action-mattermost-notify
Now initializae new repository
1
2
# cd action-mattermost-notifycomposer init
The composer will ask you for some information such as project name, author name, and email. When you are done you will have a folder structure like this one:
Now You need to add some dependencies. (Here are two of them). The first one is the HTTP client and the second one is Console.
1
2
3
# cd action-mattermost-notifycomposer require symfony/http-client
composer require symfony/console
After this step, 1st part is done. Go to next step.
Creating Console application
With the Console component is creating a new console application easy. When you finish this part your folder structure will look like follows
1
2
3
4
5
6
7
action-mattermost-notify
βββ app.php # Added this oneβββ composer.json
βββ composer.lock
βββ src
β βββ SendCommand.php # Added this oneβββ vendor
First create app.php, which is the main file that launches your console application, and put there following content.
1
2
3
4
5
6
7
8
9
10
11
12
# app.php
require__DIR__.'/vendor/autoload.php';useSymfony\Component\Console\Application;# Load version information from the composer file
# You will need to add a version tag to your composer.json
$version=json_decode(file_get_contents(__DIR__.'/composer.json'),true);$app=newApplication('Action Mattermost Notify',$version['version']);$app->run();
Good job! Now try to run it
1
php app.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Action Mattermost Notify 1.0.0
Usage:
command[options][arguments]Options:
-h, --help Display helpfor the given command. When no command is given display helpfor the list command -q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
-v|vv|vvv, --verbose Increase the verbosity of messages: 1for normal output, 2for more verbose output and 3for debug
Available commands:
completion Dump the shell completion script
help Display helpfor a command list List commands
Next, you need to create a new command that will communicate with Mattermost. Go into the src folder and create SendCommand.php
<?phpdeclare(strict_types=1);# Change namespace to your project's namespace
namespaceMaymeow\ActionMattermostNotify;useSymfony\Component\Console\Command\Command;useSymfony\Component\Console\Input\InputArgument;useSymfony\Component\Console\Input\InputInterface;useSymfony\Component\Console\Input\InputOption;useSymfony\Component\Console\Output\OutputInterface;useSymfony\Component\HttpClient\HttpClient;classSendCommandextendsCommand{protectedstatic$defaultName='send';/**
* Configure method
*
* @return void
*/publicfunctionconfigure():void{$this->setDescription('Send a message to Mattermost')->setHelp('This command allows you to send a message to Mattermost');$this->addArgument('message',InputArgument::REQUIRED,'The message to send')->addOption('channel',null,InputOption::VALUE_OPTIONAL,'The channel to send the message to')->addOption('username',null,InputOption::VALUE_OPTIONAL,'The username to send the message as')->addOption('icon',null,InputOption::VALUE_OPTIONAL,'The icon to send the message with')->addOption('url',null,InputOption::VALUE_OPTIONAL,'The URL to send the message with');}/**
* Execute method
*
* @param \Symfony\Component\Console\Input\InputInterface $input Input interface
* @param \Symfony\Component\Console\Output\OutputInterface $output Output interface
* @return int
*/publicfunctionexecute(InputInterface$input,OutputInterface$output):int{$message=$input->getArgument('message');$channel=$input->getOption('channel');$username=$input->getOption('username');$icon=$input->getOption('icon');$url=$input->getOption('url');$client=HttpClient::create();$response=$client->request('POST',$url,['body'=>json_encode(['channel'=>$channel,'text'=>$message,'username'=>$username,'icon_url'=>$icon,]),'headers'=>['Content-Type'=>'application/json',],]);$output->writeln($response->getContent());returnCommand::SUCCESS;}}
Let me show you what are parts of this file doing
1
publicfunctionconfigure():void
The function above, as the name says, is used to configure your command. It tells your application what argument or options this command needs, its name, and description or you can modify the handler (how you call it from command line).
Ok, Now register your Command to your application with $app->add(new SendCommand());. Add this to your app.php file. After this step, your file will look like this one
Try to run your app again php app.php. In your response another action has been added:
1
2
3
4
5
6
Action Mattermost Notify 1.0.0
# // ...Available commands:
completion Dump the shell completion script
help Display helpfor a command list List commands # <--- This one as beed added
To see information about any command append --help behind that command. For example send command
1
php app.php send --help
Required are the message and url of your webhook.
You can obtain the webhook URL on your mattermost instance in integrations, then click on Incoming webhook then add new and provide requested information.
Sending message
When you have all you need (created webhook), you can send a meesage to the server as follows
1
php app.php send "Hello World from PHP commandline!" --url "https://your-mattermost.url/webhook-id"
Cool isnβt it? But, I like it if I can call the application without php word as follows
1
`./action-mattermost-notify send "Hello World from PHP commandline!" --url "https://your-mattermost.url/webhook-id"`
Ok, Letβs do this.
Packing your application to single file
In this step, you will learn how to pack your PHP application into phar. You have 2 options, read the PHP manual and do it your way, or IMO a more elegant way to use phar-composer.
To check the current version go to the releases page.
Before you can pack your app you need to make small changes in your composer file. Add "bin": ["app.php"], somewhere in composer file. This tells to phar-composer which file needs to call when execute.
Ok, the console application is finished and now you can create a GitHub action
Creating Action
The folder structure after this part is finished will look like follows
1
2
3
4
5
6
7
8
9
10
action-mattermost-notify
βββ action.yml # Added this oneβββ app.php
βββ composer.json
βββ composer.lock
βββ Dockerfile # Added this oneβββ entrypoint.sh # Added this oneβββ src
β βββ SendCommand.php
βββ vendor
First of all, you need to automate the steps above like building phar and making it executable. You donβt want to have bin files in your git repository. To do this, we use Docker in this tutorial. Create Dockerfile and put there following content:
At last, you need to create an action configuration file that tells Github all the required information about the action that you creating. It is called action.yml and has to be in the root directory. Create it with the following content:
# action.ymlname:'Action Name'#change this to your action nameauthor:'Action Author'# Change this to yourdescription:'Action Description'# change thisbranding:icon:'command'color:'purple'inputs:# following are all inputs that can be used in this actionmessage:description:'Enter the message to send to Mattermost'required:trueurl:description:'The URL to send the message to'required:truechannel:description:'Enter the channel to send the message to'required:falseicon:description:'Enter the icon to use for the message'required:falseusername:description:'Enter the username to use for the message'required:falseruns:# How this action start? using:'docker'image:'Dockerfile'args:- ${{ inputs.message }}- ${{ inputs.url }}- ${{ inputs.channel }}- ${{ inputs.icon }}- ${{ inputs.username }}
Good job! Congratulation, You are reading this to the finish. You now have your own Github action and you learned how to
create a PHP console application
how to pack it in a single Phar file
how to create Github Action with PHP
How to run it
At the very end, ill show you how you can use it. There are more options on how to call it.
Register it in the marketplace (via new release)
Call it with branch name or commit hash
If you have published it you can call it as follows
1
2
3
4
5
- name:Action Mattermost Notifyuses:MayMeow/action-mattermost-notify@v1# Change this to your actionwith:url:${{ secrets.MATTERMOST_WEBHOOK }}message:"Hello world from ${{ github.repository }}"
Your action has name your-github-username/your-action-repository@version or your-github-username/your-action-repository@branch-name or your-github-username/your-action-repository@commit-hash. The last two options donβt require to have action registered in the marketplace.