Skip to content

Commit

Permalink
Merge remote-tracking branch 'remotes/origin/dev-teplo'
Browse files Browse the repository at this point in the history
  • Loading branch information
DenisCherniatev committed Aug 11, 2016
2 parents 5368339 + 08de4e7 commit dc2e5a2
Show file tree
Hide file tree
Showing 14 changed files with 805 additions and 60 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
node_modules
/.buildpath
/.project
/.settings/org.eclipse.php.core.prefs
/.settings/org.eclipse.wst.common.project.facet.core.xml
/TeploBot
/.settings/org.eclipse.core.resources.prefs
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ Plugin features:
* support up to 5 custom commands with lists or recent posts or custom post types
* in private chats: messages without command processed as search requests
* log of messages and responses
* posting from Telegram
* subscription to notifications about new posts
* for developers: commands with custom logic could be defined
* for developers: API for sending notifications to subscribers

**Limitation**. In mean time the plugin doesn't support inline mode. Follow the development progress or send as pull-requests for improvements.

Expand All @@ -22,6 +25,8 @@ The plugin developed and supported by [Teplitsa. Technologies for Social Good](h

Plugins requires PHP 5.3+ and WordPress 4.5+.

Website should work with https protocol for connecting with Telegram, self-signed certificate allowed.

1. Upload the plugin folder into `wp-content/plugins` using WordPress Dashboard (_Plugins -- Add new_) or by cloning GitHub-repo.

2. Activate the plugin through the _Plugins_ menu in WordPress.
Expand All @@ -35,9 +40,14 @@ To set the plugin into work you need to create a Telegram bot in the dialogue wi
* `/start` Greeting on the dialogue start
* `/help` Provide the help text for user
* `/s` Provide search results as list of posts' link
* `/post` Submit article to WP site
* `/sub` Subscribe to notifications about new posts (or any other content types)
* `/unsub` Unsubscribe from notifications about new posts (or any other content types)

Admins could add up to 5 custom commands that send list or posts or CPTs to chats. Developers could alter the commands logic through `gwptb_supported_commnds_list` filter (details published at [GitHub wiki](https://github.com/Teplitsa/TeploBot)).

Set "Active subscriptions" option to activate subscriptions to notifications.

Commands should be defined in chat with [@BotFather](https://telegram.me/botfather) to be accepted by plugin: use `/setcommands` command and follow the instructions.

### Screenshots ###
Expand Down Expand Up @@ -80,7 +90,10 @@ We will be very grateful if you help us to make TeploBot better.
* поддержка до 5 собственных команд, отправляющих список последних записей или пользовательских типов записей
* в индивидуальных чатах сообщения, не содержащие команд, трактуются как поисковый запрос
* лог сообщений
* написание постов из Telegram
* подписка на уведомления о новых публикациях
* для разработчиков - возможность добавлять собственные команды или менять логику существующих
* для разработчиков - API для рассылки уведомлений подписчикам

**Ограничение**. В настоящее время инлайновый режим не поддерживается плагином. Следите за обновлениями и присылайте пулл-реквесты.

Expand All @@ -90,6 +103,8 @@ We will be very grateful if you help us to make TeploBot better.

Для корректной работы необходим PHP версии 5.3 и выше и WordPress версии 4.5 и выше.

Сайт должен поддерживать протокол https для взаимодействия с Telegram, допускается использование самоподписанного сертификата.

1. Загрузите папку плагина в директорию `wp-content/plugins`, используя административный интерфейс добавления плагинов (_Плагины -- Добавить новый_)
или клонировав GitHub-репозиторий.

Expand All @@ -106,9 +121,14 @@ We will be very grateful if you help us to make TeploBot better.
* `/start` Начало диалога
* `/help` Подсказка и описание команд
* `/s` Результаты поиска
* `/post` Отправка публикации на сайт
* `/sub` Подписка на уведомления о новых публикациях
* `/unsub` Отписка от уведомлений о новых публикациях

Администраторы сайта могут добавить до 5 собственных команд, отправляющих список последних публикаций в чат. Разработчики могут определять собственные команды или менять логику существующих, используя фильтр `gwptb_supported_commnds_list` (подробнее в wiki на [GitHub](https://github.com/Teplitsa/TeploBot)).

Заполните поле "Активные подписки" в настройках, чтобы активировать возможность подписки на уведомления.

Чтобы бот распознавал команды, они должны быть установлены в диалоге с [@BotFather](https://telegram.me/botfather): отправьте ему команду `/setcommands` и следуйте инструкциям.

### Помощь проекту ###
Expand Down
8 changes: 6 additions & 2 deletions gwptb.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
/*
Plugin Name: TeploBot - Telegram Bot for WP
Description: Simple Telegram Bot for your site with green effect
Version: 1.1
Version: 1.2
Author: Teplitsa
Author URI: https://te-st.ru/
Text Domain: gwptb
Domain Path: /lang
Contributors:
Gleb Suvorov aka gsuvorov ([email protected]) - Idea, UX
Anna Ladoshkina aka foralien ([email protected]) - Development
Denis Cherniatev aka denischerniatev ([email protected]) - Development
License URI: http://www.gnu.org/licenses/gpl-2.0.txt
Expand Down Expand Up @@ -37,7 +38,7 @@

// Plugin version:
if( !defined('GWPTB_VERSION') )
define('GWPTB_VERSION', '1.1');
define('GWPTB_VERSION', '1.2');

// Plugin DIR, with trailing slash:
if( !defined('GWPTB_PLUGIN_DIR') )
Expand Down Expand Up @@ -70,6 +71,9 @@
require_once(plugin_dir_path(__FILE__).'inc/class-cssjs.php');
require_once(plugin_dir_path(__FILE__).'inc/class-stat.php');
require_once(plugin_dir_path(__FILE__).'inc/class-filters.php');
require_once(plugin_dir_path(__FILE__).'inc/api.php');
require_once(plugin_dir_path(__FILE__).'inc/subscription.php');
require_once(plugin_dir_path(__FILE__).'inc/posting.php');
$tplb = Gwptb_Core::get_instance();

if(is_admin()){
Expand Down
63 changes: 57 additions & 6 deletions inc/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,22 @@ public function setup_metabox_screen(){
<input type="hidden" name="action" value="del_webhook">

<?php } else { ?>
<input type="hidden" name="action" value="set_webhook">
<button type="submit" class="button button-primary"><?php _e('Set connection', 'gwptb');?></button>
<!-- is it possible to setup connection? -->
<?php
$core = Gwptb_Core::get_instance();
$test_webhook = $core->test_webhook_url();
if(!is_wp_error($test_webhook)) {
?>
<p><input type="hidden" name="action" value="set_webhook">
<button type="submit" class="button button-primary"><?php _e('Set connection', 'gwptb');?></button>
</p>
<?php } else { ?>
<div class="gwptb-connection-error-message">
<p><?php _e('Bot cann\'t be connected to Telegram due to following error on service URL:', 'gwptb');?></p>
<p><code><?php echo $test_webhook->get_error_message();?></code></p>
<p><?php _e('Please check the bot\'s settings and be sure that you have correct HTTPS support on your site.', 'gwptb');?></p>
</div>
<?php } ?>
<?php }?>
</div>

Expand Down Expand Up @@ -364,7 +378,9 @@ function settings_init( ) {
register_setting( 'gwptb_settings', 'gwptb_cert_key', array('GWPTB_Filters', 'sanitize_string'));
register_setting( 'gwptb_settings', 'gwptb_start_text', array('GWPTB_Filters', 'sanitize_html'));
register_setting( 'gwptb_settings', 'gwptb_help_text', array('GWPTB_Filters', 'sanitize_html'));
register_setting( 'gwptb_settings', 'gwptb_subscriptions', array('GWPTB_Filters', 'sanitize_string'));
register_setting( 'gwptb_settings', 'gwptb_custom_commands', array($this, 'custom_commands_prepare_filter'));
register_setting( 'gwptb_settings', 'gwptb_post_target_posttype', array('GWPTB_Filters', 'sanitize_string'));

//sections
add_settings_section(
Expand Down Expand Up @@ -401,19 +417,35 @@ function settings_init( ) {

add_settings_field(
'gwptb_cert_key',
__( 'Public key', 'gwptb' ),
__( 'Public key / certificate', 'gwptb' ),
array($this, 'cert_key_render'),
'gwptb_settings',
'gwptb_bot_section'
);

add_settings_field(
'gwptb_subscriptions',
__( 'Active subscriptions', 'gwptb' ),
array($this, 'subscriptions_render'),
'gwptb_settings',
'gwptb_bot_section'
);

add_settings_field(
'gwptb_custom_commands',
__( 'Custom commands', 'gwptb' ),
array($this, 'custom_commands_render'),
'gwptb_settings',
'gwptb_bot_section'
);
);

add_settings_field(
'gwptb_post_target_posttype',
__( 'Target post type for user messages', 'gwptb' ),
array($this, 'post_target_posttype_render'),
'gwptb_settings',
'gwptb_bot_section'
);
}


Expand Down Expand Up @@ -460,7 +492,7 @@ public function start_text_render(){
}

public function help_text_render(){
$default = sprintf(__('I can help you to find something useful at %%home%%. Send me %s to perform a search.', 'gwptb'), "<i>".__('your term', 'gwptb')."</i>");
$default = sprintf(__('I can help you to find something useful at %%home%%. Send me %s to perform a search, /post to make a post, /sub to subscrube to site updates or /unsub to stop updates subscription.', 'gwptb'), "<i>".__('your term', 'gwptb')."</i>");
$value = apply_filters('gwptb_output_html', get_option('gwptb_help_text', $default));
?>
<textarea name='gwptb_help_text' class="large-text" rows="3"><?php echo $value; ?></textarea>
Expand All @@ -475,10 +507,20 @@ public function cert_key_render() {
$help_link = "<a href='https://core.telegram.org/bots/self-signed' target='_blank'>".__('Telegram instructions', 'gwptb')."</a>";
?>
<textarea name='gwptb_cert_key' class="large-text" rows="3"><?php echo $value; ?></textarea>
<p class="description"><?php printf(__('For self-signed certificates: copy the content of public key. %s', 'gwptb'), $help_link);?></p>
<p class="description"><?php printf(__('For self-signed certificates: copy the content of public key / certificate. %s', 'gwptb'), $help_link);?></p>
<?php
}

public function subscriptions_render() {

$value = get_option('gwptb_subscriptions');
?>
<textarea name='gwptb_subscriptions' class="large-text" rows="3"><?php echo $value; ?></textarea>
<p class="description"><?php printf(__('Post types based subscriptions are available by default. They are: <b>%s</b>. Just put it into the field, separated by ",". Also you can add your own subscriptions and send messages using <b>gwptb_notify_subscribers</b>($subscription_name, $message) function.', 'gwptb'), implode(',', gwptb_get_available_post_types()));?></p>
<p class="description"><?php _e('To make subscriptions work /sub and /unsub commands should be added in dialog with @BotFather', 'gwptb');?></p>
<?php
}

public function custom_commands_render(){

$value = get_option('gwptb_custom_commands');
Expand Down Expand Up @@ -512,6 +554,15 @@ public function custom_commands_render(){
<?php
}

public function post_target_posttype_render() {

$value = get_option('gwptb_post_target_posttype');
?>
<input type="text" name='gwptb_post_target_posttype' class="large-text" value="<?php echo esc_attr($value);?>">
<p class="description"><?php _e('Specify a target post_type to receive messages from Telegram users with /post command. Command should be added in dialogue with @BotFather. Type \'none\' to disable feature completely. ', 'gwptb');?></p>
<?php
}

public function custom_commands_prepare_filter($option) {

if(!is_array($option))
Expand Down
32 changes: 32 additions & 0 deletions inc/api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

# subscription
function gwptb_get_post_teaser($post) {
# get teaser from post content and excerpt
$short = $post->post_excerpt;
if(!$short) {
if( preg_match( '/<!--more(.*?)?-->/', $post->post_content, $matches ) ) {
$parts = explode( $matches[0], $post->post_content, 2 );
$short = $parts[0];
}
else {
$short = wp_trim_words($post->post_content);
}
}
$short = apply_filters( 'get_the_excerpt', $short );
$short = preg_replace("/&#?[a-z0-9]+;/i", "", $short);

return $short;
}

function gwptb_notify_subscribers($subscription_name, $message) {
global $wpdb;

$table_name = Gwptb_Core::get_chat_subscriptions_tablename();
$subscribed_chat_list = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$table_name} WHERE name = %s ", $subscription_name));

$telebot = Gwptb_Self::get_instance();
foreach($subscribed_chat_list as $chat) {
$telebot->send_notification(array('chat_id' => $chat->chat_id, 'text' => $message, 'parse_mode' => 'HTML'));
}
}
1 change: 1 addition & 0 deletions inc/class-filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ private function __construct() {
//add input filter
add_filter('gwptb_input_latin', array('GWPTB_Filters', 'sanitize_email'));
add_filter('gwptb_input_text', array('GWPTB_Filters', 'sanitize_string'));
add_filter('gwptb_post_draft_content', array('GWPTB_Filters', 'sanitize_text'));

//search term
add_filter('gwptb_search_term', array('GWPTB_Filters','sanitize_search_term'));
Expand Down
20 changes: 17 additions & 3 deletions inc/class-gwptb.php
Original file line number Diff line number Diff line change
Expand Up @@ -650,11 +650,19 @@ public static function get_supported_commands(){

if (empty(self :: $commands)){
$default_commands = array(
'help' => 'gwptb_help_command_response',
'start' => 'gwptb_start_command_response',
's' => 'gwptb_search_command_response',
'help' => 'gwptb_help_command_response',
'start' => 'gwptb_start_command_response',
's' => 'gwptb_search_command_response',
'sub' => 'gwptb_subscribe_command_response',
'unsub' => 'gwptb_unsubscribe_command_response'
);

//post command if avaliable
$target_pt = get_option('gwptb_post_target_posttype');
if($target_pt && $target_pt != 'none' && post_type_exists($target_pt)){
$default_commands['post'] = 'gwptb_post_command_response';
}

$custom_commands = array();
$custom_commands_opt = get_option('gwptb_custom_commands');

Expand Down Expand Up @@ -779,4 +787,10 @@ public function get_self_username() {
return $self['username'];
}

/** == Notification == **/
public function send_notification($reply_data){

$this->request_api_json('sendMessage', $reply_data);
}

} //class
Loading

0 comments on commit dc2e5a2

Please sign in to comment.