PHP Classes

File: post-to-discord-channel.php

Recommend this page to a friend!
  Packages of Ákos Nikházy   Post to Discord WordPress Plugin   post-to-discord-channel.php   Download  
File: post-to-discord-channel.php
Role: Example script
Content type: text/plain
Description: Example script
Class: Post to Discord WordPress Plugin
Post about WordPress articles in a Discord channel
Author: By
Last change:
Date: 6 months ago
Size: 6,991 bytes
 

Contents

Class file image Download
<?php
/*
Plugin Name: Post To discord
Description: When you post to your blog post to the discord channel as well.
Version: 1.0
Author: Ákos Nikházy
License: GPL2
*/

if (!defined('ABSPATH')) {
    exit;
}

add_action('admin_menu', 'post_to_discord_menu');
add_action('add_meta_boxes', 'post_to_discord_add_metabox');
add_action('save_post', 'post_to_discord_handle_post');
register_uninstall_hook(__FILE__, 'post_to_discord_remove_options_on_uninstall');

// discord bot token is very important to not store as plain text in the database.
// Anyone knowing the webhook url can post to your discord channel so encryption is a must
function post_to_discord_encrypt($data, $key) {
   
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
   
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    return
base64_encode($encrypted . '{::}' . $iv);
}

// to decrypt the webhook url
function post_to_discord_decrypt($data, $key) {
    list(
$encrypted_data, $iv) = explode('{::}', base64_decode($data), 2);
    return
openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}

// Metabox Registration
function post_to_discord_add_metabox()
{
   
add_meta_box(
       
'post_to_discord_metabox',
       
'Post to Discord',
       
'post_to_discord_render_metabox',
       
'post',
       
'side',
       
'high'
   
);
}

// Render the metabox
function post_to_discord_render_metabox($post)
{
   
$optionBotTokenVale = get_option('post_to_discord_bot_webhook','');
   
    if(
$optionBotTokenVale == '')
    {
// no token, why give any controls? Tell them to set it up and where
       
echo 'Setup Webhook URL here: <a href="/wp-admin/options-general.php?page=post-to-discord-settings">Settings -> Post to Discord</a>';
        return;
    }
?>
<label for="post_to_discord_checkbox">Send to Discord? <input type="checkbox" id="post_to_discord_checkbox" name="post_to_discord_checkbox" value="1">
    </label><br><br>
    <label>Optional text: <input type="text" name="post_to_discord_text" placeholder="this will go before the link"></label>
<?php
}

// Here we clean metabox post data
function post_to_discord_handle_post($post_id)
{
      
    if (isset(
$_POST['post_to_discord_checkbox']))
    {
       
$text = '';
       
        if(isset(
$_POST['post_to_discord_text']))
        {
           
$text = wp_kses($_POST['post_to_discord_text'],array());
        }
       
       
post_to_discord_send_message($post_id,$text);
    }
}

// Send message to discord
function post_to_discord_send_message($post_id,$text)
{
   
   
$webhookurl = get_option('post_to_discord_bot_webhook','');
   
   
    if(
$webhookurl == '')
    {
        return;
    }
   
   
$webhookurl = post_to_discord_decrypt($webhookurl,AUTH_KEY);
   
   
$post = get_post($post_id);
   
   
$message = trim($text . ' ' . $post->post_title . ' - ' . get_permalink($post_id));

   
$data = json_encode(array("content" => $message));

   
// Initialize cURL session
   
$ch = curl_init($webhookurl);
   
   
// Set the required options
   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   
curl_setopt($ch, CURLOPT_POST, true);
   
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   
   
// Execute the cURL request
   
$result = curl_exec($ch);

  
}

// register admin settings menu item
function post_to_discord_menu() {
   
add_options_page(
       
'Post to discord',
       
'Post to discord',
       
'manage_options',
       
'post-to-discord-settings',
       
'post_to_discord_settings_page'
   
);
}

// render admin settings
function post_to_discord_settings_page()
{
    if (!
current_user_can('manage_options')) return;
   
    if (isset(
$_POST['submit']))
    {
// save changes
        // Verify the nonce
       
if (!isset($_POST['post_to_discord_nonce']) || !wp_verify_nonce( sanitize_text_field(wp_unslash($_POST['post_to_discord_nonce'])), 'post_to_discord_action')) {
           
// Nonce verification failed
           
wp_die('Nonce verification failed. Please try again.');
        }
       
        if(isset(
$_POST['post_to_discord_bot_webhook']))
           
$botToken = sanitize_text_field(wp_unslash($_POST['post_to_discord_bot_webhook']));
       
       
       
update_option('post_to_discord_bot_webhook', post_to_discord_encrypt($botToken,AUTH_KEY));
       
       
    }
   
   
$optionBotTokenVale = get_option('post_to_discord_bot_webhook','');
   
$botToken = $optionBotTokenVale;
    if(
$optionBotTokenVale != '')
    {
       
$botToken = post_to_discord_decrypt($optionBotTokenVale,AUTH_KEY);
    }
   
   
/* Hidden nonce field HTML */
   
$html_escaped = '<div class="wrap JDMwrap">
                <h1>Post to discord</h1>
               
                <form method="post" action="">
                    '
. wp_nonce_field('post_to_discord_action', 'post_to_discord_nonce');
   

   
$html_escaped .= '<label for="post_to_discord_bot_webhook">Webhook URL:</label><br>
                    <input type="password" id="post_to_discord_bot_webhook" name="post_to_discord_bot_webhook" value="'
. esc_attr($botToken) . '"><br>';
                   
   
/* Submit button HTML */
   
$html_escaped .= '<br><br>
                <input type="submit" name="submit" class="button button-primary" value="Save Changes">
                </form>'
;
   
$html_escaped .= '<hr>
                    <h2>How to use?</h2>
                    <p>You need a discord channel or group where you want to send links to your posts and a discord bot that will do the deed. These are the steps:
                    <ol>
                        <li>Create a Channel on Discord</li>
                        <li>Create a Webhook in the channel ettings</li>
                        <li>Enter the webhook URL in the field above.</li>
                        <li>When you writing a new post or updateing an existing one, check the checkbox and optionally wirte a text in the metabox. The message with a link to the post will be sent to the channel when you save the post.</li>
                    </ol>'
;

   
   
   
$allowed_html = array(
                   
'div' => array(
                       
'class' => array(),
                    ),
                   
'form' => array(
                       
'method' => array(),
                       
'action' => array()
                    ),
                   
'h1' => array(),
                   
'h2' => array(),
                   
'p' => array(),
                   
'ol' => array(),
                   
'li' => array(),
                   
'label' => array(
                       
'for' => array(),
                       
'class'=> array(),
                       
'id' => array(),
                    ),
                   
'input' => array(
                       
'type' => array(),
                       
'name' => array(),
                       
'value' => array(),
                       
'id' => array(),
                       
'class' =>array(),
                       
'checked' => array(),
                    ),
                   
'br' => array(),
                   
'a' => array(
                       
'href' => array(),
                       
'target' => array(),
                    )
                );
    echo
wp_kses($html_escaped,$allowed_html);
}

// clean up after oursleves (this is especially important so we do not leave behind bot token, not even encrypted)
function post_to_discord_remove_options_on_uninstall() {
  
   
$options_to_remove = array('post_to_discord_bot_webhook', 'post_to_discord_chat_id');

    foreach (
$options_to_remove as $option) {
        if (
get_option($option)) {
           
delete_option($option);
        }
    }

}