Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
AAWW00 committed Oct 7, 2023
1 parent 1bb64d7 commit 1dbbf40
Show file tree
Hide file tree
Showing 8 changed files with 540 additions and 0 deletions.
Empty file added bot.log
Empty file.
122 changes: 122 additions & 0 deletions bot.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
<?php
include 'config.php';

// paths to AIML files and logs
$aimlFilePath = 'demo.aiml';
$logFilePath = 'bot.log';

// function for reading AIML file and parsing its contents
function readAIMLFile($filename) {
$aimlContent = file_get_contents($filename);
$aimlData = [];
$pattern = '/<pattern>(.*?)<\/pattern>\s*<template>(.*?)<\/template>/is';
preg_match_all($pattern, $aimlContent, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
$aimlData[] = [
'pattern' => $match[1],
'template' => $match[2]
];
}

return $aimlData;
}

// function for colculateeng the percantage of streeng motches using the Levenshtein algarithm for speling corection))0)
function levenshteinPercentage($str1, $str2) {
$len1 = mb_strlen($str1, 'UTF-8');
$len2 = mb_strlen($str2, 'UTF-8');

$maxLen = max($len1, $len2);

if ($maxLen === 0) {
return 0;
}

$distance = levenshtein($str1, $str2);
return (1 - ($distance / $maxLen)) * 100;
}

// function for processing user requests using AIML templates
function processAIML($message, $aimlData) {
$message = trim($message);
$message = mb_strtoupper($message, 'UTF-8');

$bestMatchPercentage = 0;
$bestTemplate = 'I dont understand 🙈';

foreach ($aimlData as $aimlItem) {
$pattern = mb_strtoupper($aimlItem['pattern'], 'UTF-8');
$patternDistance = levenshteinPercentage($message, $pattern);

if ($patternDistance >= 50 && $patternDistance > $bestMatchPercentage) {
$bestMatchPercentage = $patternDistance;
$bestTemplate = $aimlItem['template'];
}
}

// process <random> and <li>
$bestTemplate = processRandomAndLi($bestTemplate);

return $bestTemplate;
}

function processRandomAndLi($template) {
// pattern for searching <random> & </random>
$randomPattern = '/<random>(.*?)<\/random>/is';
preg_match_all($randomPattern, $template, $randomMatches);

if (!empty($randomMatches[1])) {
$randomContent = $randomMatches[1];
$randomResponse = $randomContent[array_rand($randomContent)]; // choose a random element
$liPattern = '/<li>(.*?)<\/li>/is';
preg_match_all($liPattern, $randomResponse, $liMatches);

if (!empty($liMatches[1])) {
$randomResponse = $liMatches[1][array_rand($liMatches[1])]; // choose <li>
$template = str_replace($randomMatches[0], $randomResponse, $template);
}
}

return $template;
}

// function for logging information about requests and responses
function logMessage($fileName, $userId, $userName, $userMessage, $botResponse) {
$logLine = $userName . ' (' . $userId . ') | ' . $userMessage . ' | ' . $botResponse . "\n";
file_put_contents($fileName, $logLine, FILE_APPEND);
}

$update = json_decode(file_get_contents('php://input'), true);
$message = $update['message']['text'];
$chatId = $update['message']['chat']['id'];
$userName = $update['message']['from']['first_name'];
$userId = $update['message']['from']['id'];

$aimlData = readAIMLFile($aimlFilePath);

if (isset($message)) {
$response = processAIML($message, $aimlData);
sendMessage($chatId, $response);

// loging
logMessage($logFilePath, $userId, $userName, $message, $response);
}

// send message Telegram API
function sendMessage($chatId, $message) {
global $config;
$url = 'https://api.telegram.org/bot' . $config['telegram_token'] . '/sendMessage';
$params = [
'chat_id' => $chatId,
'text' => $message
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
9 changes: 9 additions & 0 deletions config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php
// configuration data
$config = [
'telegram_token' => 'YOUBOTTOKEN', //bot token
'aiml_file_path' => 'demo.aiml', //AIML file
'log_file_path' => 'bot.log', //log file
];


Empty file added demo.aiml
Empty file.
53 changes: 53 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, user-scalable=no">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<form action="save_aiml.php" method="post">
<input type="text" id="pattern" name="pattern" placeholder="Enter pattern 🖋">
<input type="text" id="template" name="template" placeholder="Enter template 🖋">
<div id="random-responses">
<button type="button" class="variations-button" onclick="addRandomResponse()"> + Add response variations + </button>
</div>
<button type="submit" class="save-button">Save 💾</button>
<div class="plugins">plugins 🧩</div> <!-- add your button for the plugin, please add an emoji in the plugin name 🙃 -->
<button type="button" onclick="document.location='log.php'" class="menu-button">LogConsole 📟</button>
<button type="button" onclick="document.location='aiml_editor.php'" class="menu-button">Edit AIML file 📝</button>
<button type="button" onclick="document.location='aiml_editor.php'" class="menu-button">Edit Bot 🤖</button>
</form>
</div>

<script>
//add <li> tags
function addRandomResponse() {
var randomResponsesList = document.getElementById('random-responses');
var newResponseItem = document.createElement('div');
newResponseItem.classList.add('response-item');
newResponseItem.innerHTML = '<input type="text" placeholder="Enter response 🖋" name="random_response[]">' +
'<button type="button" class="remove-button" onclick="removeResponse(this)">🗑️</button>';
randomResponsesList.appendChild(newResponseItem);
// disable the template field
document.getElementById('template').disabled = true;
}
//delete <li> tags
function removeResponse(button) {
var responseItem = button.parentElement;
if (responseItem.parentElement.id === 'random-responses') {
responseItem.remove();
} else {
alert('hmhmh its error');
}
// enable the template field if there are no random responses
var randomResponses = document.querySelectorAll('#random-responses .response-item');
if (randomResponses.length === 0) {
document.getElementById('template').disabled = false;
}
}
</script>
</body>
</html>
44 changes: 44 additions & 0 deletions log.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, user-scalable=no">
<link rel="stylesheet" href="style.css">
<!-- menu button -->
<button type="button" onclick="document.location='index.html'" class="backmenu-button">menu 📰</button>
</head>
<body>
<button type="button" onclick="document.location='index.html'" class="backmenu-button">menu 📰</button>
<div class="form">
<table class="log-table" id="log-table">
<tbody id="log-container">
<?php
$logFilePath = 'bot.log';
if (file_exists($logFilePath)) {
$lines = array_reverse(file($logFilePath, FILE_IGNORE_NEW_LINES)); // reversing the array

foreach ($lines as $line) {
if (preg_match('/^(.*?) \((\d+)\) \| (.*?) \| (.*)$/', $line, $matches)) {
$name = trim($matches[1]);
$id = $matches[2];
$question = $matches[3];
$answer = $matches[4];

echo '<tr>';
echo '<td>' . $name . '</td>';
echo '<td>' . $id . '</td>';
echo '<td>' . $question . '</td>';
echo '<td>' . $answer . '</td>';
echo '</tr>';
}
}
} else {
echo '<tr><td colspan="4">Error: Log file not found</td></tr>';
}
?>
</tbody>
</table>
</div>
</body>
</html>
42 changes: 42 additions & 0 deletions save_aiml.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php
$pattern = $_POST['pattern'] ?? '';
$template = $_POST['template'] ?? '';
$randomResponses = $_POST['random_response'] ?? [];

// check if there are random responses
$hasRandomResponses = !empty($randomResponses);

// write the AIML content to a file
$fileContent = "<category>\n";
$fileContent .= " <pattern>{$pattern}</pattern>\n";

// add random responses
if ($hasRandomResponses) {
$fileContent .= " <template>{$template}<random>\n";
foreach ($randomResponses as $response) {
// check if the response is not empty before adding
if (!empty($response)) {
$fileContent .= " <li>{$response}</li>\n";
}
}
$fileContent .= " </random></template>\n";
} elseif (!empty($template)) {
// if no random responses but theres a template, add it
$fileContent .= " <template>{$template}</template>\n";
} else {
// no random responses or template, skip adding anything
}

$fileContent .= "</category>\n\n"; // add an empty line after each category

$file = fopen('demo.aiml', 'a'); //AIML file

if ($file) {
fwrite($file, $fileContent);
fclose($file);
header('Location: index.html'); // reload page
exit(); // make sure to exit after a header redirect
} else {
echo "Failed to open AIML file";
}
?>

0 comments on commit 1dbbf40

Please sign in to comment.