Apply fixes from StyleCI

This commit is contained in:
Benjamin Harris 2017-05-01 19:33:37 +00:00 committed by StyleCI Bot
parent 98549eae10
commit 2e28bcd74e
25 changed files with 537 additions and 713 deletions

View File

@ -4,7 +4,7 @@
ini_set('display_errors', true);
error_reporting(-1);
$procname = $argv[1] ?? "BenBot";
$procname = $argv[1] ?? 'BenBot';
if (!cli_set_process_title($procname)) {
die("couldn't set process title");

View File

@ -1,26 +1,17 @@
<?php
namespace BenBot;
use Carbon\Carbon;
use Discord\Discord;
use Discord\Parts\User\Game;
use Discord\Parts\Embed\Embed;
use Discord\WebSockets\Event;
use BenBot\Utils;
use BenBot\PersistentArray;
use BenBot\Command;
use BenBot\Commands;
use BenBot\FontConverter;
use Carbon\Carbon;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Dotenv\Dotenv;
use Symfony\Component\OptionsResolver\OptionsResolver;
use function Stringy\create as s;
final class BenBot extends Discord
{
public $start_time;
public $dir;
public $defs;
@ -36,12 +27,11 @@ final class BenBot extends Discord
protected $help;
protected $banner;
protected $cmds = [];
protected $cmds = [];
protected $aliases = [];
public function __construct($dir)
{
(new Dotenv($dir))->load();
parent::__construct([
@ -50,18 +40,18 @@ final class BenBot extends Discord
'loadAllMembers' => true,
]);
$this->dir = $dir;
$this->help = [];
$this->jokes = explode("---", file_get_contents("$dir/miscjokes.txt"));
$this->copypastas = explode("---", file_get_contents("$dir/copypasta.txt"));
$this->dir = $dir;
$this->help = [];
$this->jokes = explode('---', file_get_contents("$dir/miscjokes.txt"));
$this->copypastas = explode('---', file_get_contents("$dir/copypasta.txt"));
$this->yomamajokes = file("$dir/yomamajokes.txt");
$this->banner = file_get_contents("{$this->dir}/banner.txt");
$this->tictactoe = [];
$this->hangman = [];
$this->banner = file_get_contents("{$this->dir}/banner.txt");
$this->tictactoe = [];
$this->hangman = [];
try {
$this->defs = new PersistentArray("$dir/bot_data/defs.mp");
$this->imgs = new PersistentArray("$dir/bot_data/img_urls.mp");
$this->defs = new PersistentArray("$dir/bot_data/defs.mp");
$this->imgs = new PersistentArray("$dir/bot_data/img_urls.mp");
$this->cities = new PersistentArray("$dir/bot_data/cities.mp");
$this->emails = new PersistentArray("$dir/bot_data/emails.mp");
} catch (Exception $e) {
@ -70,7 +60,6 @@ final class BenBot extends Discord
///////////////////////////////////////////////////////////////////////////////////////////////////
$this->on('ready', function () {
Utils::init($this);
FontConverter::init();
$this->updatePresence($this->factory(Game::class, [
@ -80,29 +69,29 @@ final class BenBot extends Discord
$this->registerAllCommands();
$msghandler = function ($msg) {
$str = s($msg->content);
if (!$msg->author->bot) {
// handle game move for players
if (Commands\TicTacToe::isActive($msg)) {
Commands\TicTacToe::handleMove($msg);
return;
}
if (Commands\Hangman::isGameOriginator($msg)) {
Commands\Hangman::initGameWithWord($msg);
return;
}
if (Commands\Hangman::isActive($msg)) {
Commands\Hangman::handleMove($msg);
return;
}
if ($str->startsWith(';')) {
// is command!
$args = $str->removeLeft(';')->split(' ');
@ -110,7 +99,7 @@ final class BenBot extends Discord
// look up definition
if (isset($this->defs[$cmd])) {
Utils::send($msg, "**$cmd**: " . $this->defs[$cmd]);
Utils::send($msg, "**$cmd**: ".$this->defs[$cmd]);
}
// look up image
if (isset($this->imgs[$cmd])) {
@ -124,7 +113,6 @@ final class BenBot extends Discord
});
}
// make sure stringys are strings
foreach ($args as $key => $arg) {
$args[$key] = (string) $arg;
@ -132,13 +120,13 @@ final class BenBot extends Discord
// do the font stuff!
if (array_key_exists($cmd, FontConverter::$fonts)) {
Utils::send($msg, FontConverter::$cmd(implode(" ", $args)) . "\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::send($msg, FontConverter::$cmd(implode(' ', $args))."\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
});
return;
}
// look up command
if (array_key_exists($cmd, $this->cmds)) {
$command = $this->cmds[$cmd];
@ -155,22 +143,18 @@ final class BenBot extends Discord
if (is_string($result)) {
Utils::send($msg, $result);
}
} elseif (Utils::isDM($msg)) {
return call_user_func_array(["BenBot\Commands\CleverBot", "chat"], [$msg, explode(' ', $msg->content)]);
return call_user_func_array(["BenBot\Commands\CleverBot", 'chat'], [$msg, explode(' ', $msg->content)]);
}
}
if (!Utils::isDM($msg) && $msg->channel->guild->id === "233603102047993856") {
if (!Utils::isDM($msg) && $msg->channel->guild->id === '233603102047993856') {
if ($str->contains('dib', false)) {
$msg->react(":dib:284335774823088129")->otherwise(function ($e) {
$msg->react(':dib:284335774823088129')->otherwise(function ($e) {
echo $e->getMessage(), PHP_EOL;
});
}
}
}; // --onmsg
$this->on('message', $msghandler);
@ -180,38 +164,34 @@ final class BenBot extends Discord
// register help function
$this->registerCommand('help', function ($msg, $args) {
if (count($args) > 0 && $args[0] != "") {
$cmdstr = implode(" ", $args);
if (count($args) > 0 && $args[0] != '') {
$cmdstr = implode(' ', $args);
$command = $this->getCommand($cmdstr, true);
if (is_null($command)) {
return "The command `;$cmdstr` does not exist";
}
$help = $command->getHelp()["text"];
$help = $command->getHelp()['text'];
return "```$help```";
} else {
$response = "```{$this->banner}\n- a bot made by benh. avatar by hirose.\n\n";
sort($this->help);
$response .= implode("", $this->help);
$response .= implode('', $this->help);
$response .= "\n-------------------------------------------------------------\n;help [command] - get more information about a specific command\ncommands are case-insensitive.\n\n[optional]\n<required>\n| = available options```";
return $response;
}
}, [
'description' => 'shows help text',
'usage' => '<command>',
'usage' => '<command>',
]);
Utils::ping("bot started successfully");
echo PHP_EOL, "BOT STARTED SUCCESSFULLY", PHP_EOL, PHP_EOL;
Utils::ping('bot started successfully');
echo PHP_EOL, 'BOT STARTED SUCCESSFULLY', PHP_EOL, PHP_EOL;
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////
public function registerAllCommands()
{
@ -234,7 +214,6 @@ final class BenBot extends Discord
Commands\Weather::register($this);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
public function registerCommand($command, $callable, array $options = [])
{
@ -250,13 +229,12 @@ final class BenBot extends Discord
}
if ($options['registerHelp']) {
$this->help[$command] = $commandInstance->getHelp()["text"];
$this->help[$command] = $commandInstance->getHelp()['text'];
}
return $commandInstance;
}
public function unregisterCommand($command)
{
if (!array_key_exists($command, $this->cmds)) {
@ -265,13 +243,11 @@ final class BenBot extends Discord
unset($this->cmds[$command]);
}
public function registerAlias($alias, $command)
{
$this->aliases[$alias] = $command;
}
public function unregisterAlias($alias)
{
if (!array_key_exist($alias, $this->aliases)) {
@ -280,7 +256,6 @@ final class BenBot extends Discord
unset($this->aliases[$alias]);
}
public function getCommand($command, $aliases = true)
{
if (array_key_exists($command, $this->cmds)) {
@ -291,11 +266,10 @@ final class BenBot extends Discord
}
}
public function buildCommand($command, $callable, array $options = [])
{
if (!is_callable($callable)) {
throw new \Exception("The callable has to be a callable....");
throw new \Exception('The callable has to be a callable....');
}
$options = $this->resolveCommandOptions($options);
$commandInstance = new Command(
@ -305,7 +279,6 @@ final class BenBot extends Discord
return [$commandInstance, $options];
}
public function resolveCommandOptions(array $options)
{
$resolver = new OptionsResolver();
@ -317,26 +290,26 @@ final class BenBot extends Discord
'registerHelp',
])
->setDefaults([
'description' => 'No description provided yet',
'usage' => '',
'aliases' => [],
'description' => 'No description provided yet',
'usage' => '',
'aliases' => [],
'registerHelp' => false,
]);
$options = $resolver->resolve($options);
if (!empty($options['usage'])) {
$options['usage'] .= ' ';
}
return $options;
}
public function __get($name)
{
$allowed = ['cmds', 'aliases'];
if (array_search($name, $allowed) !== false) {
return $this->$name;
}
return parent::__get($name);
}
}

View File

@ -1,7 +1,7 @@
<?php
namespace BenBot;
use BenBot\BenBot;
use Discord\Parts\Channel\Message;
final class Command
@ -9,7 +9,7 @@ final class Command
protected $command;
protected $description;
protected $usage;
protected $subCommands = [];
protected $subCommands = [];
protected $subCommandAliases = [];
public function __construct(
@ -19,14 +19,13 @@ final class Command
$description,
$usage
) {
$this->client = $client;
$this->command = $command;
$this->callable = $callable;
$this->client = $client;
$this->command = $command;
$this->callable = $callable;
$this->description = $description;
$this->usage = $usage;
$this->usage = $usage;
}
public function handle(Message $message, array $args)
{
$subCommandOrig = array_shift($args);
@ -45,7 +44,6 @@ final class Command
return call_user_func_array($this->callable, [$message, $args]);
}
public function registerSubCommand($command, $callable, array $options = [])
{
if (array_key_exists($command, $this->subCommands)) {
@ -58,10 +56,10 @@ final class Command
foreach ($options['aliases'] as $alias) {
$this->registerSubCommandAlias($alias, $command);
}
return $commandInstance;
}
public function unregisterSubCommand($command)
{
if (!array_key_exists($command, $this->subCommands)) {
@ -70,13 +68,11 @@ final class Command
unset($this->subCommands[$command]);
}
public function registerSubCommandAlias($alias, $command)
{
$this->subCommandAliases[$alias] = $command;
}
public function unregisterSubCommandAlias($alias)
{
if (!array_key_exists($alias, $this->subCommandAliases)) {
@ -85,14 +81,13 @@ final class Command
unset($this->subCommandAliases[$alias]);
}
public function getHelp()
{
$helpString = ";{$this->command} {$this->usage}- {$this->description}\n";
foreach ($this->subCommands as $command) {
$help = $command->getHelp($this->command.' ');
$helpString .= " ;{$this->command} " . ltrim($help['text'], ';');
$helpString .= " ;{$this->command} ".ltrim($help['text'], ';');
}
return [
@ -101,7 +96,6 @@ final class Command
];
}
public function __get($variable)
{
$allowed = ['command', 'description', 'usage'];
@ -109,5 +103,4 @@ final class Command
return $this->{$variable};
}
}
}

View File

@ -1,13 +1,12 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use Discord\Helpers\Process;
use function Stringy\create as s;
final class AsciiArt
{
private static $bot;
private static $figlet;
private static $fonts;
@ -19,62 +18,56 @@ final class AsciiArt
$flags = \FilesystemIterator::SKIP_DOTS
| \FilesystemIterator::UNIX_PATHS;
$di = new \RecursiveDirectoryIterator(self::$bot->dir . "/fonts", $flags);
$di = new \RecursiveDirectoryIterator(self::$bot->dir.'/fonts', $flags);
$it = new \RecursiveIteratorIterator($di);
foreach ($it as $fileinfo) {
if (pathinfo($fileinfo, PATHINFO_EXTENSION) == "flf") {
self::$fonts[$fileinfo->getBasename(".flf")] = $fileinfo->getPathName();
if (pathinfo($fileinfo, PATHINFO_EXTENSION) == 'flf') {
self::$fonts[$fileinfo->getBasename('.flf')] = $fileinfo->getPathName();
}
}
asort(self::$fonts);
$ascii = self::$bot->registerCommand('ascii', [__CLASS__, 'ascii'], [
'description' => 'creates ascii word art',
'usage' => '[font] <words>',
'description' => 'creates ascii word art',
'usage' => '[font] <words>',
'registerHelp' => true,
]);
$ascii->registerSubCommand('list', [__CLASS__, 'listFonts'], [
'description' => 'lists all ' . count(self::$fonts) . ' available ascii fonts',
'aliases' => [
'listfonts'
$ascii->registerSubCommand('list', [__CLASS__, 'listFonts'], [
'description' => 'lists all '.count(self::$fonts).' available ascii fonts',
'aliases' => [
'listfonts',
],
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function ascii($msg, $args)
{
if (isset(self::$fonts[strtolower($args[0])])) {
$filepath = self::$fonts[strtolower($args[0])];
array_shift($args);
} else {
$filepath = self::$fonts["standard"];
$filepath = self::$fonts['standard'];
}
$text = implode(" ", $args);
$text = implode(' ', $args);
$process = new Process("figlet -f $filepath '" . escapeshellarg($text) . "'");
$process = new Process("figlet -f $filepath '".escapeshellarg($text)."'");
$process->start(self::$bot->loop);
$process->stdout->on('data', function ($chunk) use ($msg) {
Utils::send($msg, "```$chunk```");
});
}
public static function listFonts($msg, $args)
{
$response = "**available ASCII art fonts**:\n";
$response .= implode(", ", array_keys(self::$fonts));
$response .= implode(', ', array_keys(self::$fonts));
$split = str_split($response, 2000);
foreach ($split as $part) {
Utils::send($msg, $part);
}
}
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
final class Cities
{
private static $bot;
public static function register(&$that)
@ -16,20 +16,18 @@ final class Cities
public static function saveCity($msg, $args)
{
$api_key = getenv('OWM_API_KEY');
$query = rawurlencode(implode(" ", $args));
$query = rawurlencode(implode(' ', $args));
$url = "http://api.openweathermap.org/data/2.5/weather?q=$query&APPID=$api_key&units=metric";
self::$bot->http->get($url)->then(function ($json) use ($msg) {
$lat = $json->coord->lat;
$lng = $json->coord->lon;
$geonamesurl = "http://api.geonames.org/timezoneJSON?username=benharri&lat=$lat&lng=$lng";
self::$bot->http->get($geonamesurl)->then(function ($geojson) use ($msg, $json) {
if (count($msg->mentions) > 0) {
$response = "the preferred city for ";
$response = 'the preferred city for ';
$mentions = [];
foreach ($msg->mentions as $mention) {
self::$bot->cities[$mention->id] = [
@ -41,7 +39,7 @@ final class Cities
];
$mentions[] = "$mention";
}
$response .= implode(", ", $mentions) . " has been set to {$json->name}";
$response .= implode(', ', $mentions)." has been set to {$json->name}";
Utils::send($msg, $response);
} else {
self::$bot->cities[$msg->author->id] = [
@ -53,8 +51,7 @@ final class Cities
];
Utils::send($msg, "{$msg->author}, your preferred city has been set to {$json->name}");
}
});
});
}
}
}

View File

@ -1,46 +1,43 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use React\Promise\Deferred;
final class CleverBot
{
private static $bot;
private static $cs;
public static function register(&$that)
{
self::$bot = $that;
self::$cs = [];
self::$cs = [];
self::$bot->registerCommand('chat', [__CLASS__, 'chat'], [
'description' => 'talk to benbot',
'usage' => '<what you want to say>',
'description' => 'talk to benbot',
'usage' => '<what you want to say>',
'registerHelp' => true,
'aliases' => [
'aliases' => [
'',
'cleverbot',
],
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function chat($msg, $args)
{
$msg->channel->broadcastTyping();
$url = "https://www.cleverbot.com/getreply";
$url = 'https://www.cleverbot.com/getreply';
$key = getenv('CLEVERBOT_API_KEY');
$input = rawurlencode(implode(" ", $args));
$input = rawurlencode(implode(' ', $args));
$url .= "?input=$input&key=$key";
if (isset(self::$cs[$msg->channel->id])) {
$url .= "&cs=" . self::$cs[$msg->channel->id];
$url .= '&cs='.self::$cs[$msg->channel->id];
}
self::$bot->http->get($url, null, [], false)->then(function ($apidata) use ($msg) {
@ -48,5 +45,4 @@ final class CleverBot
Utils::send($msg, $apidata->output);
});
}
}

View File

@ -1,16 +1,14 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use BenBot\EmbedColors;
use Discord\Parts\Embed\Embed;
use BenBot\Utils;
use Carbon\Carbon;
use function Stringy\create as s;
use Discord\Parts\Embed\Embed;
final class Debug
{
private static $bot;
public static function register(&$that)
@ -33,22 +31,22 @@ final class Debug
'description' => 'get status of bot and server',
]);
self::$bot->registerCommand('server', [__CLASS__, 'server'], [
'description' => 'displays information about the server',
'description' => 'displays information about the server',
'registerHelp' => true,
'aliases' => [
'aliases' => [
'guild',
],
]);
self::$bot->registerCommand('roles', [__CLASS__, 'roles'], [
'description' => 'lists all roles in the server',
'aliases' => [
'role'
'aliases' => [
'role',
],
]);
self::$bot->registerCommand('whois', [__CLASS__, 'userInfo'], [
'description' => 'get info about a user',
'usage' => '[@user]',
'aliases' => [
'usage' => '[@user]',
'aliases' => [
'user',
'info',
'userinfo',
@ -58,22 +56,19 @@ final class Debug
self::$bot->registerCommand('edittest', [__CLASS__, 'editMsgTest']);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function up($msg, $args)
{
return "benbot has been up for " . self::$bot->start_time->diffForHumans(Carbon::now(), true);
return 'benbot has been up for '.self::$bot->start_time->diffForHumans(Carbon::now(), true);
}
public static function dbg($msg, $args)
{
if (Utils::getUserIDFromMsg($msg) == "193011352275648514") {
if (Utils::getUserIDFromMsg($msg) == '193011352275648514') {
print_r($msg);
Utils::send($msg, "check logs!")->then(function ($result) {
Utils::send($msg, 'check logs!')->then(function ($result) {
self::$bot->loop->addTimer(3, function ($timer) use ($result) {
Utils::deleteMessage($result);
});
@ -83,28 +78,26 @@ final class Debug
}
}
public static function sys($msg, $args)
{
if (Utils::getUserIDFromMsg($msg) == "193011352275648514") {
return "```" . shell_exec(implode(" ", $args)) . "```";
if (Utils::getUserIDFromMsg($msg) == '193011352275648514') {
return '```'.shell_exec(implode(' ', $args)).'```';
} else {
return "**you're not allowed to use that command**";
}
}
public static function botEval($msg, $args)
{
if (Utils::getUserIDFromMsg($msg) == "193011352275648514") {
$cmd = implode(" ", $args);
return "```" . eval("return $cmd;") . "```";
if (Utils::getUserIDFromMsg($msg) == '193011352275648514') {
$cmd = implode(' ', $args);
return '```'.eval("return $cmd;").'```';
} else {
return "**you're not allowed to use that command**";
}
}
public static function status($msg, $args)
{
$usercount = 0;
@ -112,43 +105,36 @@ final class Debug
$usercount += $guild->member_count;
}
$url = "http://test.benharr.is/phpsysinfo/xml.php?plugin=complete&json";
$url = 'http://test.benharr.is/phpsysinfo/xml.php?plugin=complete&json';
self::$bot->http->get($url, null, [], false)->then(function ($result) use ($msg, $usercount) {
print_r($result);
$vitals = $result->Vitals->{"@attributes"};
$vitals = $result->Vitals->{'@attributes'};
$embed = self::$bot->factory(Embed::class, [
'title' => 'Benbot status',
'title' => 'Benbot status',
'thumbnail' => ['url' => self::$bot->avatar],
'color' => EmbedColors::BLUE,
'fields' => [
['name' => 'Server Uptime'
,'value' => Utils::secondsConvert($vitals->Uptime)
'color' => EmbedColors::BLUE,
'fields' => [
['name' => 'Server Uptime', 'value' => Utils::secondsConvert($vitals->Uptime),
],
['name' => 'Bot Uptime'
,'value' => self::$bot->start_time->diffForHumans(Carbon::now(), true)
['name' => 'Bot Uptime', 'value' => self::$bot->start_time->diffForHumans(Carbon::now(), true),
],
['name' => 'Server Load Average'
,'value' => $vitals->LoadAvg
['name' => 'Server Load Average', 'value' => $vitals->LoadAvg,
],
['name' => 'Bot Server Count'
,'value' => count(self::$bot->guilds)
['name' => 'Bot Server Count', 'value' => count(self::$bot->guilds),
],
['name' => 'User Count'
,'value' => $usercount
['name' => 'User Count', 'value' => $usercount,
],
['name' => 'Bot Memory Usage'
,'value' => Utils::convertMemoryUsage()
['name' => 'Bot Memory Usage', 'value' => Utils::convertMemoryUsage(),
],
],
'timestamp' => null,
]);
Utils::send($msg, "", $embed);
Utils::send($msg, '', $embed);
});
}
public static function server($msg, $args)
{
if (Utils::isDM($msg)) {
@ -156,56 +142,43 @@ final class Debug
}
$verification_levels = [
0 => "None: must have discord account",
1 => "Low: must have verified email",
2 => "Medium: must have verified email for more than 5 minutes",
3 => "(╯°□°)╯︵ ┻━┻: must have verified email, be registered on discord for more than 5 minutes, and must wait 10 minutes before speaking in any channel",
0 => 'None: must have discord account',
1 => 'Low: must have verified email',
2 => 'Medium: must have verified email for more than 5 minutes',
3 => '(╯°□°)╯︵ ┻━┻: must have verified email, be registered on discord for more than 5 minutes, and must wait 10 minutes before speaking in any channel',
];
$guild = $msg->channel->guild;
$created_at = Carbon::createFromTimestamp(Utils::timestampFromSnowflake($guild->id));
$embed = self::$bot->factory(Embed::class, [
'title' => "{$guild->name} server info",
'title' => "{$guild->name} server info",
'thumbnail' => [
'url' => $guild->icon
'url' => $guild->icon,
],
'color' => EmbedColors::BLUE,
'color' => EmbedColors::BLUE,
'fields' => [
['name' => 'Owner'
,'value' => "$guild->owner"
,'inline' => true
['name' => 'Owner', 'value' => "$guild->owner", 'inline' => true,
],
['name' => 'Region'
,'value' => $guild->region
,'inline' => true
['name' => 'Region', 'value' => $guild->region, 'inline' => true,
],
['name' => 'Member Count'
,'value' => $guild->member_count
,'inline' => true
['name' => 'Member Count', 'value' => $guild->member_count, 'inline' => true,
],
['name' => 'Channel Count'
,'value' => count($guild->channels)
,'inline' => true
['name' => 'Channel Count', 'value' => count($guild->channels), 'inline' => true,
],
['name' => 'Server Created'
,'value' => $created_at->format('g:i A \o\n l F j, Y') . " (" . $created_at->diffForHumans() . ")"
['name' => 'Server Created', 'value' => $created_at->format('g:i A \o\n l F j, Y').' ('.$created_at->diffForHumans().')',
],
['name' => 'Verification level'
,'value' => $verification_levels[$guild->verification_level]
['name' => 'Verification level', 'value' => $verification_levels[$guild->verification_level],
],
['name' => 'Server ID'
,'value' => $guild->id
['name' => 'Server ID', 'value' => $guild->id,
],
['name' => 'benbot joined'
,'value' => $guild->joined_at->format('g:i A \o\n l F j, Y') . " (" . $guild->joined_at->diffForHumans() . ")"
['name' => 'benbot joined', 'value' => $guild->joined_at->format('g:i A \o\n l F j, Y').' ('.$guild->joined_at->diffForHumans().')',
],
],
'timestamp' => null,
]);
Utils::send($msg, "", $embed);
Utils::send($msg, '', $embed);
}
public static function roles($msg, $args)
{
$guild = $msg->channel->guild;
@ -213,11 +186,10 @@ final class Debug
foreach ($guild->roles as $role) {
$response .= "{$role->name} ({$role->id})\n";
}
$response .= "```";
$response .= '```';
Utils::send($msg, $response);
}
public static function userInfo($msg, $args)
{
if (Utils::isDM($msg)) {
@ -238,34 +210,28 @@ final class Debug
$roles[] = $role->name;
}
$embed = self::$bot->factory(Embed::class, [
'title' => "User info for",
'title' => 'User info for',
'description' => "$user",
'thumbnail' => ['url' => $user->user->avatar],
'color' => EmbedColors::BLUE,
'fields' => [
['name' => 'Roles'
,'value' => implode(", ", $roles)
'thumbnail' => ['url' => $user->user->avatar],
'color' => EmbedColors::BLUE,
'fields' => [
['name' => 'Roles', 'value' => implode(', ', $roles),
],
['name' => 'ID'
,'value' => $user->id
['name' => 'ID', 'value' => $user->id,
],
['name' => 'Status'
,'value' => $user->status
['name' => 'Status', 'value' => $user->status,
],
['name' => 'Game'
,'value' => $user->game->name ?? 'not playing anything right now'
['name' => 'Game', 'value' => $user->game->name ?? 'not playing anything right now',
],
['name' => 'Member since'
,'value' => $user->joined_at->format('g:i A \o\n l F j, Y') . " ({$user->joined_at->diffForHumans()})"
['name' => 'Member since', 'value' => $user->joined_at->format('g:i A \o\n l F j, Y')." ({$user->joined_at->diffForHumans()})",
],
],
'timestamp' => null,
]);
Utils::send($msg, "", $embed);
Utils::send($msg, '', $embed);
}
}
public static function editMsgTest($msg, $args)
{
Utils::send($msg, count($msg->channel->guild->channels))->then(function ($result) {
@ -282,6 +248,4 @@ final class Debug
});
});
}
}

View File

@ -1,12 +1,11 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use function String\create as s;
final class Definitions
{
private static $bot;
public static function register(&$that)
@ -17,7 +16,7 @@ final class Definitions
'description' => 'sets this to that',
'usage' => '<this> <that>',
'registerHelp' => true,
'aliases' => [
'aliases' => [
'define',
],
]);
@ -35,20 +34,17 @@ final class Definitions
'description' => 'sends all definitions to DM',
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function setDef($msg, $args)
{
$def = strtolower(array_shift($args));
if ($def == "san" && $msg->author->id != 190933157430689792) {
if ($def == 'san' && $msg->author->id != 190933157430689792) {
return "you're not san...";
}
self::$bot->defs[$def] = implode(" ", $args);
Utils::send($msg, $def . " set to: " . implode(" ", $args))->then(function ($result) use ($msg) {
self::$bot->defs[$def] = implode(' ', $args);
Utils::send($msg, $def.' set to: '.implode(' ', $args))->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
self::$bot->loop->addTimer(5, function ($timer) use ($result) {
Utils::deleteMessage($result);
@ -61,7 +57,7 @@ final class Definitions
if (isset($args[0])) {
$def = strtolower($args[0]);
if (isset(self::$bot->defs[$def])) {
Utils::send($msg, "**$def**: " . self::$bot->defs[$def])->then(function ($result) use ($msg) {
Utils::send($msg, "**$def**: ".self::$bot->defs[$def])->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
});
} else {
@ -81,6 +77,7 @@ final class Definitions
} else {
return "doesn't exist... aborting.";
}
return "$def removed";
}
}
@ -89,12 +86,12 @@ final class Definitions
{
$response = "available definitions:\n\n";
if (isset($args[0]) && strtolower($args[0]) == "show") {
if (isset($args[0]) && strtolower($args[0]) == 'show') {
foreach (self::$bot->defs as $name => $def) {
$response .= "**$name**: $def\n";
}
} else {
$response .= implode(", ", self::$bot->defs->array_keys()) . "\n\ntype `;listdefs show` to show all definitions";
$response .= implode(', ', self::$bot->defs->array_keys())."\n\ntype `;listdefs show` to show all definitions";
}
if (strlen($response) > 2000) {
@ -112,5 +109,4 @@ final class Definitions
});
});
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
final class Emails
{
private static $bot;
public static function register(&$that)
@ -14,22 +14,22 @@ final class Emails
$emailcmd = self::$bot->registerCommand('email', [__CLASS__, 'sendMail'], [
'description' => 'send an email',
'usage' => '[@user] <message>',
'aliases' => [
'usage' => '[@user] <message>',
'aliases' => [
'mail',
],
]);
$emailcmd->registerSubCommand('save', [__CLASS__, 'saveEmailAddress'], [
$emailcmd->registerSubCommand('save', [__CLASS__, 'saveEmailAddress'], [
'description' => 'save an email address',
'usage' => '[@user] <your_email_here@example.com>',
'usage' => '[@user] <your_email_here@example.com>',
]);
$emailcmd->registerSubCommand('show', [__CLASS__, 'showEmail'], [
$emailcmd->registerSubCommand('show', [__CLASS__, 'showEmail'], [
'description' => 'show a saved email address',
'usage' => '[@user]',
'usage' => '[@user]',
]);
$emailcmd->registerSubCommand('remove', [__CLASS__, 'rmEmail'], [
$emailcmd->registerSubCommand('remove', [__CLASS__, 'rmEmail'], [
'description' => 'remove your saved email',
'aliases' => [
'aliases' => [
'rm',
'clear',
'stop',
@ -38,11 +38,9 @@ final class Emails
],
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function sendMail($msg, $args)
{
$recipients = [];
@ -54,24 +52,23 @@ final class Emails
}
}
$to = "";
$to = '';
foreach ($recipients as $recipient) {
if (isset(self::$bot->emails[$recipient])) {
$to .= self::$bot->emails[$recipient] . ";";
$to .= self::$bot->emails[$recipient].';';
} else {
return "no email found for <@$recipient>. you can save an email with `;email save <@user>`";
}
}
$body = implode(" ", $args);
$body = implode(' ', $args);
$from = "From: {$msg->channel->guild->name} {$msg->author->username} benbot <{$msg->author->username}@{$msg->channel->guild->name}.benbot>";
if (mail($to, 'BenBot message', $body, $from)) {
return "message sent successfully";
return 'message sent successfully';
}
}
public static function saveEmailAddress($msg, $args)
{
if (count($msg->mentions) === 0) {
@ -82,43 +79,44 @@ final class Emails
}
array_shift($args);
} else {
return "you can set the email for only one person.";
return 'you can set the email for only one person.';
}
self::$bot->emails[$id] = $args[0];
return "email for <@$id> set to {$args[0]}";
}
public static function showEmail($msg, $args)
{
if (count($msg->mentions) === 0) {
$id = Utils::getUserIDFromMsg($msg);
if (isset(self::$bot->emails[$id])) {
return "your email is " . self::$bot->emails[$id];
return 'your email is '.self::$bot->emails[$id];
} else {
return "you don't have an email set. use `;email save <your_email_here@domain.tld>`";
}
} else {
$response = "";
$response = '';
foreach ($msg->mentions as $mention) {
if (isset(self::$bot->emails[$mention->id])) {
$response .= "{$mention}'s email is " . self::$bot->emails[$mention->id] . "\n";
$response .= "{$mention}'s email is ".self::$bot->emails[$mention->id]."\n";
} else {
$response .= "no email found for {$mention}\n";
}
}
return $response;
}
}
public static function rmEmail($msg, $args)
{
if (count($msg->mentions) === 0) {
$id = Utils::getUserIDFromMsg($msg);
if (isset(self::$bot->emails[$id])) {
unset(self::$bot->emails[$id]);
return "your email has been removed";
return 'your email has been removed';
} else {
return "you didn't have an email saved";
}
@ -126,5 +124,4 @@ final class Emails
return "you can't remove someone else's email";
}
}
}

View File

@ -1,12 +1,12 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use BenBot\FontConverter;
use BenBot\Utils;
final class Fonts
{
private static $bot;
public static function register(&$that)
@ -14,9 +14,9 @@ final class Fonts
self::$bot = $that;
self::$bot->registerCommand('fonts', [__CLASS__, 'fontlist'], [
'description' => 'change your message to another font',
'description' => 'change your message to another font',
'registerHelp' => true,
'aliases' => [
'aliases' => [
'listfonts',
'font',
'text',
@ -25,22 +25,21 @@ final class Fonts
]);
self::$bot->registerCommand('block', [__CLASS__, 'blockText'], [
'description' => 'block text',
'usage' => '<msg>',
'usage' => '<msg>',
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function fontlist($msg, $args)
{
return "available fonts:\n```" . implode(", ", array_keys(FontConverter::$fonts)) . "```use the name of the font as a command";
return "available fonts:\n```".implode(', ', array_keys(FontConverter::$fonts)).'```use the name of the font as a command';
}
public static function blockText($msg, $args)
{
Utils::send($msg, FontConverter::blockText(implode(" ", $args)) . "\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::send($msg, FontConverter::blockText(implode(' ', $args))."\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
});
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
final class Fun
{
private static $bot;
public static function register(&$that)
@ -21,7 +21,7 @@ final class Fun
'description' => 'ask the mighty 8-ball',
'usage' => '<your question to ask here>',
'registerHelp' => true,
'aliases' => [
'aliases' => [
'8b',
'fortune',
],
@ -31,7 +31,7 @@ final class Fun
]);
self::$bot->registerCommand('shrug', [__CLASS__, 'shrugGuy'], [
'description' => 'meh',
'aliases' => [
'aliases' => [
'meh',
],
]);
@ -42,57 +42,54 @@ final class Fun
'description' => 'get random copypasta',
]);
self::$bot->registerCommand('kaomoji', [__CLASS__, 'kaomoji'], [
'description' => 'shows a cool japanese emoji face thing',
'usage' => '[sad|happy|angry|confused|surprised]',
'description' => 'shows a cool japanese emoji face thing',
'usage' => '[sad|happy|angry|confused|surprised]',
'registerHelp' => true,
]);
self::$bot->registerCommand('bamboozle', [__CLASS__, 'bamboozle'], [
'description' => 'bamboozled again',
'usage' => '[@user]',
'usage' => '[@user]',
]);
self::$bot->registerCommand('trap', [__CLASS__, 'trap'], [
'description' => 'hmm',
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function rollDie($msg, $args)
{
return "{$msg->author}, you rolled a " . rand(1, $args[0] == "" ? 6 : $args[0]);
return "{$msg->author}, you rolled a ".rand(1, $args[0] == '' ? 6 : $args[0]);
}
public static function ask8Ball($msg, $args)
{
$fortunes = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes definitely',
'You may rely on it',
'As I see it, yes',
'Most likely',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
'My reply is no',
'My sources say no',
'Outlook not so good',
'Very doubtful',
];
if (count($args) > 0) {
$response = "Your question: *" . implode(" ", $args) . "*\n\n**";
$response .= $fortunes[array_rand($fortunes)] . "**";
$response = 'Your question: *'.implode(' ', $args)."*\n\n**";
$response .= $fortunes[array_rand($fortunes)].'**';
Utils::send($msg, $response)->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
});
@ -103,7 +100,7 @@ final class Fun
public static function lennyFace($msg, $args)
{
echo "lenny", PHP_EOL;
echo 'lenny', PHP_EOL;
Utils::send($msg, "( ͡° ͜ʖ ͡°)\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
});
@ -111,7 +108,7 @@ final class Fun
public static function shrugGuy($msg, $args)
{
echo "meh", PHP_EOL;
echo 'meh', PHP_EOL;
Utils::send($msg, "¯\\\_(ツ)\_/¯")->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
});
@ -119,7 +116,7 @@ final class Fun
public static function noice($msg, $args)
{
$bs = "
$bs = '
:ok_hand: :joy:
:ok_hand::joy:
  :joy:
@ -142,7 +139,7 @@ $bs = "
:joy:  :ok_hand:
:joy: :ok_hand:
:joy: :ok_hand:
  :ok_hand:";
  :ok_hand:';
Utils::send($msg, $bs)->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
@ -157,21 +154,21 @@ $bs = "
public static function kaomoji($msg, $args)
{
$kaomojis = [
'sad' => ['(_<。)', '(*-_-)', '(´-ω-`)', '.・゚゚・(/ω\)・゚゚・.', '(μ_μ)', '(ノД`)', '(-ω-、)', '。゜゜(´`) ゜゜。', 'o(TヘTo)', '( ; ω ; )', '(。╯3╰。)', '。・゚゚*(>д<)*゚゚・。', '( ゚_ゝ)', '(个_个)', '(╯︵╰,)', '。・゚(゚><゚)゚・。', '( ╥ω╥ )', '(╯_╰)', '(╥_╥)', '.。・゚゚・(_)・゚゚・。.', '(/ˍ・、)', '(_<、)', '(╥﹏╥)', '。゚(。ノωヽ。)゚。', '(つω`*)', '(。T ω T。)', '(ノω・、)', '・゚・(。>ω<。)・゚・', '(T_T)', '(>_<)', '(T▽T)', '。゚・ (><) ・゚。', 'o(〒﹏〒)o', '(。•́︿•̀。)', '(ಥ﹏ಥ)'],
'happy' => ['(* ^ ω ^)', '(´ ∀ ` *)', '٩(◕‿◕。)۶', '☆*:.。.o(≧▽≦)o.。.:*☆', '(o^▽^o)', '(⌒▽⌒)☆', '<( ̄︶ ̄)>', 'ヽ(・∀・)ノ', '(´。• ω •。`)', '( ̄ω ̄)', ';:゛;;・(°ε° )', '(o・ω・o)', '()', 'ヽ(*・ω・)ノ', '(o_ _)ノ彡☆', '(^人^)', '(o´▽`o)', '(*´▽`*)', '。゚( ゚^∀^゚)゚。', '( ´ ω ` )', '(((o(*°▽°*)o)))', '(≧◡≦)', '(o´∀`o)', '(´• ω •`)', '(^▽^)', '(⌒ω⌒)', '∑d(°∀°d)', '╰(▔∀▔)╯', '(─‿‿─)', '(*^‿^*)', 'ヽ(o^―^o)ノ', '(✯◡✯)', '(◕‿◕)', '(*≧ω≦*)', '(☆▽☆)', '(⌒‿⌒)', '(≧▽≦)', '⌒(oo)', '(*°▽°*)', '٩(。•́‿•̀。)۶', '(✧ω✧)', 'ヽ(*⌒▽⌒*)ノ', '(´。• ᵕ •。`)', '( ´ ▽ ` )', '( ̄▽ ̄)', '╰(*´︶`*)╯', 'ヽ(>∀<☆)', 'o(≧▽≦)o', '(☆ω☆)', '(っ˘ω˘ς )', '( ̄▽ ̄)', '(*¯︶¯*)', '(^▽^)', '٩(◕‿◕)۶', '(o˘◡˘o)', '\(★ω★)/', '\(^ヮ^)/', '(〃^▽^〃)', '(╯✧▽✧)╯', 'o(>ω<)o', 'o( ❛ᴗ❛ )o', '。゚(TヮT)゚。', '( ‾́ ◡ ‾́ )', '(ノ´ヮ`)ノ*: ・゚'],
'angry' => ['(`Д´)', '(`皿´#)', '( ` ω ´ )', 'ヽ( `д´*)', '(・`ω´・)', '(`ー´)', 'ヽ(`⌒´メ)', '凸(`△´#)', '( `ε´ )', 'ψ( ` ∇ ´ )ψ', 'ヾ(`ヘ´)ノ゙', 'ヽ(´)', '(メ` ロ ´)', '(╬`益´)', '┌∩┐(◣_◢)┌∩┐', '凸( ` ロ ´ )凸', 'Σ(▼□▼メ)', '(°ㅂ°╬)', 'ψ(▼へ▼メ)~→', '(ノ°益°)', '(҂ `з´ )', '(‡▼益▼)', '(҂` ロ ´)凸', '((╬◣﹏◢))', '٩(╬ʘ益ʘ╬)۶', '(╬ Ò﹏Ó)', '\\٩(๑`^´๑)۶//', '(凸ಠ益ಠ)凸', '↑_(ΦwΦ)Ψ', '←~(Ψ▼ー▼)∈', '୧((#Φ益Φ#))', '٩(ఠ益ఠ)۶', '(ノಥ益ಥ)ノ'],
'confused' => ['( ̄ω ̄;)', 'σ( ̄、 ̄〃)', '( ̄~ ̄;)', '(-_-;)・・・', '(・_・ヾ', '(〃 ̄ω ̄〃ゞ', '┐( ̄ヘ ̄;)┌', '(・_・;)', '( ̄_ ̄)・・・', '╮( ̄ω ̄;)╭', '( ̄. ̄;)', '(_)', '(・・;)ゞ', 'Σ( ̄。 ̄ノ)', '(・・ ) ?', '(•ิ_•ิ)?', '(◎ ◎)ゞ', '(ーー;)', 'ლ(ಠ_ಠ ლ)', 'ლ(¯ロ¯"ლ)'],
'surprised' => ['w(°o°)w', 'ヽ(°〇°)ノ', 'Σ(O_O)', 'Σ(°ロ°)', '(⊙_⊙)', '(o_O)', '(O_O;)', '(O.O)', '(°ロ°) !', '(o_O) !', '(□_□)', 'Σ(□_□)', '∑(O_O;)', '( : : )'],
'sad' => ['(_<。)', '(*-_-)', '(´-ω-`)', '.・゚゚・(/ω\)・゚゚・.', '(μ_μ)', '(ノД`)', '(-ω-、)', '。゜゜(´`) ゜゜。', 'o(TヘTo)', '( ; ω ; )', '(。╯3╰。)', '。・゚゚*(>д<)*゚゚・。', '( ゚_ゝ)', '(个_个)', '(╯︵╰,)', '。・゚(゚><゚)゚・。', '( ╥ω╥ )', '(╯_╰)', '(╥_╥)', '.。・゚゚・(_)・゚゚・。.', '(/ˍ・、)', '(_<、)', '(╥﹏╥)', '。゚(。ノωヽ。)゚。', '(つω`*)', '(。T ω T。)', '(ノω・、)', '・゚・(。>ω<。)・゚・', '(T_T)', '(>_<)', '(T▽T)', '。゚・ (><) ・゚。', 'o(〒﹏〒)o', '(。•́︿•̀。)', '(ಥ﹏ಥ)'],
'happy' => ['(* ^ ω ^)', '(´ ∀ ` *)', '٩(◕‿◕。)۶', '☆*:.。.o(≧▽≦)o.。.:*☆', '(o^▽^o)', '(⌒▽⌒)☆', '<( ̄︶ ̄)>', 'ヽ(・∀・)ノ', '(´。• ω •。`)', '( ̄ω ̄)', ';:゛;;・(°ε° )', '(o・ω・o)', '()', 'ヽ(*・ω・)ノ', '(o_ _)ノ彡☆', '(^人^)', '(o´▽`o)', '(*´▽`*)', '。゚( ゚^∀^゚)゚。', '( ´ ω ` )', '(((o(*°▽°*)o)))', '(≧◡≦)', '(o´∀`o)', '(´• ω •`)', '(^▽^)', '(⌒ω⌒)', '∑d(°∀°d)', '╰(▔∀▔)╯', '(─‿‿─)', '(*^‿^*)', 'ヽ(o^―^o)ノ', '(✯◡✯)', '(◕‿◕)', '(*≧ω≦*)', '(☆▽☆)', '(⌒‿⌒)', '(≧▽≦)', '⌒(oo)', '(*°▽°*)', '٩(。•́‿•̀。)۶', '(✧ω✧)', 'ヽ(*⌒▽⌒*)ノ', '(´。• ᵕ •。`)', '( ´ ▽ ` )', '( ̄▽ ̄)', '╰(*´︶`*)╯', 'ヽ(>∀<☆)', 'o(≧▽≦)o', '(☆ω☆)', '(っ˘ω˘ς )', '( ̄▽ ̄)', '(*¯︶¯*)', '(^▽^)', '٩(◕‿◕)۶', '(o˘◡˘o)', '\(★ω★)/', '\(^ヮ^)/', '(〃^▽^〃)', '(╯✧▽✧)╯', 'o(>ω<)o', 'o( ❛ᴗ❛ )o', '。゚(TヮT)゚。', '( ‾́ ◡ ‾́ )', '(ノ´ヮ`)ノ*: ・゚'],
'angry' => ['(`Д´)', '(`皿´#)', '( ` ω ´ )', 'ヽ( `д´*)', '(・`ω´・)', '(`ー´)', 'ヽ(`⌒´メ)', '凸(`△´#)', '( `ε´ )', 'ψ( ` ∇ ´ )ψ', 'ヾ(`ヘ´)ノ゙', 'ヽ(´)', '(メ` ロ ´)', '(╬`益´)', '┌∩┐(◣_◢)┌∩┐', '凸( ` ロ ´ )凸', 'Σ(▼□▼メ)', '(°ㅂ°╬)', 'ψ(▼へ▼メ)~→', '(ノ°益°)', '(҂ `з´ )', '(‡▼益▼)', '(҂` ロ ´)凸', '((╬◣﹏◢))', '٩(╬ʘ益ʘ╬)۶', '(╬ Ò﹏Ó)', '\\٩(๑`^´๑)۶//', '(凸ಠ益ಠ)凸', '↑_(ΦwΦ)Ψ', '←~(Ψ▼ー▼)∈', '୧((#Φ益Φ#))', '٩(ఠ益ఠ)۶', '(ノಥ益ಥ)ノ'],
'confused' => ['( ̄ω ̄;)', 'σ( ̄、 ̄〃)', '( ̄~ ̄;)', '(-_-;)・・・', '(・_・ヾ', '(〃 ̄ω ̄〃ゞ', '┐( ̄ヘ ̄;)┌', '(・_・;)', '( ̄_ ̄)・・・', '╮( ̄ω ̄;)╭', '( ̄. ̄;)', '(_)', '(・・;)ゞ', 'Σ( ̄。 ̄ノ)', '(・・ ) ?', '(•ิ_•ิ)?', '(◎ ◎)ゞ', '(ーー;)', 'ლ(ಠ_ಠ ლ)', 'ლ(¯ロ¯"ლ)'],
'surprised' => ['w(°o°)w', 'ヽ(°〇°)ノ', 'Σ(O_O)', 'Σ(°ロ°)', '(⊙_⊙)', '(o_O)', '(O_O;)', '(O.O)', '(°ロ°) !', '(o_O) !', '(□_□)', 'Σ(□_□)', '∑(O_O;)', '( : : )'],
'embarrassed' => ['(⌒_⌒;)', '(o^ ^o)', '(*/ω\)', '(*/。\)', '(*/_)', '(*ノωノ)', '(o-_-o)', '(*μ_μ)', '( ◡‿◡ *)', '(ᵔ.ᵔ)', '(//ω//)', '(*°▽°*)', '(*^.^*)', '(*ノ▽ノ)', '( ̄▽ ̄*)ゞ', '( ⁄•⁄ω⁄•⁄ )', '(*/▽\*)', '( >< )'],
];
if (isset($args[0]) && isset($kaomojis[$args[0]])) {
Utils::send($msg, $kaomojis[$args[0]][array_rand($kaomojis[$args[0]])] . "\n\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::send($msg, $kaomojis[$args[0]][array_rand($kaomojis[$args[0]])]."\n\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
});
} else {
$allkaomojis = Utils::arrayFlatten($kaomojis);
Utils::send($msg, $allkaomojis[array_rand($allkaomojis)] . "\n\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::send($msg, $allkaomojis[array_rand($allkaomojis)]."\n\n--{$msg->author}")->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
});
}
@ -179,7 +176,7 @@ $bs = "
public static function bamboozle($msg, $args)
{
$response = count($msg->mentions) > 0 ? implode(", ", array_keys($msg->mentions)) : $msg->author;
$response = count($msg->mentions) > 0 ? implode(', ', array_keys($msg->mentions)) : $msg->author;
$response .= ", you've been heccin' bamboozled again!!!!!!!!!!!!!!!!!!!!!!!!";
Utils::sendFile($msg, 'img/bamboozled.jpg', 'bamboozle.jpg', $response)->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
@ -189,11 +186,10 @@ $bs = "
public static function trap($msg, $args)
{
Utils::deleteMessage($msg);
Utils::send($msg, "traps are gay")->then(function ($result) {
Utils::send($msg, 'traps are gay')->then(function ($result) {
self::$bot->loop->addTimer(5, function ($timer) use ($result) {
Utils::editMessage($result, "traps aren't gay");
});
});
}
}

View File

@ -1,8 +1,8 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use function Stringy\create as s;
final class Hangman
@ -14,34 +14,31 @@ final class Hangman
{
self::$bot = $that;
self::$gallows = explode("==", file_get_contents(self::$bot->dir . "/gallows.txt"));
self::$gallows = explode('==', file_get_contents(self::$bot->dir.'/gallows.txt'));
self::$bot->registerCommand('hangman', [__CLASS__, 'startGame'], [
'description' => 'play hangman. everyone in the channel plays. `;hangman stop` to cancel a game in progress.',
'usage' => '[stop]',
'description' => 'play hangman. everyone in the channel plays. `;hangman stop` to cancel a game in progress.',
'usage' => '[stop]',
'registerHelp' => true,
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function isActive($msg)
{
$gameid = $msg->channel->id;
return isset(self::$bot->hangman[$gameid])
&& self::$bot->hangman[$gameid]['active'];
}
public static function isGameOriginator($msg)
{
return Utils::isDM($msg)
&& self::$bot->hangman['readymsg']->author->id === $msg->author->id;
}
public static function initGameWithWord($msg)
{
$gameid = self::$bot->hangman['readymsg']->channel->id;
@ -55,22 +52,20 @@ final class Hangman
self::$bot->hangman['readymsg'] = null;
}
public static function handleMove($msg)
{
$gameid = $msg->channel->id;
$text = strtolower($msg->content);
if (strlen($text) === 1) {
if (in_array($text, self::$bot->hangman[$gameid]['guessed_letters'])) {
Utils::send($msg, self::showGameState($gameid) . "\nalready guessed...")->then(function ($result) use ($msg, $gameid) {
Utils::send($msg, self::showGameState($gameid)."\nalready guessed...")->then(function ($result) use ($msg, $gameid) {
Utils::deleteMessage(self::$bot->hangman[$gameid]['last_msg']);
self::$bot->hangman[$gameid]['last_msg'] = $result;
Utils::deleteMessage($msg);
});
return;
} else {
self::$bot->hangman[$gameid]['guessed_letters'][] = $text;
if (!in_array($text, str_split(self::$bot->hangman[$gameid]['secret_word']))) {
self::$bot->hangman[$gameid]['state']++;
@ -78,14 +73,15 @@ final class Hangman
self::$bot->hangman[$gameid]['active'] = false;
self::$bot->hangman[$gameid]['guessed_letters'] = array_unique(str_split(self::$bot->hangman[$gameid]['secret_word']));
Utils::send($msg,
self::showGameState($gameid) .
"\n**you lose**. the word was:\n" .
self::showGameState($gameid).
"\n**you lose**. the word was:\n".
self::$bot->hangman[$gameid]['secret_word']
)->then(function ($result) use ($msg, $gameid) {
Utils::deleteMessage(self::$bot->hangman[$gameid]['last_msg']);
self::$bot->hangman[$gameid]['last_msg'] = $result;
Utils::deleteMessage($msg);
});
return;
}
} else {
@ -93,36 +89,35 @@ final class Hangman
if (count(array_intersect($secretletters, self::$bot->hangman[$gameid]['guessed_letters'])) === count($secretletters)) {
self::$bot->hangman[$gameid]['active'] = false;
self::$bot->hangman[$gameid]['guessed_letters'] = $secretletters;
Utils::send($msg, self::showGameState($gameid) . "\n**you win!**")->then(function ($result) use ($msg, $gameid) {
Utils::send($msg, self::showGameState($gameid)."\n**you win!**")->then(function ($result) use ($msg, $gameid) {
Utils::deleteMessage(self::$bot->hangman[$gameid]['last_msg']);
self::$bot->hangman[$gameid]['last_msg'] = $result;
Utils::deleteMessage($msg);
});
return;
}
}
}
Utils::send($msg, self::showGameState($gameid))->then(function ($result) use ($msg, $gameid) {
Utils::deleteMessage(self::$bot->hangman[$gameid]['last_msg']);
self::$bot->hangman[$gameid]['last_msg'] = $result;
Utils::deleteMessage($msg);
});
} elseif ($text === strtolower(self::$bot->hangman[$gameid]['secret_word'])) {
self::$bot->hangman[$gameid]['active'] = false;
self::$bot->hangman[$gameid]['guessed_letters'] = array_unique(str_split(self::$bot->hangman[$gameid]['secret_word']));
Utils::send($msg, self::showGameState($gameid) . "\nyou guessed the word! **you win!!**")->then(function ($result) use ($msg, $gameid) {
Utils::send($msg, self::showGameState($gameid)."\nyou guessed the word! **you win!!**")->then(function ($result) use ($msg, $gameid) {
Utils::deleteMessage(self::$bot->hangman[$gameid]['last_msg']);
self::$bot->hangman[$gameid]['last_msg'] = $result;
Utils::deleteMessage($msg);
});
} elseif ($text === ";hangman stop") {
} elseif ($text === ';hangman stop') {
self::$bot->hangman[$gameid]['active'] = false;
self::$bot->hangman[$gameid]['guessed_letters'] = array_unique(str_split(self::$bot->hangman[$gameid]['secret_word']));
Utils::send($msg,
self::showGameState($gameid) .
"\n**game forfeited**. the word was:\n" .
self::showGameState($gameid).
"\n**game forfeited**. the word was:\n".
self::$bot->hangman[$gameid]['secret_word']
)->then(function ($result) use ($msg, $gameid) {
Utils::deleteMessage(self::$bot->hangman[$gameid]['last_msg']);
@ -132,17 +127,16 @@ final class Hangman
}
}
public static function startGame($msg, $args)
{
$gameid = $msg->channel->id;
self::$bot->hangman[$gameid] = [
'active' => false,
'state' => 0,
'active' => false,
'state' => 0,
'guessed_letters' => [' '],
];
self::$bot->hangman['readymsg'] = $msg;
$msg->author->user->sendMessage("enter the secret word")->otherwise(function ($e) {
$msg->author->user->sendMessage('enter the secret word')->otherwise(function ($e) {
echo $e->getMessage(), PHP_EOL;
echo $e->getTraceAsString(), PHP_EOL;
});
@ -151,24 +145,22 @@ final class Hangman
});
}
private static function showSecretWord($gameid)
{
$ret = "Word: ";
$ret = 'Word: ';
foreach (s(self::$bot->hangman[$gameid]['secret_word']) as $char) {
$ret .= $char == ' ' ? ' ' : in_array($char, self::$bot->hangman[$gameid]['guessed_letters']) ? $char : "_";
$ret .= " ";
$ret .= $char == ' ' ? ' ' : in_array($char, self::$bot->hangman[$gameid]['guessed_letters']) ? $char : '_';
$ret .= ' ';
}
return $ret;
}
private static function showGameState($gameid)
{
return "```" . self::$gallows[self::$bot->hangman[$gameid]['state']] . "\n" .
self::showSecretWord($gameid) . "\n\n" .
"Incorrect letters: " . implode(" ", array_diff(self::$bot->hangman[$gameid]['guessed_letters'], str_split(self::$bot->hangman[$gameid]['secret_word']))) . "\n" .
"Guessed letters:" . implode(" ", self::$bot->hangman[$gameid]['guessed_letters']) . "```";
return '```'.self::$gallows[self::$bot->hangman[$gameid]['state']]."\n".
self::showSecretWord($gameid)."\n\n".
'Incorrect letters: '.implode(' ', array_diff(self::$bot->hangman[$gameid]['guessed_letters'], str_split(self::$bot->hangman[$gameid]['secret_word'])))."\n".
'Guessed letters:'.implode(' ', self::$bot->hangman[$gameid]['guessed_letters']).'```';
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
final class Images
{
private static $bot;
public static function register(&$that)
@ -13,32 +13,30 @@ final class Images
self::$bot = $that;
$img = self::$bot->registerCommand('img', [__CLASS__, 'img'], [
'description' => 'save and retrieve images',
'usage' => '<name of image to show|list|save|rm>',
'description' => 'save and retrieve images',
'usage' => '<name of image to show|list|save|rm>',
'registerHelp' => true,
]);
$img->registerSubCommand('save', [__CLASS__, 'save'], [
$img->registerSubCommand('save', [__CLASS__, 'save'], [
'description' => 'saves attached image',
'usage' => '<name>',
'usage' => '<name>',
]);
$img->registerSubCommand('list', [__CLASS__, 'listImgs'], [
$img->registerSubCommand('list', [__CLASS__, 'listImgs'], [
'description' => 'lists all saved images',
]);
$img->registerSubCommand('rm', [__CLASS__, 'delImg'], [
$img->registerSubCommand('rm', [__CLASS__, 'delImg'], [
'description' => 'deletes a saved image',
'usage' => '<image name>',
'aliases' => [
'usage' => '<image name>',
'aliases' => [
'del',
'remove',
'delete',
],
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function img($msg, $args)
{
if (isset($args[0])) {
@ -47,7 +45,7 @@ final class Images
$msg->channel->broadcastTyping();
Utils::sendFile(
$msg,
self::$bot->dir . "/uploaded_images/" . self::$bot->imgs[$imgname],
self::$bot->dir.'/uploaded_images/'.self::$bot->imgs[$imgname],
self::$bot->imgs[$imgname],
"$imgname\nby {$msg->author}"
)->then(function ($result) use ($msg) {
@ -57,7 +55,7 @@ final class Images
return "$imgname does not exist. you can save it by attaching the image with `;img save $imgname`";
}
} else {
return "type the name of the image you want. type `;img list` to see the name of all available images.";
return 'type the name of the image you want. type `;img list` to see the name of all available images.';
}
}
@ -69,25 +67,25 @@ final class Images
return "img with this name already exists. change the name or remove the current img with `;img rm $imgname` and then re-save it.";
} else {
if (count($msg->attachments) < 1) {
return "please attach an image";
return 'please attach an image';
} else {
$ext = pathinfo($msg->attachments[0]->url, PATHINFO_EXTENSION);
self::$bot->imgs[$imgname] = "$imgname.$ext";
file_put_contents(self::$bot->dir . "/uploaded_images/$imgname.$ext", file_get_contents($msg->attachments[0]->url));
file_put_contents(self::$bot->dir."/uploaded_images/$imgname.$ext", file_get_contents($msg->attachments[0]->url));
return "image save as $imgname";
}
}
}
}
public static function listImgs($msg, $args)
{
$imgs = self::$bot->imgs->array_keys();
sort($imgs);
return "avilable images:\n\n" . implode(", ", $imgs);
}
return "avilable images:\n\n".implode(', ', $imgs);
}
public static function delImg($msg, $args)
{
@ -96,14 +94,15 @@ final class Images
if (isset(self::$bot->imgs[$imgname])) {
$img = self::$bot->imgs[$imgname];
unset(self::$bot->imgs[$imgname]);
unlink(self::$bot->dir . "/uploaded_images/$img");
unlink(self::$bot->dir."/uploaded_images/$img");
return "$imgname deleted";
} else {
return "that wasn't an image...";
}
} {
return "you have to tell me which image to delete";
}
{
return 'you have to tell me which image to delete';
}
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
final class Jokes
{
private static $bot;
public static function register(&$that)
@ -13,34 +13,29 @@ final class Jokes
self::$bot = $that;
$joke = self::$bot->registerCommand('joke', [__CLASS__, 'joke'], [
'description' => 'tells a random joke',
'usage' => '[chucknorris|yomama|dad]',
'description' => 'tells a random joke',
'usage' => '[chucknorris|yomama|dad]',
'registerHelp' => true,
]);
$joke->registerSubCommand('chucknorris', [__CLASS__, 'chucknorris'], [
$joke->registerSubCommand('chucknorris', [__CLASS__, 'chucknorris'], [
'description' => 'get a fact about chuck norris',
'aliases' => [
'aliases' => [
'chuck',
'norris',
],
]);
$joke->registerSubCommand('yomama', [__CLASS__, 'yomama'], [
$joke->registerSubCommand('yomama', [__CLASS__, 'yomama'], [
'description' => 'yo mama joke',
]);
$joke->registerSubCommand('dad', [__CLASS__, 'dad'], [
$joke->registerSubCommand('dad', [__CLASS__, 'dad'], [
'description' => 'get a dad joke',
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function joke($msg, $args)
{
return self::$bot->jokes[array_rand(self::$bot->jokes)];
@ -48,8 +43,8 @@ final class Jokes
public static function chucknorris($msg, $args)
{
echo "looking up chucknorris joke", PHP_EOL;
$url = "http://api.icndb.com/jokes/random1";
echo 'looking up chucknorris joke', PHP_EOL;
$url = 'http://api.icndb.com/jokes/random1';
self::$bot->http->get($url, null, [], false)->then(function ($result) use ($msg) {
Utils::send($msg, $result->value->joke);
}, function ($e) use ($msg) {
@ -64,13 +59,12 @@ final class Jokes
public static function dad($msg, $args)
{
echo "looking up dad joke", PHP_EOL;
$url = "https://icanhazdadjoke.com";
echo 'looking up dad joke', PHP_EOL;
$url = 'https://icanhazdadjoke.com';
self::$bot->http->get($url, null, ['Accept' => 'application/json'], false)->then(function ($result) use ($msg) {
Utils::send($msg, $result->joke);
}, function ($e) use ($msg) {
Utils::send($msg, $e->getMessage());
});
}
}

View File

@ -1,4 +1,5 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
@ -6,7 +7,6 @@ use function Stringy\create as s;
final class Misc
{
private static $bot;
public static function register(&$that)
@ -18,50 +18,49 @@ final class Misc
]);
self::$bot->registerCommand('text_benh', [__CLASS__, 'textBenh'], [
'description' => 'sends an SMS to benh',
'usage' => '[message]',
'aliases' => [
'usage' => '[message]',
'aliases' => [
'textben',
],
'registerHelp' => true,
]);
self::$bot->registerCommand('say', [__CLASS__, 'say'], [
'description' => 'says stuff back to you',
'usage' => '[stuff to say]',
'usage' => '[stuff to say]',
]);
self::$bot->registerCommand('dm', [__CLASS__, 'dm'], [
'description' => 'sends a dm',
'usage' => '[@user] [message]',
'description' => 'sends a dm',
'usage' => '[@user] [message]',
'registerHelp' => true,
'aliases' => [
'aliases' => [
'pm',
],
]);
self::$bot->registerCommand('avatar', [__CLASS__, 'avatar'], [
'description' => 'gets avatar for a user (gets your own if you don\'t mention anyone)',
'usage' => '<@user>',
'aliases' => [
'usage' => '<@user>',
'aliases' => [
'profilepic',
'pic',
'userpic',
],
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function hi($msg, $args)
{
$greetings = [
"hello {$msg->author}, how are you today?",
"soup",
"hi!",
"henlo",
"hallo!",
"hola",
"wassup",
'soup',
'hi!',
'henlo',
'hallo!',
'hola',
'wassup',
];
return $greetings[array_rand($greetings)];
}
@ -74,17 +73,17 @@ final class Misc
$server = $msg->channel->guild->name;
$user = Utils::isDM($msg) ? $msg->author->username : $msg->author->user->username;
$from = "From: {$server} Discord <{$server}@bot.benharris.ch>";
$msg_body = "$user:\n\n" . implode(" ", $args);
$msg_body = "$user:\n\n".implode(' ', $args);
if (mail(getenv('PHONE_NUMBER')."@vtext.com", "", $msg_body, $from)) {
return "message sent to benh";
if (mail(getenv('PHONE_NUMBER').'@vtext.com', '', $msg_body, $from)) {
return 'message sent to benh';
}
}
public static function say($msg, $args)
{
$a = s(implode(" ", $args));
if ($a->contains("@everyone") || $a->contains("@here")) {
$a = s(implode(' ', $args));
if ($a->contains('@everyone') || $a->contains('@here')) {
return "sorry can't do that! :P";
}
Utils::send($msg, "$a\n\n**love**, {$msg->author}")->then(function ($result) use ($msg) {
@ -94,8 +93,8 @@ final class Misc
public static function sing($msg, $args)
{
$a = s(implode(" ", $args));
if ($a->contains("@everyone") || $a->contains("@here")) {
$a = s(implode(' ', $args));
if ($a->contains('@everyone') || $a->contains('@here')) {
return "sorry can't do that! :P";
}
Utils::send($msg, ":musical_note::musical_note::musical_note::musical_note::musical_note::musical_note:\n\n$a\n\n:musical_note::musical_note::musical_note::musical_note::musical_note::musical_note:, {$msg->author}")->then(function ($result) use ($msg) {
@ -109,13 +108,13 @@ final class Misc
return "you're already in a DM, silly";
}
if (count($msg->mentions) == 0) {
$msg->author->user->sendMessage("hi, {$msg->author} said:\n" . implode(" ", $args));
$msg->author->user->sendMessage("hi, {$msg->author} said:\n".implode(' ', $args));
} else {
foreach ($msg->mentions as $mention) {
$mention->sendMessage("hi!\n{$msg->author} said:\n\n" . implode(" ", $args));
$mention->sendMessage("hi!\n{$msg->author} said:\n\n".implode(' ', $args));
}
}
Utils::send($msg, "sent!")->then(function ($result) use ($msg) {
Utils::send($msg, 'sent!')->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
self::$bot->loop->addTimer(3, function ($timer) use ($msg, $result) {
Utils::deleteMessage($result);
@ -137,5 +136,4 @@ final class Misc
}
}
}
}

View File

@ -1,17 +1,15 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use React\Promise\Deferred;
use Discord\Helpers\Process;
use Discord\Voice\VoiceClient;
use Discord\Parts\Channel\Channel;
use Discord\Voice\VoiceClient;
use React\Promise\Deferred;
final class Music
{
private static $bot;
private static $voiceclients;
@ -23,8 +21,8 @@ final class Music
self::$bot->registerCommand('play', [__CLASS__, 'playFromYouTube'], [
'description' => 'plays',
'usage' => '<yt ID|URL|search>',
'aliases' => [
'usage' => '<yt ID|URL|search>',
'aliases' => [
'yt',
],
]);
@ -41,18 +39,16 @@ final class Music
'description' => 'ur just my type',
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function playTest($msg, $args)
{
$guild = self::$bot->guilds->get('id', '289410862907785216');
$channel = $guild->channels->get('id', '294208856970756106');
self::$bot->joinVoiceChannel($channel)->then(function (VoiceClient $vc) {
$vc->playFile(self::$bot->dir . '/music/mytype.m4a')->then(function ($test) use ($vc){
$vc->playFile(self::$bot->dir.'/music/mytype.m4a')->then(function ($test) use ($vc) {
//Leave voice channel
$vc->close();
});
@ -62,7 +58,6 @@ final class Music
});
}
public static function playFromYouTube($msg, $args)
{
$channel = self::getVoiceChannel($msg);
@ -70,16 +65,16 @@ final class Music
return "you're not in a voice channel, silly";
}
Utils::send($msg, "getting info...")->then(function ($statusmsg) use ($channel, $msg, $args) {
Utils::send($msg, 'getting info...')->then(function ($statusmsg) use ($channel, $msg, $args) {
self::getVideoJSON($args)->then(function ($json) use ($channel, $msg, $statusmsg) {
$statusmsg->content = "downloading...";
$statusmsg->content = 'downloading...';
$statusmsg->channel->messages->save($statusmsg);
print_r($json);
self::downloadAudio($json)->then(function ($file) use ($channel, $statusmsg, $msg) {
$statusmsg->channel->messages->delete($statusmsg);
self::$bot->joinVoiceChannel($channel)->then(function (VoiceClient $vc) use ($file, $msg) {
self::$voiceclients[$msg->channel->guild->id] = $vc;
$vc->playFile(self::$bot->dir . "/music/$file")->then(function () use ($vc) {
$vc->playFile(self::$bot->dir."/music/$file")->then(function () use ($vc) {
$vc->close();
}, function ($e) {
echo $e->getMessage(), PHP_EOL;
@ -100,52 +95,51 @@ final class Music
});
}
public static function pauseAudio($msg, $args)
{
if (self::$voiceclients[$msg->channel->guild->id] instanceof VoiceClient) {
self::$voiceclients[$msg->channel->guild->id]->pause();
return "paused";
return 'paused';
} else {
return "not playing...";
return 'not playing...';
}
}
public static function resumeAudio($msg, $args)
{
if (self::$voiceclients[$msg->channel->guild->id] instanceof VoiceClient) {
self::$voiceclients[$msg->channel->guild->id]->unpause();
return "resuming";
return 'resuming';
} else {
return "not stopped...";
return 'not stopped...';
}
}
public static function stopAudio($msg, $args)
{
if (self::$voiceclients[$msg->channel->guild->id] instanceof VoiceClient) {
self::$voiceclients[$msg->channel->guild->id]->stop();
return "stopped";
return 'stopped';
} else {
return "not playing...";
return 'not playing...';
}
}
private static function getVideoJSON($args)
{
$deferred = new Deferred();
$cmd = "youtube-dl --dump-single-json ";
if ($args[0] != "") {
$cmd = 'youtube-dl --dump-single-json ';
if ($args[0] != '') {
if (strlen($args[0]) === 11) {
$cmd .= "https://www.youtube.com/watch?v={$args[0]}";
} elseif (strpos($args[0], "youtube.com") !== false) {
} elseif (strpos($args[0], 'youtube.com') !== false) {
$cmd = $args[0];
} else {
$query = implode(" ", $args);
$query = implode(' ', $args);
$cmd .= "'ytsearch:$query'";
}
}
@ -172,23 +166,23 @@ final class Music
return $deferred->promise();
}
private static function downloadAudio($result)
{
$deferred = new Deferred();
$json = $result->entries[0] ?? $result;
$url = escapeshellarg($json->webpage_url);
$filename = $json->id . '-' . md5($json->title) . '-' . $json->duration;
$filename = $json->id.'-'.md5($json->title).'-'.$json->duration;
foreach (scandir(self::$bot->dir . '/music') as $file) {
foreach (scandir(self::$bot->dir.'/music') as $file) {
// check if we've already downloaded the file!
if (pathinfo($file, PATHINFO_FILENAME) === $filename) {
$deferred->resolve($file);
return $deferred->promise();
}
}
$file = escapeshellarg(self::$bot->dir . "/music/$filename.%(ext)s");
$file = escapeshellarg(self::$bot->dir."/music/$filename.%(ext)s");
$cmd = "youtube-dl --extract-audio --audio-format mp3 --audio-quality 0 --restrict-filenames --no-playlist --no-check-certificate --no-warnings --source-address 0.0.0.0 -o $file $url";
echo $cmd, PHP_EOL;
@ -198,7 +192,7 @@ final class Music
if (intval($exitcode) !== 0) {
$deferred->reject('error downloading video');
} else {
foreach (scandir(self::$bot->dir . '/music') as $file) {
foreach (scandir(self::$bot->dir.'/music') as $file) {
if (pathinfo($file, PATHINFO_FILENAME) === $filename) {
$deferred->resolve($file);
}
@ -213,7 +207,6 @@ final class Music
return $deferred->promise();
}
private static function getVoiceChannel($msg)
{
foreach ($msg->channel->guild->channels->getAll('type', Channel::TYPE_VOICE) as $voicechannel) {
@ -221,7 +214,5 @@ final class Music
return $voicechannel;
}
}
return null;
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
final class Poll
{
private static $bot;
public static function register(&$that)
@ -13,30 +13,29 @@ final class Poll
self::$bot = $that;
self::$bot->registerCommand('poll', [__CLASS__, 'createPoll'], [
'description' => 'yes/no poll. lasts 30 seconds.',
'usage' => '<question>',
'description' => 'yes/no poll. lasts 30 seconds.',
'usage' => '<question>',
'registerHelp' => true,
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function createPoll($msg, $args)
{
if ($args[0] == "") {
if ($args[0] == '') {
return "you didn't ask a question...";
}
$question = implode(" ", $args);
$question = implode(' ', $args);
$response = "{$msg->author}'s poll:\n\n*$question*";
Utils::send($msg, $response)->then(function ($result) use ($msg) {
Utils::deleteMessage($msg);
$result->react("👍");
$result->react("👎");
$result->react('👍');
$result->react('👎');
$poll_results = [
'upboats' => 0,
'upboats' => 0,
'downboats' => 0,
];
@ -54,9 +53,9 @@ final class Poll
)->then(function ($downboats) use (&$poll_results, $res) {
$poll_results['downboats'] = count($downboats) - 1;
switch ($poll_results['upboats'] <=> $poll_results['downboats']) {
case 1: $conclusion = "Yes!"; break;
case 1: $conclusion = 'Yes!'; break;
case 0: $conclusion = "It's a tie..."; break;
case -1: $conclusion = "Nope"; break;
case -1: $conclusion = 'Nope'; break;
}
Utils::editMessage($res,
"{$res->content}\n\n**Results**\nUpboats: {$poll_results['upboats']}\nDownboats: {$poll_results['downboats']}\n**$conclusion**"
@ -68,5 +67,4 @@ final class Poll
});
});
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
final class TicTacToe
{
private static $bot;
public static function register(&$that)
@ -13,24 +13,22 @@ final class TicTacToe
self::$bot = $that;
$tic = self::$bot->registerCommand('tic', [__CLASS__, 'startGame'], [
'description' => 'play tic tac toe!',
'usage' => '<@user>',
'description' => 'play tic tac toe!',
'usage' => '<@user>',
'registerHelp' => true,
'aliases' => [
'aliases' => [
'tictactoe',
'tictac',
'ttt',
],
]);
$tic->registerSubCommand('stop', [__CLASS__, 'stopGame'], [
$tic->registerSubCommand('stop', [__CLASS__, 'stopGame'], [
'description' => 'stops current game',
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
// 1 2 3
// 4 5 6
// 7 8 9
@ -42,31 +40,30 @@ final class TicTacToe
// [0, 0, 0],
// ];
// functions to register
public static function startGame($msg, $args)
{
if (count($msg->mentions) === 0) {
return "mention someone who you would like to play with!";
return 'mention someone who you would like to play with!';
} elseif (count($msg->mentions) === 1) {
$gameid = $msg->channel->id;
self::$bot->tictactoe[$gameid] = [
'board' => [
[":one:", ":two:", ":three:"],
[":four:", ":five:", ":six:"],
[":seven:", ":eight:", ":nine:"],
[':one:', ':two:', ':three:'],
[':four:', ':five:', ':six:'],
[':seven:', ':eight:', ':nine:'],
],
'game' => 'TicTacToe',
'game' => 'TicTacToe',
'players' => [
":x:" => $msg->author->id
':x:' => $msg->author->id,
],
'turn' => ":x:",
'turn' => ':x:',
'active' => true,
];
foreach ($msg->mentions as $mention) {
self::$bot->tictactoe[$gameid]['players'][":o:"] = $mention->id;
self::$bot->tictactoe[$gameid]['players'][':o:'] = $mention->id;
}
Utils::send($msg, self::printBoard($gameid) . "\n<@" . self::$bot->tictactoe[$gameid]['players'][self::$bot->tictactoe[$gameid]['turn']] . ">, it's your turn!")->then(function ($result) use ($gameid, $msg) {
Utils::send($msg, self::printBoard($gameid)."\n<@".self::$bot->tictactoe[$gameid]['players'][self::$bot->tictactoe[$gameid]['turn']].">, it's your turn!")->then(function ($result) use ($gameid, $msg) {
self::$bot->tictactoe[$gameid]['last_msg'] = $result;
Utils::deleteMessage($msg);
});
@ -75,7 +72,6 @@ final class TicTacToe
}
}
public static function isActive($msg)
{
$gameid = $msg->channel->id;
@ -85,16 +81,16 @@ final class TicTacToe
&& $msg->author->id === self::$bot->tictactoe[$gameid]['players'][self::$bot->tictactoe[$gameid]['turn']];
}
public static function handleMove($msg)
{
$gameid = $msg->channel->id;
$player = self::$bot->tictactoe[$gameid]['turn'];
$text = $msg->content;
$move = intval($text);
$text = $msg->content;
$move = intval($text);
if (strtolower($text) == "stop" || strtolower($text) == ";tic stop") {
if (strtolower($text) == 'stop' || strtolower($text) == ';tic stop') {
self::stopGame($msg, []);
return;
}
if ($move > 0 && $move < 10) {
@ -103,39 +99,38 @@ final class TicTacToe
self::$bot->tictactoe[$gameid]['last_msg'] = $result;
Utils::deleteMessage($msg);
});
return;
} else {
Utils::deleteMessage(self::$bot->tictactoe[$gameid]['last_msg']);
Utils::send($msg, self::printBoard($gameid) . "\ninvalid move. enter a number 1-9 or quit with `;tic stop`")->then(function ($result) use ($gameid, $msg) {
Utils::send($msg, self::printBoard($gameid)."\ninvalid move. enter a number 1-9 or quit with `;tic stop`")->then(function ($result) use ($gameid, $msg) {
self::$bot->tictactoe[$gameid]['last_msg'] = $result;
Utils::deleteMessage($msg);
});
return;
}
}
public static function doMove($gameid, $player, $move)
{
if (self::placePieceAt($gameid, $move, $player)) {
if (self::checkWin($gameid)) {
self::$bot->tictactoe[$gameid]['active'] = false;
$response = "<@" . self::$bot->tictactoe[$gameid]['players'][self::$bot->tictactoe[$gameid]['turn']] . "> (" . self::$bot->tictactoe[$gameid]['turn'] . ") won!";
$response = '<@'.self::$bot->tictactoe[$gameid]['players'][self::$bot->tictactoe[$gameid]['turn']].'> ('.self::$bot->tictactoe[$gameid]['turn'].') won!';
} elseif (isset(self::$bot->tictactoe[$gameid]['tied']) && self::$bot->tictactoe[$gameid]['tied']) {
self::$bot->tictactoe[$gameid]['active'] = false;
$response = "it's a tie... game over";
} else {
self::$bot->tictactoe[$gameid]['turn'] = self::$bot->tictactoe[$gameid]['turn'] == ":x:" ? ":o:" : ":x:";
$response = "<@" . self::$bot->tictactoe[$gameid]['players'][self::$bot->tictactoe[$gameid]['turn']] . ">, it's your turn! (you're " . self::$bot->tictactoe[$gameid]['turn'] . "'s)";
self::$bot->tictactoe[$gameid]['turn'] = self::$bot->tictactoe[$gameid]['turn'] == ':x:' ? ':o:' : ':x:';
$response = '<@'.self::$bot->tictactoe[$gameid]['players'][self::$bot->tictactoe[$gameid]['turn']].">, it's your turn! (you're ".self::$bot->tictactoe[$gameid]['turn']."'s)";
}
} else {
$response = "position $move occupied! try again.";
}
return self::printBoard($gameid) . "\n$response";
}
return self::printBoard($gameid)."\n$response";
}
public static function stopGame($msg, $args)
{
@ -144,33 +139,31 @@ final class TicTacToe
self::$bot->tictactoe[$gameid] = [
'active' => false,
];
Utils::send($msg, "game stopped")->then(function ($result) {
Utils::send($msg, 'game stopped')->then(function ($result) {
self::$bot->loop->addTimer(5, function ($timer) use ($result) {
Utils::deleteMessage($result);
});
});
}
// internal functions
private static function checkWin($gameid)
{
if ((self::getPieceAt($gameid, 1) === self::getPieceAt($gameid, 4)) && (self::getPieceAt($gameid, 4) === self::getPieceAt($gameid, 7))) {
return true;
} else if ((self::getPieceAt($gameid, 2) === self::getPieceAt($gameid, 5)) && (self::getPieceAt($gameid, 5) === self::getPieceAt($gameid, 8))) {
} elseif ((self::getPieceAt($gameid, 2) === self::getPieceAt($gameid, 5)) && (self::getPieceAt($gameid, 5) === self::getPieceAt($gameid, 8))) {
return true;
} else if ((self::getPieceAt($gameid, 3) === self::getPieceAt($gameid, 6)) && (self::getPieceAt($gameid, 6) === self::getPieceAt($gameid, 9))) {
} elseif ((self::getPieceAt($gameid, 3) === self::getPieceAt($gameid, 6)) && (self::getPieceAt($gameid, 6) === self::getPieceAt($gameid, 9))) {
return true;
} else if ((self::getPieceAt($gameid, 1) === self::getPieceAt($gameid, 2)) && (self::getPieceAt($gameid, 2) === self::getPieceAt($gameid, 3))) {
} elseif ((self::getPieceAt($gameid, 1) === self::getPieceAt($gameid, 2)) && (self::getPieceAt($gameid, 2) === self::getPieceAt($gameid, 3))) {
return true;
} else if ((self::getPieceAt($gameid, 4) === self::getPieceAt($gameid, 5)) && (self::getPieceAt($gameid, 5) === self::getPieceAt($gameid, 6))) {
} elseif ((self::getPieceAt($gameid, 4) === self::getPieceAt($gameid, 5)) && (self::getPieceAt($gameid, 5) === self::getPieceAt($gameid, 6))) {
return true;
} else if ((self::getPieceAt($gameid, 7) === self::getPieceAt($gameid, 8)) && (self::getPieceAt($gameid, 8) === self::getPieceAt($gameid, 9))) {
} elseif ((self::getPieceAt($gameid, 7) === self::getPieceAt($gameid, 8)) && (self::getPieceAt($gameid, 8) === self::getPieceAt($gameid, 9))) {
return true;
} else if ((self::getPieceAt($gameid, 1) === self::getPieceAt($gameid, 5)) && (self::getPieceAt($gameid, 5) === self::getPieceAt($gameid, 9))) {
} elseif ((self::getPieceAt($gameid, 1) === self::getPieceAt($gameid, 5)) && (self::getPieceAt($gameid, 5) === self::getPieceAt($gameid, 9))) {
return true;
} else if ((self::getPieceAt($gameid, 3) === self::getPieceAt($gameid, 5)) && (self::getPieceAt($gameid, 5) === self::getPieceAt($gameid, 7))) {
} elseif ((self::getPieceAt($gameid, 3) === self::getPieceAt($gameid, 5)) && (self::getPieceAt($gameid, 5) === self::getPieceAt($gameid, 7))) {
return true;
} else {
for ($i = 1; $i <= 9; $i++) {
@ -185,24 +178,24 @@ final class TicTacToe
self::$bot->tictactoe[$gameid]['active'] = false;
self::$bot->tictactoe[$gameid]['tied'] = true;
}
return false;
}
}
private static function printBoard($gameid)
{
$response = "";
$response = '';
foreach (self::$bot->tictactoe[$gameid]['board'] as $row) {
foreach ($row as $col) {
$response .= $col;
}
$response .= "\n";
}
return $response;
}
private static function getPieceAt($gameid, $i)
{
return self::$bot->tictactoe[$gameid]['board'][intval(($i - 1) / 3)][($i - 1) % 3];
@ -210,13 +203,12 @@ final class TicTacToe
private static function placePieceAt($gameid, $i, $piece)
{
if (self::getPieceAt($gameid, $i) == ":x:" || self::getPieceAt($gameid, $i) == ":o:") {
if (self::getPieceAt($gameid, $i) == ':x:' || self::getPieceAt($gameid, $i) == ':o:') {
return false;
} else {
self::$bot->tictactoe[$gameid]['board'][intval(($i - 1) / 3)][($i - 1) % 3] = $piece;
return true;
}
}
}

View File

@ -1,15 +1,12 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use BenBot\Commands\Cities;
use Carbon\Carbon;
final class Time
{
private static $bot;
public static function register(&$that)
@ -17,52 +14,50 @@ final class Time
self::$bot = $that;
$timeCmd = self::$bot->registerCommand('time', [__CLASS__, 'getUserTime'], [
'description' => 'looks up times in different time zones. you can save a preferred city.',
'usage' => '[@user]',
'description' => 'looks up times in different time zones. you can save a preferred city.',
'usage' => '[@user]',
'registerHelp' => true,
]);
$timeCmd->registerSubCommand('save', ['BenBot\Commands\Cities','saveCity'], [
$timeCmd->registerSubCommand('save', ['BenBot\Commands\Cities', 'saveCity'], [
'description' => 'save a city for use with time and weather.',
'usage' => '<city>',
'usage' => '<city>',
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function getUserTime($msg, $args)
{
$id = Utils::getUserIDFromMsg($msg);
if (count($args) <= 1 && $args[0] == "") {
if (count($args) <= 1 && $args[0] == '') {
// look up the user's time
if (isset(self::$bot->cities[$id])) {
$city = self::$bot->cities[$id];
return self::sayTime($city);
} else {
return self::sayTime([
'timezone' => 'America/Detroit',
'city' => 'Eastern Time (USA)'
]) . "\n you can set a preferred city with `;time save <city>`";
'city' => 'Eastern Time (USA)',
])."\n you can set a preferred city with `;time save <city>`";
}
} else {
if (count($msg->mentions) > 0) {
foreach ($msg->mentions as $mention) {
if (isset(self::$bot->cities[$mention->id])) {
$city = self::$bot->cities[$mention->id];
return self::sayTime($city);
} else {
return "No city found for {$mention}.\nset a preferred city with `;time save <city> <@user>`";
}
}
} else {
$msg->channel->broadcastTyping();
$api_key = getenv('OWM_API_KEY');
$query = rawurlencode(implode(" ", $args));
$query = rawurlencode(implode(' ', $args));
$url = "http://api.openweathermap.org/data/2.5/weather?q={$query}&APPID=$api_key&units=metric";
self::$bot->http->get($url)->then(function ($weatherjson) use ($msg) {
@ -72,7 +67,7 @@ final class Time
self::$bot->http->get($geonamesurl)->then(function ($json) use ($msg, $weatherjson) {
Utils::send($msg, self::sayTime([
'timezone' => $json->timezoneId,
'city' => $weatherjson->name
'city' => $weatherjson->name,
]));
});
});
@ -80,20 +75,18 @@ final class Time
}
}
public static function sayTime($city)
{
$time = Carbon::now($city['timezone']);
return "It's " . $time->format('g:i A \o\n l F j, Y') . " in {$city["city"]}. " . self::clockEmojiForTime($time);
}
return "It's ".$time->format('g:i A \o\n l F j, Y')." in {$city['city']}. ".self::clockEmojiForTime($time);
}
public static function clockEmojiForTime(Carbon $emojitime)
{
$hour = $emojitime->hour % 12;
$minute = $emojitime->minute >= 30 ? "30" : "";
$minute = $emojitime->minute >= 30 ? '30' : '';
return ":clock$hour$minute:";
}
}
}

View File

@ -1,16 +1,13 @@
<?php
namespace BenBot\Commands;
use BenBot\Utils;
use BenBot\Cities;
use Discord\Parts\Embed\Embed;
use Carbon\Carbon;
use Discord\Parts\Embed\Embed;
final class Weather
{
private static $bot;
public static function register(&$that)
@ -18,61 +15,58 @@ final class Weather
self::$bot = $that;
$weather = self::$bot->registerCommand('weather', [__CLASS__, 'weather'], [
'description' => 'get current weather',
'usage' => '[@user|city search]',
'description' => 'get current weather',
'usage' => '[@user|city search]',
'registerHelp' => true,
]);
$weather->registerSubCommand('save', ['BenBot\Commands\Cities', 'saveCity'], [
$weather->registerSubCommand('save', ['BenBot\Commands\Cities', 'saveCity'], [
'description' => "saves a city for a user (or yourself if you don't mention anyone)",
'usage' => '<city search> [@user]',
'usage' => '<city search> [@user]',
]);
echo __CLASS__ . " registered", PHP_EOL;
echo __CLASS__.' registered', PHP_EOL;
}
public static function weather($msg, $args)
{
$id = Utils::getUserIDFromMsg($msg);
$api_key = getenv('OWM_API_KEY');
$url = "http://api.openweathermap.org/data/2.5/weather?APPID=$api_key&units=metric&";
if (count($args) <= 1 && $args[0] == "") {
if (count($args) <= 1 && $args[0] == '') {
echo "looking up weather for {$msg->author} $id";
if (isset(self::$bot->cities[$id])) {
$city = self::$bot->cities[$id];
$url .= "id={$city["id"]}";
$url .= "id={$city['id']}";
self::$bot->http->get($url)->then(function ($result) use ($msg, $city) {
Utils::send($msg, "", self::formatWeatherJson($result, $city["timezone"]));
Utils::send($msg, '', self::formatWeatherJson($result, $city['timezone']));
});
} else {
return "you can set your city with `;weather save <city>`";
return 'you can set your city with `;weather save <city>`';
}
} else {
if (count($msg->mentions) > 0) {
foreach ($msg->mentions as $mention) {
if (isset(self::$bot->cities[$mention->id])) {
$city = self::$bot->cities[$mention->id];
$url .= "id={$city["id"]}";
$url .= "id={$city['id']}";
self::$bot->http->get($url)->then(function ($result) use ($msg, $city) {
Utils::send($msg, "", self::formatWeatherJson($result, $city["timezone"]));
Utils::send($msg, '', self::formatWeatherJson($result, $city['timezone']));
});
} else {
return "no city saved for $mention.\nset a preferred city with `;weather save <city> $mention`";
}
}
} else {
$query = rawurlencode(implode(" ", $args));
$query = rawurlencode(implode(' ', $args));
$url .= "q=$query";
self::$bot->http->get($url)->then(function ($result) use ($msg) {
Utils::send($msg, "", self::formatWeatherJson($result));
Utils::send($msg, '', self::formatWeatherJson($result));
});
}
}
}
////////////////////////////////////////////////////
// util fns
////////////////////////////////////////////////////
@ -81,55 +75,35 @@ final class Weather
return $celsius * 9 / 5 + 32;
}
public static function fahrenheitToCelsius($fahrenheit)
{
return $fahrenheit * 5 / 9 + 32;
}
public static function formatWeatherJson($json, $timezone = null)
{
return self::$bot->factory(Embed::class, [
'title' => "Weather in {$json->name}, {$json->sys->country}",
'title' => "Weather in {$json->name}, {$json->sys->country}",
'thumbnail' => ['url' => "http://openweathermap.org/img/w/{$json->weather[0]->icon}.png"],
'fields' => [
['name' => 'Current temperature'
, 'value' => "{$json->main->temp}°C (".self::celsiusToFahrenheit($json->main->temp)."°F)"
, 'inline' => true
'fields' => [
['name' => 'Current temperature', 'value' => "{$json->main->temp}°C (".self::celsiusToFahrenheit($json->main->temp).'°F)', 'inline' => true,
],
['name' => 'Low/High Forecasted Temp'
, 'value' => "{$json->main->temp_min}/{$json->main->temp_max}°C " . self::celsiusToFahrenheit($json->main->temp_min) . "/" . self::celsiusToFahrenheit($json->main->temp_max) . "°F"
, 'inline' => true
['name' => 'Low/High Forecasted Temp', 'value' => "{$json->main->temp_min}/{$json->main->temp_max}°C ".self::celsiusToFahrenheit($json->main->temp_min).'/'.self::celsiusToFahrenheit($json->main->temp_max).'°F', 'inline' => true,
],
['name' => 'Current conditions'
, 'value' => $json->weather[0]->description
, 'inline' => true
['name' => 'Current conditions', 'value' => $json->weather[0]->description, 'inline' => true,
],
['name' => 'Atmospheric Pressure'
, 'value' => "{$json->main->pressure} hPa"
, 'inline' => true
['name' => 'Atmospheric Pressure', 'value' => "{$json->main->pressure} hPa", 'inline' => true,
],
['name' => 'Humidity'
, 'value' => "{$json->main->humidity} %"
, 'inline' => true
['name' => 'Humidity', 'value' => "{$json->main->humidity} %", 'inline' => true,
],
['name' => 'Wind'
, 'value' => "{$json->wind->speed} meters/second, {$json->wind->deg}°"
, 'inline' => true
['name' => 'Wind', 'value' => "{$json->wind->speed} meters/second, {$json->wind->deg}°", 'inline' => true,
],
['name' => 'Sunrise'
, 'value' => Carbon::createFromTimestamp($json->sys->sunrise, $timezone)->toTimeString()
, 'inline' => true
['name' => 'Sunrise', 'value' => Carbon::createFromTimestamp($json->sys->sunrise, $timezone)->toTimeString(), 'inline' => true,
],
['name' => 'Sunset'
, 'value' => Carbon::createFromTimestamp($json->sys->sunset, $timezone)->toTimeString()
, 'inline' => true
['name' => 'Sunset', 'value' => Carbon::createFromTimestamp($json->sys->sunset, $timezone)->toTimeString(), 'inline' => true,
],
],
'timestamp' => null,
]);
}
}

View File

@ -1,27 +1,28 @@
<?php
namespace BenBot;
final class EmbedColors
{
const DEFAULT = 0;
const AQUA = 1752220;
const GREEN = 3066993;
const BLUE = 3447003;
const PURPLE = 10181046;
const GOLD = 15844367;
const ORANGE = 15105570;
const RED = 15158332;
const GREY = 9807270;
const DARKER_GREY = 8359053;
const NAVY = 3426654;
const DARK_AQUA = 1146986;
const DARK_GREEN = 2067276;
const DARK_BLUE = 2123412;
const DARK_PURPLE = 7419530;
const DARK_GOLD = 12745742;
const DARK_ORANGE = 11027200;
const DARK_RED = 10038562;
const DARK_GREY = 9936031;
const LIGHT_GREY = 12370112;
const DARK_NAVY = 2899536;
}
<?php
namespace BenBot;
final class EmbedColors
{
const DEFAULT = 0;
const AQUA = 1752220;
const GREEN = 3066993;
const BLUE = 3447003;
const PURPLE = 10181046;
const GOLD = 15844367;
const ORANGE = 15105570;
const RED = 15158332;
const GREY = 9807270;
const DARKER_GREY = 8359053;
const NAVY = 3426654;
const DARK_AQUA = 1146986;
const DARK_GREEN = 2067276;
const DARK_BLUE = 2123412;
const DARK_PURPLE = 7419530;
const DARK_GOLD = 12745742;
const DARK_ORANGE = 11027200;
const DARK_RED = 10038562;
const DARK_GREY = 9936031;
const LIGHT_GREY = 12370112;
const DARK_NAVY = 2899536;
}

View File

@ -1,12 +1,11 @@
<?php
namespace BenBot;
use BenBot\Utils;
use function Stringy\create as s;
final class FontConverter
{
public static $fonts;
public static function init()
@ -15,103 +14,104 @@ final class FontConverter
'full' => [
'lowers' => s(''),
'uppers' => s(''),
'nums' => s(''),
'nums' => s(''),
],
'mono' => [
'lowers' => s('𝚊𝚋𝚌𝚍𝚎𝚏𝚐𝚑𝚒𝚓𝚔𝚕𝚖𝚗𝚘𝚙𝚚𝚛𝚜𝚝𝚞𝚟𝚠𝚡𝚢𝚣'),
'uppers' => s('𝙰𝙱𝙲𝙳𝙴𝙵𝙶𝙷𝙸𝙹𝙺𝙻𝙼𝙽𝙾𝙿𝚀𝚁𝚂𝚃𝚄𝚅𝚆𝚇𝚈𝚉'),
'nums' => s('𝟶𝟷𝟸𝟹𝟺𝟻𝟼𝟽𝟾𝟿'),
'nums' => s('𝟶𝟷𝟸𝟹𝟺𝟻𝟼𝟽𝟾𝟿'),
],
'flipped' => [
'lowers' => s('ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz'),
'uppers' => s('ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇn𐌡ʍxʎz'),
'nums' => s('0123456789'),
'nums' => s('0123456789'),
],
'reversed' => [
'lowers' => s('AdↄbɘꟻgHijklmᴎoqpᴙꙅTUvwxYz'),
'uppers' => s('AdↃbƎꟻGHIJK⅃MᴎOꟼpᴙTUVWXYZ'),
'nums' => s('0߁23456789'),
'nums' => s('0߁23456789'),
],
'cyrillic' => [
'lowers' => s('αв¢∂єƒﻭнιנкℓмησρ۹яѕтυνωχуչ'),
'uppers' => s('αв¢∂єƒﻭнιנкℓмησρ۹яѕтυνωχуչ'),
'nums' => s('0123456789'),
'nums' => s('0123456789'),
],
'slashed' => [
'lowers' => s('Ⱥƀȼđɇfǥħɨɉꝁłmnøᵽꝗɍsŧᵾvwxɏƶ'),
'uppers' => s('ȺɃȻĐɆFǤĦƗɈꝀŁMNØⱣꝖɌSŦᵾVWXɎƵ'),
'nums' => s('01ƻ3456789'),
'nums' => s('01ƻ3456789'),
],
'script' => [
'lowers' => s('𝓪𝓫𝓬𝓭𝓮𝓯𝓰𝓱𝓲𝓳𝓴𝓵𝓶𝓷𝓸𝓹𝓺𝓻𝓼𝓽𝓾𝓿𝔀𝔁𝔂𝔃'),
'uppers' => s('𝓐𝓑𝓒𝓓𝓔𝓕𝓖𝓗𝓘𝓙𝓚𝓛𝓜𝓝𝓞𝓟𝓠𝓡𝓢𝓣𝓤𝓥𝓦𝓧𝓨𝓩'),
'nums' => s('𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗'),
'nums' => s('𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗'),
],
'gothic' => [
'lowers' => s('𝖆𝖇𝖈𝖉𝖊𝖋𝖌𝖍𝖎𝖏𝖐𝖑𝖒𝖓𝖔𝖕𝖖𝖗𝖘𝖙𝖚𝖛𝖜𝖝𝖞𝖟'),
'uppers' => s('𝕬𝕭𝕮𝕯𝕰𝕱𝕲𝕳𝕴𝕵𝕶𝕷𝕸𝕹𝕺𝕻𝕼𝕽𝕾𝕿𝖀𝖁𝖂𝖃𝖄𝖅'),
'nums' => s('𝟘𝟙𝟚𝟛𝟜𝟝𝟞𝟟𝟠𝟡'),
'nums' => s('𝟘𝟙𝟚𝟛𝟜𝟝𝟞𝟟𝟠𝟡'),
],
'vaporwave' => [
'lowers' => s(''),
'uppers' => s(''),
'nums' => s(''),
'nums' => s(''),
],
];
}
public static function blockText($text) {
$ret = "";
public static function blockText($text)
{
$ret = '';
foreach (s($text)->toLowerCase() as $char) {
if (ctype_alpha($char)) $ret .= ":regional_indicator_" . $char . ": ";
else if (ctype_digit($char)) {
if (ctype_alpha($char)) {
$ret .= ':regional_indicator_'.$char.': ';
} elseif (ctype_digit($char)) {
switch ($char) {
case 0: $ret .= ":zero: "; break;
case 1: $ret .= ":one: "; break;
case 2: $ret .= ":two: "; break;
case 3: $ret .= ":three: "; break;
case 4: $ret .= ":four: "; break;
case 5: $ret .= ":five: "; break;
case 6: $ret .= ":six: "; break;
case 7: $ret .= ":seven: "; break;
case 8: $ret .= ":eight: "; break;
case 9: $ret .= ":nine: "; break;
case 0: $ret .= ':zero: '; break;
case 1: $ret .= ':one: '; break;
case 2: $ret .= ':two: '; break;
case 3: $ret .= ':three: '; break;
case 4: $ret .= ':four: '; break;
case 5: $ret .= ':five: '; break;
case 6: $ret .= ':six: '; break;
case 7: $ret .= ':seven: '; break;
case 8: $ret .= ':eight: '; break;
case 9: $ret .= ':nine: '; break;
}
} elseif ($char == ' ') {
$ret .= ' ';
}
else if ($char == " ") $ret .= " ";
}
return $ret;
}
public static function __callStatic($name, $args)
{
if (!isset(self::$fonts[$name])) {
$ret = "sorry that font doesn't exist. try these fonts:\n";
$ret .= implode(", ", array_keys(self::$fonts));
$ret .= implode(', ', array_keys(self::$fonts));
return $ret;
}
$ret = "";
$ret = '';
foreach (s($args[0]) as $char) {
$ord = ord($char);
if ($ord >= ord('0') && $ord <= ord('9')) {
$ret .= self::$fonts[$name]["nums"][$ord - ord('0')];
$ret .= self::$fonts[$name]['nums'][$ord - ord('0')];
} elseif ($ord >= ord('a') && $ord <= ord('z')) {
$ret .= self::$fonts[$name]["lowers"][$ord - ord('a')];
$ret .= self::$fonts[$name]['lowers'][$ord - ord('a')];
} elseif ($ord >= ord('A') && $ord <= ord('Z')) {
$ret .= self::$fonts[$name]["uppers"][$ord - ord('A')];
} elseif ($char == " ") {
$ret .= " ";
$ret .= self::$fonts[$name]['uppers'][$ord - ord('A')];
} elseif ($char == ' ') {
$ret .= ' ';
} else {
continue;
}
$ret .= " ";
$ret .= ' ';
}
return $ret;
}
}
}

View File

@ -1,39 +1,39 @@
<?php
namespace BenBot;
final class PersistentArray implements \ArrayAccess, \Iterator
{
protected $data;
protected $filepath;
public function __construct($filepath)
{
$this->filepath = $filepath;
if (!is_file($this->filepath)) throw new Exception("Invalid filepath");
if (!is_file($this->filepath)) {
throw new Exception('Invalid filepath');
}
$rawfiledata = file_get_contents($this->filepath);
if (strlen($rawfiledata) > 3) {
$this->data = msgpack_unpack($rawfiledata);
}
}
public function __debugInfo()
{
return print_r($this->data, true);
}
public function __call($func, $argv)
{
if (!is_callable($func) || substr($func, 0, 6) !== 'array_') {
throw new \BadMethodCallException(__CLASS__ . "->$func");
throw new \BadMethodCallException(__CLASS__."->$func");
}
$copy = $this->data;
return call_user_func_array($func, array_merge([$copy], $argv));
}
// array access methods
public function offsetGet($offset)
{
@ -66,30 +66,29 @@ final class PersistentArray implements \ArrayAccess, \Iterator
{
return reset($this->data);
}
public function current()
{
return current($this->data);
}
public function key()
{
return key($this->data);
}
public function next()
{
return next($this->data);
}
public function valid()
{
return key($this->data) !== null;
}
private function save()
{
file_put_contents($this->filepath, msgpack_pack($this->data));
}
}

View File

@ -1,27 +1,23 @@
<?php
namespace BenBot;
use Carbon\Carbon;
use Discord\Parts\Embed\Embed;
use React\Promise\Deferred;
final class Utils
{
private static $bot;
public static function init(&$that)
{
self::$bot = $that;
echo PHP_EOL, "Utils initialized.", PHP_EOL;
echo PHP_EOL, 'Utils initialized.', PHP_EOL;
}
public static function send($msg, $txt, $embed = null)
{
return $msg->channel->sendMessage($txt, false, $embed)
->otherwise(function($e) use ($msg) {
->otherwise(function ($e) use ($msg) {
echo $e->getMessage(), PHP_EOL;
echo $e->getTraceAsString(), PHP_EOL;
$msg->reply("sry, an error occurred. check with <@193011352275648514>.\n```{$e->getMessage()}```");
@ -29,11 +25,10 @@ final class Utils
});
}
public static function sendFile($msg, $filepath, $filename, $txt)
{
return $msg->channel->sendFile($filepath, $filename, $txt)
->otherwise(function($e) use ($msg) {
->otherwise(function ($e) use ($msg) {
echo $e->getMessage(), PHP_EOL;
echo $e->getTraceAsString(), PHP_EOL;
$msg->reply("sry, an error occurred. check with <@193011352275648514>.\n```{$e->getMessage()}```");
@ -41,29 +36,25 @@ final class Utils
});
}
public static function isDM($msg)
{
return $msg->channel->is_private;
}
public static function getUserIDFromMsg($msg)
{
return self::isDM($msg) ? $msg->author->id : $msg->author->user->id;
}
public static function timestampFromSnowflake ($snowflake)
public static function timestampFromSnowflake($snowflake)
{
return (($snowflake / 4194304) + 1420070400000) / 1000;
}
public static function ping($msg)
{
if (is_null(self::$bot)) {
throw new \Exception("Utils class not initialized");
throw new \Exception('Utils class not initialized');
}
$channel_id = self::$bot->devbot ? '297082205048668160' : '289611811094003715';
@ -74,7 +65,6 @@ final class Utils
->sendMessage("<@193011352275648514>, $msg");
}
public static function secondsConvert($uptime)
{
// Method here heavily based on freebsd's uptime source
@ -88,7 +78,7 @@ final class Utils
$minutes = floor($uptime / 60);
$seconds = floor($uptime % 60);
// Send out formatted string
$return = array();
$return = [];
if ($years > 0) {
$return[] = $years.' '.($years > 1 ? 'years' : 'year');
}
@ -104,10 +94,10 @@ final class Utils
if ($seconds > 0) {
$return[] = $seconds.(date('m/d') == '06/03' ? ' sex' : ' seconds');
}
return implode(', ', $return);
}
public static function convertMemoryUsage($system = false)
{
$mem_usage = memory_get_usage($system);
@ -115,13 +105,12 @@ final class Utils
if ($mem_usage < 1024) {
return "$mem_usage bytes";
} elseif ($mem_usage < 1048576) {
return round($mem_usage / 1024, 2) . " kilobytes";
return round($mem_usage / 1024, 2).' kilobytes';
} else {
return round($mem_usage / 1048576, 2) . " megabytes";
return round($mem_usage / 1048576, 2).' megabytes';
}
}
public static function deleteMessage($msg)
{
$deferred = new Deferred();
@ -138,7 +127,6 @@ final class Utils
return $deferred->promise();
}
public static function editMessage($msg, $text)
{
$deferred = new Deferred();
@ -146,7 +134,7 @@ final class Utils
self::$bot->http->patch(
"channels/{$msg->channel->id}/messages/{$msg->id}",
[
'content' => $text
'content' => $text,
]
)->then(
function ($response) use ($deferred, $msg) {
@ -155,10 +143,10 @@ final class Utils
},
\React\Partial\bind_right($msg->reject, $deferred)
);
return $deferred->promise();
}
public static function arrayFlatten($array)
{
if (!is_array($array)) {
@ -172,7 +160,7 @@ final class Utils
$result[$key] = $val;
}
}
return $result;
}
}

View File

@ -1,17 +1,18 @@
<?php
namespace BenBot\Tests;
use PHPUnit\Framework\TestCase;
/**
* @covers BenBot\Commands\AsciiArt
*/
final class AsciiArtTest extends TestCase
{
public function testTrueisTrue(): void
{
$true = true;
$this->assertTrue($true);
$this->assertEquals($true, true);
}
}
<?php
namespace BenBot\Tests;
use PHPUnit\Framework\TestCase;
/**
* @covers BenBot\Commands\AsciiArt
*/
final class AsciiArtTest extends TestCase
{
public function testTrueisTrue(): void
{
$true = true;
$this->assertTrue($true);
$this->assertEquals($true, true);
}
}