Skip to content

Commit

Permalink
Merge pull request #53 from centosadmin/develop
Browse files Browse the repository at this point in the history
Make release 1.0.0
  • Loading branch information
constXife authored Jun 30, 2017
2 parents aa2ae44 + b92dd47 commit 4dd6773
Show file tree
Hide file tree
Showing 19 changed files with 166 additions and 381 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# 1.0.0

* Upgrade redmine_telegram_common to version 0.1.0
* Move from telegrammer to telegram-bot-ruby
* Telegram bot can work via getUpdates or WebHooks
* Telegram rake bot will bind default to tmp/pids

# 0.6.2

* Add support sidekiq 5 version
Expand Down
2 changes: 1 addition & 1 deletion Gemfile
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
gem 'telegrammer'
gem 'pidfile', git: 'https://github.com/arturtr/pidfile.git'
gem 'sidekiq-failures', git: 'https://github.com/mhfs/sidekiq-failures.git', branch: 'master'
gem 'sidekiq-cron'
gem 'sidekiq-rate-limiter', git: 'https://github.com/centosadmin/sidekiq-rate-limiter', branch: 'master',
require: 'sidekiq-rate-limiter/server'
gem 'telegram-bot-ruby', '<= 0.7.2'

group :test do
gem 'minitest-reporters'
Expand Down
47 changes: 27 additions & 20 deletions README-RU.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
[![Code Climate](https://codeclimate.com/github/centosadmin/redmine_intouch/badges/gpa.svg)](https://codeclimate.com/github/centosadmin/redmine_intouch)

[English version](https://github.com/centosadmin/redmine_intouch/blob/master/README.md)
[English version](README.md)

# redmine_intouch

Плагин разработан [Centos-admin.ru](https://centos-admin.ru/).

Плагин предназначен для рассылки уведомлений пользователям Redmine через Telegram или E-mail.

Пожалуйста помогите нам сделать этот плагин лучше, сообщая во вкладке [Issues](https://github.com/centosadmin/redmine_intouch/issues) обо всех проблемах, с которыми Вы столкнётесь при его использовании. Мы готовы ответить на Все ваши вопросы, касающиеся этого плагина.
Пожалуйста, помогите нам сделать этот плагин лучше, сообщая во вкладке [Issues](https://github.com/centosadmin/redmine_intouch/issues) обо всех проблемах, с которыми Вы столкнётесь при его использовании. Мы готовы ответить на Все ваши вопросы, касающиеся этого плагина.

# Установка

## Требования

* **Ruby 2.3+**
* **Redmine 3.1+**
* [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common)
* У Вас должен быть аккаунт пользователя Telegram
* У Вас должен быть аккаунт для создания ботов в Telegram
* Настроенный [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common)
* У Вас должен быть бот в Telegram
* Установите плагин [redmine_sidekiq](https://github.com/ogom/redmine_sidekiq). [Redis](https://redis.io) 2.8 или выше требуется.
* Настройте Sidekiq на обработку очереди `default` и `telegram`. [Пример конфига](https://github.com/centosadmin/redmine_intouch/blob/master/extras/sidekiq.yml) - разместите его в папке `redmine/config`
* Плагин устанавливается стандартно:
Expand All @@ -32,9 +29,14 @@ bundle exec rake redmine:plugins:migrate RAILS_ENV=production

Примеры конфигурационного файла и скрипта для `init.d` находятся в папке `extras`

### Обновление с 0.3 на 1.0.0+

Начиная с версии 1.0.0 этот плагин использует [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common)
версии 0.1.0, в которой ушли от зависимости от Telegram CLI. Обратите внимание на новые зависимости.

### Обновление с 0.2 на 0.3+

Начиная с версии 0.3 это плагин использует [redmine_telegram_common](https://github
Начиная с версии 0.3 этот плагин использует [redmine_telegram_common](https://github
.com/centosadmin/redmine_telegram_common).

Перед обновлением установите [этот](https://github.com/centosadmin/redmine_telegram_common) плагин.
Expand All @@ -61,7 +63,21 @@ bundle exec rake redmine:plugins:migrate RAILS_ENV=production

## Telegram

На этой вкладке необходимо указать токен бота Telegram.
На этой вкладке необходимо указать токен бота Telegram и сохранить настройки.

### Режимы бота

Бот может работать в двух [режимах](https://core.telegram.org/bots/api#getting-updates) — getUpdates или WebHooks.

#### getUpdates

Чтобы у вас заработал бот через getUpdates, вам необходимо запустить процесс бота `bundle exec rake -D intouch:telegram:bot`.
Эта команда отключит WebHook у бота.

#### WebHooks

Чтобы у вас заработал бот через WebHooks, вам необходимо зайти в настройки плагина и нажать на кнопку "Инициализировать бота"
(токен бота уже должен быть записан, а также обратите внимание, что в этом случае необходим https)

### Создание бота Telegram

Expand All @@ -74,7 +90,7 @@ bundle exec rake redmine:plugins:migrate RAILS_ENV=production
В случае успеха BotFather возвращает токен бота и ссылку для быстрого добавления бота в контакты,
иначе придется поломать голову над именем.

Полученный токен нужно ввести на странце настройки плагина.
Полученный токен нужно ввести и сохранить на странице настройки плагина.

### Запуск бота

Expand All @@ -84,16 +100,7 @@ bundle exec rake redmine:plugins:migrate RAILS_ENV=production
* рабочее время - в это время отправляются уведомления по не срочным задачам
* указать какие приоритеты считать срочными
* указать какие статусы считать *в работе* и *обратной связью*

После этого необходимо запустить бота командой:

```shell
bundle exec rake intouch:telegram:bot PID_DIR='/pid/dir' RAILS_ENV=production
```

* пример скрипта для `init.d` в папке `extras`

Этот процесс добавляет пользователей Telegram в Redmine, а также создает в Redmine группы Telegram, в которые добавили бота.
* сохранить настройки

### Добавление аккаунта Telegram к пользователю

Expand Down
39 changes: 24 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[![Code Climate](https://codeclimate.com/github/centosadmin/redmine_intouch/badges/gpa.svg)](https://codeclimate.com/github/centosadmin/redmine_intouch)

[Русская версия](https://github.com/centosadmin/redmine_intouch/blob/master/README-RU.md)
[Русская версия](README-RU.md)

# redmine_intouch

Expand All @@ -14,8 +14,7 @@ Please help us make this plugin better telling us of any [issues](https://github

* **Ruby 2.3+**
* **Redmine 3.1+**
* [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common)
* You should have Telegram user account
* Configured [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common)
* You should have Telegram bot account
* Install the [redmine_sidekiq](https://github.com/ogom/redmine_sidekiq) plugin. [Redis](https://redis.io) 2.8 or greater is required.
* You need to configure Sidekiq queues `default` and `telegram`. [Config example](https://github.com/centosadmin/redmine_intouch/blob/master/extras/sidekiq.yml) - place it to `redmine/config` directory
Expand All @@ -30,7 +29,12 @@ bundle exec rake redmine:plugins:migrate RAILS_ENV=production

The `extras` folder has the examples of the plugin config files and the `init.d` startup script

### Upgrade form 0.2 to 0.3+
### Upgrade from 0.3 to 1.0.0+

Since version 1.0.0 this plugin uses [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common)
0.1.0 version, where removed Telegram CLI dependency. Please, take a look on new requirements.

### Upgrade from 0.2 to 0.3+

Since version 0.2 this plugin uses [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common)
plugin.
Expand Down Expand Up @@ -58,7 +62,7 @@ The plugin contains the fuctionality that allows you to send scheduled notificat

## Telegram

Specify the Telegram Bot token here.
Specify the Telegram Bot token here, save settings and then initialize bot.

### Creating a Telegram bot

Expand All @@ -72,6 +76,20 @@ You'll have to invent a new name if the registration fails.

You should enter the token you've just created on the Plugin Settings page.

### Bot modes

Bot can work in two [modes](https://core.telegram.org/bots/api#getting-updates) — getUpdates or WebHooks.

#### getUpdates

To work via getUpdates, you should run bot process `bundle exec rake intouch:telegram:bot`.
This will drop bot WebHook setting.

#### WebHooks

To work via WebHooks, you should go to plugin settings and press button "Initialize bot"
(bot token should be saved earlier, and notice redmine should work on https)

### Bot launch

Specify the following things before launching the bot:
Expand All @@ -80,16 +98,7 @@ Specify the following things before launching the bot:
* Working Time - when and what notifications will be sent
* Specify what priorities should be considered as urgent ones
* Specify what statuses should be considered _in work_ and _feedback_

Run the bot by typing:

```shell
bundle exec rake intouch:telegram:bot PID_DIR='/pid/dir' RAILS_ENV=production
```

The `extras` folder has the examples of the plugin config files and the `init.d` startup script.

This will add the Telegram users to Redmine and create the Telegram groups in which it was added in Redmine.
* Save settings

### Adding a Telegram account to the user

Expand Down
15 changes: 14 additions & 1 deletion app/controllers/intouch_controller.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class IntouchController < ApplicationController
unloadable

before_filter :find_project
before_filter :find_project, only: [:save_settings]

def save_settings
if request.put?
Expand All @@ -15,6 +15,19 @@ def save_settings
redirect_to controller: 'projects', action: 'settings', tab: params[:tab] || 'intouch_settings', id: @project
end

def bot_init
bot = Telegram::Bot::Client.new(Intouch.bot_token)
bot.api.setWebhook(url: Intouch.web_hook_url)

redirect_to plugin_settings_path('redmine_intouch'), notice: t('intouch.bot.authorize.success')
end

def bot_deinit
bot = Telegram::Bot::Client.new(Intouch.bot_token)
bot.api.setWebhook(url: '')
redirect_to plugin_settings_path('redmine_intouch'), notice: t('intouch.bot.deauthorize.success')
end

private

def find_project
Expand Down
8 changes: 8 additions & 0 deletions app/controllers/intouch_handler_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class IntouchHandlerController < ActionController::Metal
def handle
IntouchHandlerWorker.perform_async(params)

self.status = 200
self.response_body = ''
end
end
20 changes: 20 additions & 0 deletions app/views/settings/_telegram.html.erb
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
<p>
<label for="settings_telegram_bot_token">Bot Token</label>
<%= text_field_tag 'settings[telegram_bot_token]', @settings['telegram_bot_token'], size: 50 %>

<div style="display: flex; align-items: center;">
<div style="flex: 1; padding: 0.5em;">
<h3>WebHooks</h3>

<% if Setting['protocol'] == 'https' %>
<%= link_to intouch_bot_init_path, method: 'post' do %><button type="button"><%= t 'intouch.settings.bot_init' %></button><% end %>

<%= link_to intouch_bot_deinit_path, method: 'delete' do %><button type="button"><%= t 'intouch.settings.bot_deinit' %></button><% end %>
<% else %>
<strong><%= t 'intouch.settings.web_hooks_warning' %></strong>
<% end %>
</div>

<div style="flex: 1; padding: 0.5em;">
<h3>getUpdates</h3>

<pre><%= t 'intouch.settings.get_updates_hint' %></pre>
</div>
</div>
</p>

<h3><%= t 'intouch.settings.telegram.groups' %></h3>
Expand Down
19 changes: 19 additions & 0 deletions app/workers/intouch_handler_worker.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class IntouchHandlerWorker
include Sidekiq::Worker
sidekiq_options queue: :telegram

def perform(params)
message = Telegram::Bot::Types::Update.new(params).message

if message.present?
Intouch.handle_message(message)
else
logger.fatal "Can't find message: #{params.to_json}"
end
end

def logger
@logger ||= Logger.new(Rails.root.join('log/intouch/',
'telegram-handler.log'))
end
end
20 changes: 6 additions & 14 deletions app/workers/telegram_message_sender.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@ class TelegramMessageSender

def perform(telegram_account_id, message)
token = Intouch.bot_token
bot = Telegrammer::Bot.new(token)
bot = Telegram::Bot::Client.new(token)

begin

bot.send_message(chat_id: telegram_account_id, text: message, disable_web_page_preview: true, parse_mode: 'Markdown')
bot.api.send_message(chat_id: telegram_account_id,
text: message,
disable_web_page_preview: true,
parse_mode: 'Markdown')
TELEGRAM_MESSAGE_SENDER_LOG.info "telegram_account_id: #{telegram_account_id}\tmessage: #{message}"

rescue Telegrammer::Errors::BadRequestError => e
rescue => e

TELEGRAM_MESSAGE_SENDER_ERRORS_LOG.info "MESSAGE: #{message}"

Expand All @@ -44,16 +46,6 @@ def perform(telegram_account_id, message)

end

rescue Telegrammer::Errors::ServiceUnavailableError

TELEGRAM_MESSAGE_SENDER_ERRORS_LOG.error "ServiceUnavailableError. retry to send after 5 seconds\ntelegram_account_id: #{telegram_account_id}\tmessage: #{message}"
TelegramMessageSender.perform_in(5.seconds, telegram_account_id, message)

rescue Telegrammer::Errors::TimeoutError

TELEGRAM_MESSAGE_SENDER_ERRORS_LOG.error "TimeoutError. retry to send after 5 seconds\ntelegram_account_id: #{telegram_account_id}\tmessage: #{message}"
TelegramMessageSender.perform_in(5.seconds, telegram_account_id, message)

end
end
end
8 changes: 8 additions & 0 deletions config/locales/en.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
en:
intouch:
bot:
authorize:
success: Bot is initialized
deauthorize:
success: Bot is deinitialized
private:
help:
start: "Start work with bot"
Expand Down Expand Up @@ -116,6 +120,10 @@ en:
working: In work
settings:
required: "required for this plugin"
bot_init: Initialize bot
bot_deinit: Deinitialize bot
get_updates_hint: bundle exec rake -D intouch:telegram:bot
web_hooks_warning: Need https to setup WebHooks
common:
alarm:
description_1: Notification about the issues with the selected priorities will be sent twenty-four seven.
Expand Down
8 changes: 8 additions & 0 deletions config/locales/ru.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
ru:
intouch:
bot:
authorize:
success: Бот инициализирован
deauthorize:
success: Бот деинициализирован
private:
help:
start: "Начало работы с ботом"
Expand Down Expand Up @@ -115,7 +119,11 @@ ru:
unassigned: "Неназначенные/Назначенные на группу"
working: "В работе"
settings:
bot_init: Инициализировать бота
bot_deinit: Деинициализировать бота
required: "требуется для работы этого плагина"
get_updates_hint: bundle exec rake -D intouch:telegram:bot
web_hooks_warning: Нужен https протокол, чтобы настроить WebHooks
common:
alarm:
description_1: "Уведомления о задачах, с выбранными приоритетами, будут отправляться круглосуточно и без выходных."
Expand Down
9 changes: 8 additions & 1 deletion config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
put 'intouch/save_settings' => 'intouch#save_settings'
resources :settings_templates
get 'settings_templates/:copy_from/copy', to: 'settings_templates#new', as: 'copy_settings_template'

scope :intouch do
put 'save_settings' => 'intouch#save_settings'

post 'web_hook', to: IntouchHandlerController.action(:handle), as: :intouch_web_hook
post 'bot_init' => 'intouch#bot_init', as: :intouch_bot_init
delete 'bot_deinit' => 'intouch#bot_deinit', as: :intouch_bot_deinit
end

resources :telegram_groups, only: [:destroy]

resources :sidekiq_cron_jobs do
Expand Down
1 change: 0 additions & 1 deletion extras/README.md

This file was deleted.

Loading

0 comments on commit 4dd6773

Please sign in to comment.