Skip to content

Instantly share code, notes, and snippets.

@RamBouda22
Created February 8, 2025 09:40
Show Gist options
  • Save RamBouda22/b257d915eeec67ecd358098cf7e4bd78 to your computer and use it in GitHub Desktop.
Save RamBouda22/b257d915eeec67ecd358098cf7e4bd78 to your computer and use it in GitHub Desktop.
LeBon ChatBot
<div class="wrap lebon-settings">
<h1><?php esc_html_e('LeBon ChatBot Settings', 'lebon-chatbot'); ?></h1>
<form method="post" action="options.php">
<?php settings_fields('lebon_chat_colors'); ?>
<h2><?php esc_html_e('Color Settings', 'lebon-chatbot'); ?></h2>
<table class="form-table">
<tr>
<th><?php esc_html_e('Primary Color', 'lebon-chatbot'); ?></th>
<td>
<input type="text" name="lebon_chat_colors[primary]"
value="<?php echo esc_attr(get_option('lebon_chat_colors')['primary']); ?>"
class="color-picker">
</td>
</tr>
<!-- Plus de champs couleur... -->
</table>
<?php submit_button(); ?>
</form>
</div>
<div id="lebon-chatbot">
<div class="lebon-chat-icon">🤖</div>
<div class="lebon-chat-panel">
<div class="lebon-chat-header">
<h3>LeBon Assistant</h3>
<button class="lebon-close-btn">×</button>
</div>
<div class="lebon-messages"></div>
<div class="lebon-service-section">
<button class="lebon-service-btn">Service Client 🛠️</button>
</div>
<div class="lebon-input-area">
<input type="text" class="lebon-input" placeholder="Comment puis-je vous aider ?">
<button class="lebon-send-btn">Envoyer</button>
</div>
</div>
</div>
<?php include LEBON_PLUGIN_DIR . 'templates/troubleshooting-menu.php'; ?>
<?php
class LeBon_Admin {
public function __construct() {
add_action('admin_menu', [$this, 'add_admin_menu']);
add_action('admin_init', [$this, 'register_settings']);
add_action('admin_enqueue_scripts', [$this, 'admin_assets']);
}
public function add_admin_menu() {
add_menu_page(
'LeBon ChatBot Settings',
'LeBon ChatBot',
'manage_options', // Ensure user has admin capabilities
'lebon-chatbot',
[$this, 'settings_page'],
'dashicons-format-chat', // Add WordPress dashicon
80 // Position in menu
);
}
// ... rest of the code ...
public function register_settings() {
// Couleurs
register_setting('lebon_chat_colors', 'lebon_chat_colors');
// Dépannage
register_setting('lebon_troubleshooting', 'lebon_common_problems');
register_setting('lebon_troubleshooting', 'lebon_manual_link');
// Produits
register_setting('lebon_products', 'lebon_product_categories');
}
public function admin_assets($hook) {
if ($hook !== 'toplevel_page_lebon-chatbot') return;
wp_enqueue_style('wp-color-picker');
wp_enqueue_style(
'lebon-admin-css',
LEBON_PLUGIN_URL . 'assets/css/lebon-admin.css',
[],
filemtime(LEBON_PLUGIN_DIR . 'assets/css/lebon-admin.css')
);
wp_enqueue_script(
'lebon-admin-js',
LEBON_PLUGIN_URL . 'assets/js/lebon-admin.js',
['jquery', 'wp-color-picker'],
filemtime(LEBON_PLUGIN_DIR . 'assets/js/lebon-admin.js'),
true
);
}
public function settings_page() {
include LEBON_PLUGIN_DIR . 'templates/admin-settings.php';
}
}
<?php
class LeBon_AI {
private $api_key;
public function __construct() {
$this->api_key = get_option('lebon_deepseek_key');
add_action('wp_ajax_lebon_process_message', [$this, 'process_message']);
add_action('wp_ajax_nopriv_lebon_process_message', [$this, 'process_message']);
add_action('lebon_daily_cleanup', [$this, 'clean_logs']);
}
public function process_message() {
try {
check_ajax_referer('lebon-chat-nonce', 'nonce');
$message = sanitize_text_field($_POST['message']);
$response = $this->generate_response($message);
wp_send_json_success([
'response' => $response,
'timestamp' => current_time('mysql')
]);
} catch (Exception $e) {
wp_send_json_error([
'message' => $e->getMessage()
], 500);
}
}
private function generate_response($message) {
// Logique de réponse ici
}
public function clean_logs() {
// Nettoyage des logs
}
public function handle_product_search($query) {
$args = [
'post_type' => 'product',
's' => sanitize_text_field($query),
'meta_query' => [
[
'key' => '_price',
'value' => [0, get_option('lebon_max_product_price', 1000)],
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
]
]
];
$results = new WP_Query($args);
if($results->have_posts()) {
$response = '<div class="lebon-product-results">';
while($results->have_posts()) {
$results->the_post();
$response .= $this->format_product_result(get_the_ID());
}
$response .= '</div>';
wp_reset_postdata();
return $response;
}
return $this->fallback_response();
}
private function format_product_result($product_id) {
// Formatage des résultats produits
}
}
<?php
class LeBon_Chat {
public function __construct() {
add_action('wp_footer', [$this, 'render_interface'], 100);
add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);
add_shortcode('lebon_chat', [$this, 'shortcode_handler']);
}
public function enqueue_assets() {
// Force refresh cache avec versioning
$version = time(); // À remplacer par une constante de version en production
$css_url = LEBON_PLUGIN_URL . 'assets/css/lebon-front.css';
$js_url = LEBON_PLUGIN_URL . 'assets/js/lebon-chat.js';
// Enregistrement des styles
wp_enqueue_style(
'lebon-chat-css',
$css_url,
[],
$version
);
// Enregistrement des scripts
wp_enqueue_script(
'lebon-chat-js',
$js_url,
['jquery'],
$version,
true
);
// Localisation des variables JavaScript
wp_localize_script('lebon-chat-js', 'lebon_vars', [
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('lebon-chat-nonce'),
'colors' => get_option('lebon_chat_colors'),
'i18n' => [
'error' => __('An error occurred. Please try again.', 'lebon-chatbot'),
'human' => __('Connect to human support', 'lebon-chatbot'),
'placeholder' => __('Type your message...', 'lebon-chatbot')
]
]);
}
public function render_interface() {
if (file_exists(LEBON_PLUGIN_DIR . 'templates/chat-interface.php')) {
include LEBON_PLUGIN_DIR . 'templates/chat-interface.php';
} else {
error_log('LeBon ChatBot: Missing template file - chat-interface.php');
}
}
public function shortcode_handler($atts = []) {
$atts = shortcode_atts([
'position' => 'fixed',
'width' => '350px'
], $atts);
ob_start();
echo '<div class="lebon-chat-shortcode" style="';
echo ($atts['position'] === 'fixed') ? 'position:fixed;bottom:20px;right:20px;' : '';
echo 'width:' . esc_attr($atts['width']) . '">';
$this->render_interface();
echo '</div>';
return ob_get_clean();
}
}
<?php
class LeBon_Product_Helper {
public function __construct() {
add_action('wp_ajax_lebon_search_products', [$this, 'search_products']);
add_action('wp_ajax_nopriv_lebon_search_products', [$this, 'search_products']);
}
public function search_products() {
$search_query = sanitize_text_field($_POST['search_query']);
$results = [];
// Recherche WooCommerce
$args = [
'post_type' => 'product',
's' => $search_query,
'tax_query' => [
[
'taxonomy' => 'product_cat',
'terms' => get_option('lebon_product_categories'),
'operator' => 'IN'
]
]
];
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts()) {
$query->the_post();
$results[] = [
'title' => get_the_title(),
'link' => get_permalink(),
'image' => get_the_post_thumbnail_url(null, 'thumbnail')
];
}
}
wp_send_json_success($results);
}
}
<?php
class LeBon_Shortcodes {
public function __construct() {
add_shortcode('lebon_chat', [$this, 'chat_interface']);
add_shortcode('lebon_troubleshooting', [$this, 'troubleshooting_shortcode']);
add_shortcode('lebon_product_finder', [$this, 'product_finder']);
}
public function chat_interface($atts) {
wp_enqueue_style('lebon-chat-css');
wp_enqueue_script('lebon-chat-js');
$atts = shortcode_atts([
'position' => 'fixed',
'width' => '350px',
'height' => '500px'
], $atts);
ob_start(); ?>
<div class="lebon-chat-container"
data-position="<?= esc_attr($atts['position']) ?>"
style="width: <?= esc_attr($atts['width']) ?>; height: <?= esc_attr($atts['height']) ?>">
<?php do_action('lebon_render_chat_interface'); ?>
</div>
<?php
return ob_get_clean();
}
public function troubleshooting_shortcode() {
if (!is_user_logged_in()) return '';
ob_start(); ?>
<div class="lebon-troubleshooting-shortcode">
<h3><?= esc_html__('Diagnostic Rapide', 'lebon-chatbot') ?></h3>
<div class="lebon-problem-selector">
<?php foreach($this->get_common_problems() as $problem): ?>
<button class="lebon-problem-btn" data-problem="<?= esc_attr($problem['id']) ?>">
<?= esc_html($problem['label']) ?>
</button>
<?php endforeach; ?>
</div>
<div id="lebon-solution-container"></div>
</div>
<?php
return ob_get_clean();
}
private function get_common_problems() {
return [
['id' => 'aspiration', 'label' => __('Problème d\'aspiration', 'lebon-chatbot')],
['id' => 'bruit', 'label' => __('Bruit anormal', 'lebon-chatbot')],
// ... autres problèmes
];
}
public function product_finder($atts) {
$atts = shortcode_atts([
'category' => '',
'max_price' => 0,
'features' => ''
], $atts);
ob_start(); ?>
<div class="lebon-product-finder">
<input type="text" class="lebon-product-search"
placeholder="<?= esc_attr__('Rechercher un aspirateur...', 'lebon-chatbot') ?>">
<div class="lebon-product-results"></div>
</div>
<?php
return ob_get_clean();
}
}
<?php
class LeBon_Troubleshooting {
public function __construct() {
add_action('wp_ajax_lebon_get_troubleshooting', [$this, 'get_troubleshooting']);
add_action('wp_ajax_nopriv_lebon_get_troubleshooting', [$this, 'get_troubleshooting']);
}
public function get_troubleshooting() {
$problem = sanitize_text_field($_POST['problem']);
$solutions = $this->get_solutions($problem);
$response = '<div class="lebon-solution">';
$response .= "<h4>Solution pour : " . ucfirst($problem) . "</h4>";
$response .= "<p>" . $solutions['description'] . "</p>";
$response .= "<ol>";
foreach ($solutions['steps'] as $step) {
$response .= "<li>" . $step . "</li>";
}
$response .= "</ol>";
$response .= '<a href="' . $solutions['manual_link'] . '" class="lebon-manual-link">Voir le manuel</a>';
$response .= '</div>';
wp_send_json_success($response);
}
private function get_solutions($problem) {
// Récupération depuis la base de données
return [
'description' => get_option('lebon_problem_' . $problem . '_desc'),
'steps' => get_option('lebon_problem_' . $problem . '_steps'),
'manual_link' => get_option('lebon_product_manual_link')
];
}
public function log_troubleshooting($user_id, $problem, $solution) {
$history = get_user_meta($user_id, 'lebon_troubleshooting_history', true) ?: [];
$entry = [
'timestamp' => current_time('timestamp'),
'problem' => sanitize_text_field($problem),
'solution' => wp_kses_post($solution)
];
array_unshift($history, $entry);
update_user_meta($user_id, 'lebon_troubleshooting_history', array_slice($history, 0, 10));
}
public function get_manual_steps($problem_id) {
$steps = get_option("lebon_steps_{$problem_id}", []);
return array_map('wp_kses_post', $steps);
}
}
/* Admin interface styling */
.lebon-settings-wrap {
max-width: 800px;
margin: 20px auto;
}
.lebon-color-picker {
display: flex;
gap: 15px;
margin: 15px 0;
}
.lebon-qa-repeater {
border: 1px solid #ddd;
padding: 15px;
margin: 15px 0;
}
.lebon-qa-pair {
display: flex;
gap: 10px;
margin-bottom: 10px;
}
.lebon-qa-actions {
margin-top: 10px;
}
.wp-picker-container {
vertical-align: middle;
}
jQuery(document).ready(function($) {
// Gestion des Q/R
$('#qa-repeater').on('click', '.add-qa', function() {
const clone = $('.lebon-qa-pair:first').clone();
clone.find('input').val('');
$(this).before(clone);
});
// Suppression des Q/R
$('#qa-repeater').on('click', '.remove-qa', function() {
if($('.lebon-qa-pair').length > 1) {
$(this).closest('.lebon-qa-pair').remove();
}
});
// Color picker
$('.lebon-color-field').wpColorPicker();
});
jQuery(document).ready(function($) {
const LebonChat = {
init() {
this.cacheElements();
this.bindEvents();
this.applyColors();
},
cacheElements() {
this.$icon = $('.lebon-chat-icon');
this.$panel = $('.lebon-chat-panel');
this.$messages = $('.lebon-messages');
this.$input = $('.lebon-input');
this.$sendBtn = $('.lebon-send-btn');
},
bindEvents() {
this.$icon.on('click', () => this.toggleChat());
this.$sendBtn.on('click', () => this.sendMessage());
this.$input.on('keypress', (e) => {
if (e.which === 13) this.sendMessage();
});
},
toggleChat() {
this.$panel.slideToggle(300);
},
async sendMessage() {
const message = this.$input.val().trim();
if (!message) return;
this.addMessage(message, 'user');
this.$input.val('');
try {
const response = await $.ajax({
url: lebon_vars.ajaxurl,
method: 'POST',
data: {
action: 'lebon_process_message',
nonce: lebon_vars.nonce,
message: message
}
});
this.addMessage(response.data.response, 'bot');
} catch (error) {
this.showError(lebon_vars.i18n.error);
}
},
addMessage(content, type) {
const message = `
<div class="lebon-message ${type}">
${content}
<div class="lebon-timestamp">${new Date().toLocaleTimeString()}</div>
</div>`;
this.$messages.append(message).scrollTop(this.$messages[0].scrollHeight);
},
applyColors() {
const colors = lebon_vars.colors;
this.$panel.css({
'--primary-color': colors.primary,
'--secondary-color': colors.secondary,
'--text-color': colors.text
});
},
showError(message) {
// Gestion des erreurs
}
};
LebonChat.init();
});
// Gestion des shortcodes
document.addEventListener('DOMContentLoaded', function() {
// Product Finder
document.querySelectorAll('.lebon-product-search').forEach(input => {
input.addEventListener('input', debounce(function(e) {
fetchProducts(e.target.value);
}, 300));
});
function fetchProducts(query) {
fetch(lebon_vars.ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `action=lebon_search_products&nonce=${lebon_vars.nonce}&query=${encodeURIComponent(query)}`
})
.then(response => response.json())
.then(data => {
if(data.success) {
displayProducts(data.data);
}
});
}
});
<?php
/*
Plugin Name: LeBon ChatBot
Description: Assistant intelligent pour LeBon avec service client intégré
Version: 1.1.0
Author: Ram Bouda (NeoAdaptive)
Text Domain: lebon-chatbot
*/
defined('ABSPATH') || exit;
// Définition des constantes
define('LEBON_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('LEBON_PLUGIN_URL', plugin_dir_url(__FILE__));
define('LEBON_MIN_PHP', '7.4');
define('LEBON_MIN_WP', '5.6');
// Vérification des dépendances
if (!version_compare(PHP_VERSION, LEBON_MIN_PHP, '>=')) {
add_action('admin_notices', function() {
echo '<div class="error"><p>';
printf(__('LeBon ChatBot requiert PHP %s ou supérieur. Version actuelle : %s', 'lebon-chatbot'), LEBON_MIN_PP, PHP_VERSION);
echo '</p></div>';
});
return;
}
if (!version_compare(get_bloginfo('version'), LEBON_MIN_WP, '>=')) {
add_action('admin_notices', function() {
echo '<div class="error"><p>';
printf(__('LeBon ChatBot requiert WordPress %s ou supérieur. Version actuelle : %s', 'lebon-chatbot'), LEBON_MIN_WP, get_bloginfo('version'));
echo '</p></div>';
});
return;
}
// Chargement des classes
require_once LEBON_PLUGIN_DIR . 'includes/class-lebon-admin.php';
require_once LEBON_PLUGIN_DIR . 'includes/class-lebon-chat.php';
require_once LEBON_PLUGIN_DIR . 'includes/class-lebon-ai.php';
require_once LEBON_PLUGIN_DIR . 'includes/class-lebon-products.php';
require_once LEBON_PLUGIN_DIR . 'includes/class-lebon-troubleshooting.php';
require_once LEBON_PLUGIN_DIR . 'includes/class-lebon-shortcodes.php';
class LeBon_ChatBot {
public function __construct() {
if ($this->check_woocommerce()) {
$this->init_components();
$this->register_hooks();
}
}
private function check_woocommerce() {
if (!class_exists('WooCommerce')) {
add_action('admin_notices', function() {
echo '<div class="error"><p>';
_e('LeBon ChatBot nécessite WooCommerce pour fonctionner correctement.', 'lebon-chatbot');
echo '</p></div>';
});
return false;
}
return true;
}
private function init_components() {
new LeBon_Admin();
new LeBon_Chat();
new LeBon_AI();
new LeBon_Product_Helper();
new LeBon_Troubleshooting();
new LeBon_Shortcodes();
}
private function register_hooks() {
register_activation_hook(__FILE__, [$this, 'activate']);
register_deactivation_hook(__FILE__, [$this, 'deactivate']);
add_action('plugins_loaded', [$this, 'load_textdomain']);
}
public function activate() {
// Initialisation des options
update_option('lebon_chat_colors', [
'primary' => '#25D366',
'secondary' => '#FFFFFF',
'text' => '#2C3E50'
]);
// Création table logs si nécessaire
// ...
}
public function deactivate() {
wp_clear_scheduled_hook('lebon_daily_cleanup');
}
public function load_textdomain() {
load_plugin_textdomain(
'lebon-chatbot',
false,
dirname(plugin_basename(__FILE__)) . '/languages/'
);
}
}
new LeBon_ChatBot();
/* Interface principale */
#lebon-chatbot {
display: block !important;
position: fixed;
bottom: 25px;
right: 25px;
z-index: 99999;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}
.lebon-chat-panel {
position: fixed;
right: 20px;
bottom: 20px;
width: 350px;
height: 500px;
background: #fff;
box-shadow: 0 5px 40px rgba(0,0,0,0.2);
border-radius: 15px;
overflow: hidden;
}
.lebon-chat-icon {
/* Styles de l'icône... */
}
/* Menu de dépannage */
.lebon-troubleshooting-menu {
background: #f8f9fa;
border-radius: 10px;
padding: 15px;
margin: 15px 0;
border: 1px solid #dee2e6;
}
.lebon-problem-item {
padding: 10px;
margin: 8px 0;
background: white;
border-radius: 8px;
cursor: pointer;
transition: background 0.3s ease;
}
.lebon-problem-item:hover {
background: #e9ecef;
}
/* Messages */
.lebon-message.user {
background: var(--primary-color);
color: white;
border-radius: 15px 15px 0 15px;
}
.lebon-message.bot {
background: #f1f3f5;
color: #212529;
border-radius: 15px 15px 15px 0;
}
<div class="lebon-troubleshooting-wrapper" style="display: none;">
<div class="lebon-troubleshooting-header">
<h4>Diagnostic Produit</h4>
</div>
<div class="lebon-problem-list">
<?php foreach($this->get_common_problems() as $problem): ?>
<div class="lebon-problem-item" data-problem="<?= $problem['slug'] ?>">
<?= $problem['title'] ?>
</div>
<?php endforeach; ?>
</div>
<div class="lebon-manual-section">
<a href="<?= get_option('lebon_manual_link') ?>" target="_blank" class="lebon-manual-link">
📘 Manuel d'utilisation
</a>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment