Skip to content

Commit

Permalink
Telegram Jenkins plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
alekseiko committed Nov 7, 2017
0 parents commit dd866cd
Show file tree
Hide file tree
Showing 32 changed files with 1,534 additions and 0 deletions.
29 changes: 29 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
I*.iws
/out/
.idea_modules/
atlassian-ide-plugin.xml
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
!/.mvn/wrapper/maven-wrapper.jar
*.class
*.ctxt
.mtj.tmp/
*.jar
*.war
*.ear
hs_err_pid*
.gitignore
.idea/*
telegram-notifications.iml
work/
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Change Log

TeleJenkins changes
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# TeleJenkins

![TeleJenkins Japan Style](https://pp.vk.me/c636926/v636926471/193d1/fARBefBcfzs.jpg)

This plugin allows **Jenkins** to send notifications via **telegram** bot.

---

#### Installation
1. Download latest release
2. [Manually install](https://wiki.jenkins-ci.org/display/JENKINS/Plugins#P..) *.hpi* plugin to your jenkins

#### Basic usage
##### Create bot
1. Find BotFather in Telegram (*@BotFather*)
2. Send */newbot* command
3. Enter bot name and bot username

##### Global config
1. Open the Jenkins global config
2. Paste your bot name and username to according textfields
3. In filed Usernames fill names of users who can get Jenkins messages (separated by spaces)
4. Save

##### Subscribe for Jenkins messages
1. In telegram find your bot and send */start* command
2. Send */sub* command

##### Manage your job
1. Add build-step (or post build-step)
2. Fill the message (you can use environment variables and simple Markdown)
3. Save your job
118 changes: 118 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<properties>
<jenkins.version>2.7</jenkins.version>
<java.level>8</java.level>
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
<source.level>1.8</source.level>
<target.level>1.8</target.level>
<junit.version>4.12</junit.version>
<jacoco.version>0.7.4.201502262128</jacoco.version>
<telegrambots.version>v2.3.3.4</telegrambots.version>
<log4j.version>1.2.17</log4j.version>
<job-dsl.version>1.48</job-dsl.version>
<log4j.configuration>log4j.properties</log4j.configuration>
<findbugs.failOnError>false</findbugs.failOnError>
<maven-hpi-plugin.disabledTestInjection>true</maven-hpi-plugin.disabledTestInjection>
</properties>

<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>2.11</version>
<relativePath/>
</parent>

<groupId>jenkins-ci.plugins</groupId>
<artifactId>telegram-notifications</artifactId>
<version>2.0.0-SNAPSHOT</version>
<packaging>hpi</packaging>

<name>Telegram Bot Plugin</name>
<description>This plugin allows you to send messages from Jenkins jobs to Telegram chat.</description>
<url>https://wiki.jenkins-ci.org/display/JENKINS/TelegramBotPlugin</url>

<licenses>
<license>
<name>MIT License</name>
<url>http://opensource.org/licenses/MIT</url>
</license>
</licenses>

<repositories>
<repository>
<id>repo.jenkins-ci.org</id>
<url>http://repo.jenkins-ci.org/public/</url>
</repository>
<repository>
<id>central</id>
<name>Maven Repository Switchboard</name>
<layout>default</layout>
<url>http://repo1.maven.org/maven2</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

<pluginRepositories>
<pluginRepository>
<id>repo.jenkins-ci.org</id>
<url>http://repo.jenkins-ci.org/public/</url>
</pluginRepository>
</pluginRepositories>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>com.github.rubenlagus</groupId>
<artifactId>TelegramBots</artifactId>
<version>${telegrambots.version}</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>job-dsl</artifactId>
<version>${job-dsl.version}</version>
<optional>true</optional>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${source.level}</source>
<target>${target.level}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>

</project>
181 changes: 181 additions & 0 deletions src/main/java/jenkinsci/plugins/telegrambot/TelegramBotBuilder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
package jenkinsci.plugins.telegrambot;

import jenkinsci.plugins.telegrambot.config.GlobalConfiguration;
import jenkinsci.plugins.telegrambot.telegram.TelegramBotRunner;
import jenkinsci.plugins.telegrambot.users.Subscribers;
import jenkinsci.plugins.telegrambot.users.User;
import jenkinsci.plugins.telegrambot.users.UserApprover;
import jenkinsci.plugins.telegrambot.utils.StaplerRequestContainer;
import jenkinsci.plugins.telegrambot.utils.Utils;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
import jenkins.tasks.SimpleBuildStep;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;

import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

public class TelegramBotBuilder extends Builder implements SimpleBuildStep {
private final Logger logger = Logger.getLogger(this.getClass());

/**
* The message that will be expanded and sent to users
*/
private final String message;

@DataBoundConstructor
public TelegramBotBuilder(String message) {
this.message = message;
}

public String getMessage() {
return message;
}

@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}

@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath filePath, @Nonnull Launcher launcher,
@Nonnull TaskListener taskListener) throws InterruptedException, IOException {

TelegramBotDelegate delegate = new TelegramBotDelegate();
delegate.setMessage(getMessage());
delegate.perform(run, filePath, launcher, taskListener);
}

@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> implements Observer {
private Boolean shouldLogToConsole;
private String botToken;
private String botName;
private UserApprover.ApprovalType approvalType;
private Set<User> users;

/**
* Called when Jenkins is starting and it's config is loading
*/
public DescriptorImpl() {
// Load global Jenkins config
load();
updateConfigSimpleParams();

// Set the loaded recipients map
Subscribers.getInstance().setUsers(users != null ? users : new HashSet<>());

// Descriptor object is observer for the Subscribers object
Subscribers.getInstance().addObserver(this);

// Run the bot after Jenkins config have been loaded
TelegramBotRunner.getInstance().runBot();
}

/**
* Called when Jenkins config is saving via web-interface
*/
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {

// Save for the future using
StaplerRequestContainer.req = req;

// Getting simple params from formData
this.shouldLogToConsole = formData.getBoolean("shouldLogToConsole");
this.botToken = formData.getString("botToken");
this.botName = formData.getString("botName");

// Approve users
UserApprover userApprover = new UserApprover(users);
approvalType = userApprover.approve(formData);
users = userApprover.getUsers();

// Store params to the global configuration
updateConfigSimpleParams();

// Store users
Subscribers.getInstance().setUsers(users != null ? new HashSet<>(users) : new HashSet<>());

// Save the configuration
save();
return super.configure(req, formData);
}

/**
* Called when recipients object have been changed
*/
@Override
public void update(Observable observable, Object o) {
try {
users = Subscribers.getInstance().getUsers();
save();
super.configure(StaplerRequestContainer.req, new JSONObject());
} catch (FormException e) {
Logger.getLogger(this.getClass()).error("Error while saving the recipients map");
}
}

/**
* Update global config params using Jenkins config
*/
private void updateConfigSimpleParams() {
GlobalConfiguration config = GlobalConfiguration.getInstance();

config.setLogToConsole(shouldLogToConsole != null ? shouldLogToConsole : true);
config.setBotToken(botToken != null ? botToken : "");
config.setBotName(botName != null ? botName : "");
config.setApprovalType(approvalType != null ? approvalType : UserApprover.ApprovalType.ALL);
}

public FormValidation doCheckMessage(@QueryParameter String value) throws IOException, ServletException {
return Utils.checkNonEmpty(value, "Please set a message");
}

public boolean isApplicable(Class<? extends AbstractProject> clazz) {
return true;
}

@Nonnull
@Override
public String getDisplayName() {
return GlobalConfiguration.PLUGIN_DISPLAY_NAME;
}

public Boolean shouldLogToConsole() {
return shouldLogToConsole;
}

public String getBotToken() {
return botToken;
}

public String getBotName() {
return botName;
}

public Set<User> getUsers() {
return users;
}

public UserApprover.ApprovalType getApprovalType() {
return approvalType;
}
}
}
Loading

0 comments on commit dd866cd

Please sign in to comment.