Added proper logging and error handling

This commit is contained in:
Miguel Nogueira 2020-12-27 19:26:38 +00:00
parent 03cd015f12
commit 33eb4021fa
Signed by: miguel456
GPG Key ID: 2CF61B825316C6A0
10 changed files with 160 additions and 21 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
vendor/ vendor/
.env .env
Storage/Logs/*.log

View File

@ -1,6 +1,7 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
use Analog\Analog;
use nogueiracodes\RaspberryBot\Bot\Actions\MessageLogger; use nogueiracodes\RaspberryBot\Bot\Actions\MessageLogger;
use nogueiracodes\RaspberryBot\Bot\Commands\Gimme; use nogueiracodes\RaspberryBot\Bot\Commands\Gimme;
use nogueiracodes\RaspberryBot\Bot\Commands\MinecraftInfo; use nogueiracodes\RaspberryBot\Bot\Commands\MinecraftInfo;
@ -13,9 +14,7 @@ require 'src/Bot/init.php';
$raspberryBot = new RaspberryBot(); $raspberryBot = new RaspberryBot();
echo 'RaspberryBot v.0.1.0. Loading commands and actions.' . PHP_EOL; Analog::info('RaspberryBot v.0.1.0 ready. Loading commands and actions.');
echo 'This console will now display logging output from actions and commands sent by users.' . PHP_EOL;
$raspberryBot $raspberryBot
->initialize() ->initialize()
->addCommand([ ->addCommand([

View File

@ -6,7 +6,8 @@
"team-reflex/discord-php": "^5.0", "team-reflex/discord-php": "^5.0",
"vlucas/phpdotenv": "^5.2", "vlucas/phpdotenv": "^5.2",
"kitetail/zttp": "^0.6.0", "kitetail/zttp": "^0.6.0",
"ely/mojang-api": "^0.2.1" "ely/mojang-api": "^0.2.1",
"analog/analog": "^1.0"
}, },
"require-dev": { "require-dev": {
"monolog/monolog": "^2.1" "monolog/monolog": "^2.1"

73
composer.lock generated
View File

@ -4,8 +4,77 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "e9cc6619e8c1bb4e6546fcb9e369bcd4", "content-hash": "e92633d7a29521137b4726e3060ecc6d",
"packages": [ "packages": [
{
"name": "analog/analog",
"version": "1.0.17-stable",
"source": {
"type": "git",
"url": "https://github.com/jbroadway/analog.git",
"reference": "f9541cdf30dfb391a8be1befb05a3344099e6ea9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/jbroadway/analog/zipball/f9541cdf30dfb391a8be1befb05a3344099e6ea9",
"reference": "f9541cdf30dfb391a8be1befb05a3344099e6ea9",
"shasum": ""
},
"require": {
"php": ">=7.2",
"psr/log": "^1.0.1"
},
"require-dev": {
"phpunit/phpunit": "^8.5"
},
"type": "library",
"autoload": {
"psr-0": {
"Analog": "lib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Johnny Broadway",
"email": "johnny@johnnybroadway.com",
"homepage": "http://www.johnnybroadway.com/"
}
],
"description": "Fast, flexible, easy PSR-3-compatible PHP logging package with dozens of handlers.",
"homepage": "https://github.com/jbroadway/analog",
"keywords": [
"PSR3",
"alerts",
"amon",
"apprise",
"chrome-logger",
"console",
"debug",
"debugging",
"error",
"errors",
"firephp",
"gelf",
"log",
"logger",
"logging",
"logs",
"monitor",
"monitoring",
"psr-3",
"stderr",
"syslog"
],
"support": {
"issues": "https://github.com/jbroadway/analog/issues",
"source": "https://github.com/jbroadway/analog/tree/1.0.17-stable"
},
"time": "2020-12-16T17:57:17+00:00"
},
{ {
"name": "brick/math", "name": "brick/math",
"version": "0.9.1", "version": "0.9.1",
@ -3432,5 +3501,5 @@
"prefer-lowest": false, "prefer-lowest": false,
"platform": [], "platform": [],
"platform-dev": [], "platform-dev": [],
"plugin-api-version": "1.1.0" "plugin-api-version": "2.0.0"
} }

View File

@ -2,14 +2,21 @@
namespace nogueiracodes\RaspberryBot\Bot\Actions; namespace nogueiracodes\RaspberryBot\Bot\Actions;
use Analog\Analog;
use nogueiracodes\RaspberryBot\Core\Interfaces\Action; use nogueiracodes\RaspberryBot\Core\Interfaces\Action;
class MessageLogger implements Action class MessageLogger implements Action
{ {
public function __construct()
{
Analog::info('Actions: Loaded MessageLogger!');
}
public function processAction($message) public function processAction($message)
{ {
echo "Sniffed message from " . $message->author->username . ": " . $message->content . PHP_EOL; Analog::info("Siffer: Sniffed message from " . $message->author->username . ": " . $message->content)
} }

View File

@ -2,6 +2,7 @@
namespace nogueiracodes\RaspberryBot\Bot\Commands; namespace nogueiracodes\RaspberryBot\Bot\Commands;
use Analog\Analog;
use Exception; use Exception;
use nogueiracodes\RaspberryBot\Bot\Helpers\CatAPI; use nogueiracodes\RaspberryBot\Bot\Helpers\CatAPI;
use nogueiracodes\RaspberryBot\Core\Interfaces\Command; use nogueiracodes\RaspberryBot\Core\Interfaces\Command;
@ -20,10 +21,19 @@ class Gimme implements Command
public function __construct() public function __construct()
{ {
$this->cats = new CatAPI(); $this->cats = new CatAPI();
Analog::info('Commands: Loaded Gimme!');
} }
public function run(array $parameters) public function run(array $parameters)
{ {
Analog::debug('Gimme: Nr of args: ' . count($parameters));
Analog::debug('Gimme: Thing: ' . $parameters['thing'] ?? 'unset');
Analog::debug('Gimme: Count: ' . $parameters['quantity'] ?? 'unset');
Analog::debug('Gimme: Raw parameter contents: ', json_encode($parameters));
if ($parameters['quantity'] > 25) if ($parameters['quantity'] > 25)
{ {
throw new Exception('Sorry, but I can\'t send you more than 25 cat pictures at a time. What a cat lover!'); throw new Exception('Sorry, but I can\'t send you more than 25 cat pictures at a time. What a cat lover!');

View File

@ -2,6 +2,7 @@
namespace nogueiracodes\RaspberryBot\Bot\Commands; namespace nogueiracodes\RaspberryBot\Bot\Commands;
use Analog\Analog;
use Exception; use Exception;
use nogueiracodes\RaspberryBot\Core\Interfaces\Command; use nogueiracodes\RaspberryBot\Core\Interfaces\Command;
use nogueiracodes\RaspberryBot\Traits\HasSignature; use nogueiracodes\RaspberryBot\Traits\HasSignature;
@ -14,6 +15,10 @@ class Help implements Command
public $signature = "help {section: The section to retrieve help for}"; public $signature = "help {section: The section to retrieve help for}";
public function __construct()
{
Analog::info('Commands: Loaded Help!');
}
public function run(array $parameters) public function run(array $parameters)
{ {

View File

@ -2,6 +2,7 @@
namespace nogueiracodes\RaspberryBot\Bot\Commands; namespace nogueiracodes\RaspberryBot\Bot\Commands;
use Analog\Analog;
use Exception; use Exception;
use nogueiracodes\RaspberryBot\Core\Interfaces\Command; use nogueiracodes\RaspberryBot\Core\Interfaces\Command;
use nogueiracodes\RaspberryBot\Traits\HasSignature; use nogueiracodes\RaspberryBot\Traits\HasSignature;
@ -15,6 +16,11 @@ class NumberFact implements Command
public $signature = "numberfact {number: The number for which you want facts for.}"; public $signature = "numberfact {number: The number for which you want facts for.}";
public function __construct()
{
Analog::log('Commands: Loaded NumberFact!');
}
public function run(array $parameters) public function run(array $parameters)
{ {

View File

@ -7,6 +7,7 @@ use GuzzleHttp\Exception\ClientException;
namespace nogueiracodes\RaspberryBot\Bot\Helpers; namespace nogueiracodes\RaspberryBot\Bot\Helpers;
use Analog\Analog;
use Exception; use Exception;
use InvalidArgumentException; use InvalidArgumentException;
use Zttp\Zttp; use Zttp\Zttp;
@ -18,37 +19,69 @@ class CatAPI {
private $baseURL = "https://api.thecatapi.com/v1/"; private $baseURL = "https://api.thecatapi.com/v1/";
private $hardLimit = 25;
public function __construct() public function __construct()
{
Analog::info('Helpers: Loaded new instance of CatAPI!');
if (isset($_ENV['CAT_API_KEY']))
{ {
$this->headers = [ $this->headers = [
'x-api-key' => $_ENV['CAT_API_KEY'] 'x-api-key' => $_ENV['CAT_API_KEY']
]; ];
} }
else
{
$this->hardLimit = 1;
Analog::urgent('CatAPI ERROR: Failed to load Cat API key. Results limited to 1 picture. It is recommended set an API key.');
}
}
public function getCatPicture($count = 1, $size = "small"): string { public function getCatPicture($count = 1, $size = "small"): string {
// anti smart-ass device Analog::debug('CatAPI: Fetching cat picture with count ' . $count . ' and size ' . $size);
if ($count = 0)
$count = 1;
$catPic = Zttp::withHeaders($this->headers)->get($this->baseURL . 'images/search' . http_build_query([ // anti smart-ass device
if ($count > 0 && $count <= $this->hardLimit)
{
Analog::error('CatAPI: Invalid arguments: Count of ' . $count . ' is over the hard limit of ' . $this->hardLimit);
throw new Exception("Unacceptable quantity: " . $count . ". Please try again with no more than " . $this->hardLimit . " picture(s).");
}
if (!empty($this->headers))
{
$catPic = Zttp::withHeaders($this->headers)->get($this->baseURL . 'images/search', [
'limit' => $count, 'limit' => $count,
'size' => $size, 'size' => $size,
'has_breeds' => false 'has_breeds' => false
])); ]);
}
if ($catPic->isOk()) else
{ {
$catPic = Zttp::get($this->baseURL . 'images/search', [
'limit' => $count,
'size' => $size,
'has_breeds' => false
]);
}
if ($catPic->isSuccess())
{
$results = $catPic->json(); $results = $catPic->json();
$pics = []; $pics = [];
if (count($results) == 1) if (count($results) == 1)
{ {
Analog::debug('CatAPI: Fetched single cat picture.');
return $results[0]['url']; return $results[0]['url'];
} }
foreach($results as $result) foreach($results as $result)
{ {
Analog::debug('CatAPI: Fetched multiple cat pictures; Splitting into EOL divided string.');
array_push($pics, $result['url']); array_push($pics, $result['url']);
} }
@ -57,6 +90,7 @@ class CatAPI {
} }
else else
{ {
Analog::error('CatAPI: Network error. Failed to fetch cat picture. Request status code: ' . $catPic->status());
throw new Exception('Sorry, but I couldn\'t get you a good cat picture this time. Try again later!'); throw new Exception('Sorry, but I couldn\'t get you a good cat picture this time. Try again later!');
} }

View File

@ -1,5 +1,8 @@
<?php <?php
use Analog\Analog;
use Analog\Handler\File;
require realpath(__DIR__ . '/../../vendor/autoload.php'); require realpath(__DIR__ . '/../../vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(realpath(__DIR__ . '/../../')); $dotenv = Dotenv\Dotenv::createImmutable(realpath(__DIR__ . '/../../'));
@ -10,3 +13,7 @@ $dotenv->required('COMMAND_PREFIX')->notEmpty();
$dotenv->required('CAT_API_KEY')->notEmpty(); $dotenv->required('CAT_API_KEY')->notEmpty();
define('PROJECT_ROOT', realpath(__DIR__ . '/../../')); define('PROJECT_ROOT', realpath(__DIR__ . '/../../'));
Analog::handler(File::init(PROJECT_ROOT . 'Storage/Logs/bot.log'));
Analog::info("Finished intializing configuration and dependencies.");