Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENH] Add telegram notification webhook when new messages are detected #1056

Draft
wants to merge 10 commits into
base: master
Choose a base branch
from
74 changes: 74 additions & 0 deletions lib/telegram_webhook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

/**
* Webhook
* @package framework
* @subpackage webhook
*/

class Hm_Telegram_Webhook {

const PREFIX_URI = 'https://api.telegram.org/';

/**
* send telegram notiofication using curl
* @param int $msg_count
* @param string $email_to
* @param string $webhook_token
*/
public static function send($msg_count, $email_to, $webhook_token) {
self::delete_webhook($webhook_token);
// Get the chat ID
$chatId = self::get_chat_id($webhook_token);
if (!empty($chatId)) {
$text = "You have received: $msg_count unread email.s\nTo: $email_to";
$curl_handle = Hm_Functions::c_init();
Hm_Functions::c_setopt($curl_handle, CURLOPT_URL, static::PREFIX_URI.'bot'.$webhook_token.'/sendMessage');
Hm_Functions::c_setopt($curl_handle, CURLOPT_POST, true);
Hm_Functions::c_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
Hm_Functions::c_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query(['chat_id' => $chatId, 'text' => $text]));
Hm_Functions::c_setopt($curl_handle, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]);
$curl_result = Hm_Functions::c_exec($curl_handle);
if (trim($curl_result)) {
$response_data = json_decode($curl_result, true);
if (!$response_data['ok']) {

}
}
}
}

/**
* get the chat ID using webhook_token
* @param string $webhook_token
*/
private static function get_chat_id($webhook_token) {
$curl_handle = Hm_Functions::c_init();
Hm_Functions::c_setopt($curl_handle, CURLOPT_URL, static::PREFIX_URI.'bot'.$webhook_token.'/getUpdates');
Hm_Functions::c_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
$curl_result = Hm_Functions::c_exec($curl_handle);
if (trim($curl_result)) {
$response_data = json_decode($curl_result, true);
if(!empty($chatId = $response_data['result'][0]['message']['chat']['id'])){
return $chatId;
} else {
Hm_Msgs::add('ERRNo messages found. Please send a message to your bot first.<br>');
return '';
}
}
}

/**
* This function is usefull when trying to resend, we need to delete old webhook before we send a new one
* delete the webhook using webhook_token if there is one
* sometimes the webhook is not deleted, so we need to delete it manually
* and sometines we are gettiting not found error
* @param string $webhook_token
*/
private static function delete_webhook($webhook_token) {
$curl_handle = Hm_Functions::c_init();
Hm_Functions::c_setopt($curl_handle, CURLOPT_URL, static::PREFIX_URI.'bot'.$webhook_token.'/delete_webhook');
Hm_Functions::c_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
Hm_Functions::c_exec($curl_handle);
}
}
21 changes: 20 additions & 1 deletion modules/core/site.js
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,24 @@ var reset_default_value_checkbox = function() {
}
};

var reset_default_value_input_webhook_token = function() {
let field = this.parentElement.parentElement.querySelector('input[type="text"]');
const defaultValue = field.getAttribute("data-default-value");

if (field.disabled == false) {
this.style.transform = "scaleX(1)";
this.parentElement.setAttribute("restore_aria_label", hm_trans("Restore current value"));
field.setAttribute("current_value", field.value);
field.value = defaultValue; // Use the default value (which is now an empty string)
field.disabled = true;
} else {
this.style.transform = "scaleX(-1)";
this.parentElement.setAttribute("restore_aria_label", hm_trans("Restore default value"));
field.value = field.getAttribute("current_value");
field.disabled = false;
}
};

var reset_default_value_select = function() {
let field = this.parentElement.parentElement.firstChild;
let tab_static_default_value = {"inline_message_style" : 0, "smtp_compose_type" : 0, "theme_setting" : 0,
Expand Down Expand Up @@ -1942,6 +1960,7 @@ $(function() {
$('.reset_default_value_checkbox').on("click", reset_default_value_checkbox);
$('.reset_default_value_select').on("click", reset_default_value_select);
$('.reset_default_value_input').on("click", reset_default_value_input);
$('.reset_default_value_input_webhook_token').on("click", reset_default_value_input_webhook_token);
}

if (hm_check_dirty_flag()) {
Expand Down Expand Up @@ -2602,7 +2621,7 @@ const observeMessageTextMutationAndHandleExternalResources = (inline) => {
if (mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach(function (node) {
if (node.classList.contains('msg_text_inner')) {
handleExternalResources(inline);
handleExternalResources(inline);
}
});
}
Expand Down
2 changes: 1 addition & 1 deletion modules/feeds/hm-feed.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ function get_feed_data($url) {
}
switch ($type) {
case 'curl':
$curl_handle=curl_init();
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36");
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,15);
Expand Down
26 changes: 25 additions & 1 deletion modules/imap/handler_modules.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<?php

/**
* IMAP modules
* @package modules
Expand All @@ -8,6 +7,7 @@

if (!defined('DEBUG_MODE')) { die(); }

require_once APP_PATH .'lib/telegram_webhook.php';

/**
* Check for attachments when forwarding a message
Expand Down Expand Up @@ -93,6 +93,16 @@ public function process() {
}
}

class Hm_Handler_process_webhook_token_setting extends Hm_Handler_Module {
/**
* Allowed values are greater than zero and less than MAX_PER_SOURCE
*/
public function process() {
function webhook_token_callback($val) { return $val; }
process_site_setting('webhook_token', $this, 'webhook_token_callback', false, true);
}
}

/**
* Process input from the max google contacts input in the settings page
* @subpackage imap/handler
Expand Down Expand Up @@ -1304,6 +1314,20 @@ public function process() {
$this->out('folder_status', $status);
$this->out('imap_unread_data', $msg_list);
$this->out('imap_server_ids', $form['imap_server_ids']);

$webhook_token = $this->user_config->get('webhook_token_setting');
$msg_count = count($msg_list);
$email_to = $msg_list[0]['to'];
if ($msg_count > 0) {
$interval = 5 * 60;
Baraka24 marked this conversation as resolved.
Show resolved Hide resolved
set_time_limit(0);
while (true) {
if($webhook_token && !empty($webhook_token)) {
Hm_Telegram_Webhook::send($msg_count, $email_to, $webhook_token);
sleep($interval);
}
}
}
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions modules/imap/output_modules.php
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,23 @@ protected function output() {
}
}

class Hm_Output_webhook_token_setting extends Hm_Output_Module {
protected function output() {
$settings = $this->get('user_settings', array());
$webhook_token = '';
$reset = '';
if (array_key_exists('webhook_token', $settings)) {
$webhook_token = $settings['webhook_token'];
}
if (!empty($webhook_token)) {
$reset = '<span class="tooltip_restore" restore_aria_label="Restore default value"><i class="bi bi-arrow-repeat refresh_list reset_default_value_input_webhook_token"></i></span>';
}
return '<tr class="general_setting"><td><label for="webhook_token">'.
$this->trans('Webhook telegram token').'</label></td><td><input class="form-control form-control-sm w-auto" type="text" id="webhook_token" '.
'name="webhook_token" value="'.$this->html_safe($webhook_token).'" data-default-value="" />'.$reset.'</td></tr>';
}
}

/**
* Option to set number of google contacts
* @subpackage imap/output
Expand Down
5 changes: 4 additions & 1 deletion modules/imap/setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
add_handler('settings', 'process_enable_simple_download_options', true, 'imap', 'date', 'after');
add_handler('settings', 'process_unread_on_open', true, 'imap', 'date', 'after');
add_handler('settings', 'process_imap_per_page_setting', true, 'imap', 'date', 'after');
add_handler('settings', 'process_webhook_token_setting', true, 'imap', 'save_user_settings', 'before');
add_handler('settings', 'process_max_google_contacts_number', true, 'imap', 'date', 'after');
add_handler('settings', 'process_review_sent_email_setting', true, 'imap', 'date', 'after');
add_handler('settings', 'process_auto_advance_email_setting', true, 'imap', 'date', 'after');
Expand All @@ -51,6 +52,7 @@
add_output('settings', 'imap_pagination_links', true, 'imap', 'imap_msg_icons_setting', 'after');
add_output('settings', 'imap_unread_on_open', true, 'imap', 'imap_msg_icons_setting', 'after');
add_output('settings', 'imap_per_page_setting', true, 'imap', 'imap_pagination_links', 'after');
add_output('settings', 'webhook_token_setting', true, 'imap', 'imap_per_page_setting', 'after');
add_output('settings', 'enable_simple_download_options', true, 'imap', 'imap_per_page_setting', 'after');
add_output('settings', 'max_google_contacts_number', true, 'imap', 'imap_per_page_setting', 'after');
add_output('settings', 'review_sent_email', true, 'imap', 'imap_pagination_links', 'after');
Expand Down Expand Up @@ -416,6 +418,7 @@
'review_sent_email' => FILTER_VALIDATE_BOOLEAN,
'imap_snooze_ids' => FILTER_DEFAULT,
'imap_snooze_until' => FILTER_DEFAULT,
'auto_advance_email' => FILTER_VALIDATE_BOOLEAN
'auto_advance_email' => FILTER_VALIDATE_BOOLEAN,
'webhook_token' => FILTER_DEFAULT,
)
);