hyperbot/hypervoice.php
2018-09-15 23:48:52 -03:00

123 lines
2.5 KiB
PHP
Executable File

<?php
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
set_time_limit(0);
const NEW_LINE = "\n";
$isDaemon = (bool)($argv[1] ?? false);
// ---
function startsWith($haystack, $needle) {
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
function contains($haystack, $needle) {
if (strpos($haystack, $needle) > -1) {
return true;
}
else {
return false;
}
}
// ---
function funcSendCommand($cmd) {
sleep(2);
fputs($GLOBALS['irc'], $cmd . NEW_LINE);
funcOutput($cmd, 'snd');
}
function funcExtractNick ($fullUsername) {
return preg_replace("/\:(.*)\!(.*)/i", "$1", $fullUsername);
}
function funcOutput($output, $mode) {
if ($mode != 'err' && $GLOBALS['isDaemon']) {
return;
}
switch ($mode) {
case 'snd':
print('Snd> ' . $output . NEW_LINE);
break;
case 'rcv':
print('Rvc> ' . $output);
break;
case 'msg':
print('Msg> ' . $output . NEW_LINE);
break;
case 'err':
print('Err> ' . $output . NEW_LINE);
break;
default:
return;
}
}
// ---
$ircServer = 'chat.freenode.net';
$ircPort = '6667';
$botNick = 'hypervoice';
$botChannel = '#hyperbola';
$arrayConnectCommands = array(
"USER $botNick $botNick $botNick $botNick :$botNick",
"NICK $botNick",
"PONG",
"CAP REQ :account-notify extended-join",
"NICKSERV identify nick password",
"JOIN $botChannel"
);
$irc = fsockopen($ircServer, $ircPort);
if (!$irc) {
funcOutput('Something went wrong with the socket', 'err');
exit(1);
}
foreach ($arrayConnectCommands as $_value) {
funcSendCommand($_value);
}
// ---
while(1) {
while ($raw = fgets($irc)) {
if (startsWith($raw, 'PING')) {
$lastPing = time();
funcOutput($raw, 'rcv');
funcSendCommand('PONG');
}
if (startsWith($raw, 'ERROR')) {
funcOutput($raw, 'rcv');
exit(1);
}
if (startsWith($raw, ':')) {
$rawEx = explode(' ', $raw);
funcOutput($raw, 'rcv');
switch($rawEx[1]) {
case 'PONG':
$lastPing = time();
break;
case 'JOIN':
if (!contains($rawEx[0], $botNick) && $rawEx[3] != '*') {
funcSendCommand("MODE $botChannel +v " . funcExtractNick($rawEx[0]));
}
break;
case 'ACCOUNT':
funcSendCommand("MODE $botChannel +v " . funcExtractNick($rawEx[0]));
break;
}
}
}
}
?>