2016-04-19 30 views
0

我正在開發一個簡單的irc bot在php中。 上面的一半是IRC bot從頭開始的一個實現(連接套接字...等) 我想添加的功能是「計劃通知」 當具體時間到了時,會發送一些消息。無法在PHP中發送預定的消息IRC-BOT

例如, 時間Tue Apr 19 16:32到來時,會發送一些通知消息。

因此,如果你設置了類似(date("D") == "Tue" && date("H") == 15), 的東西,這應該會持續發送消息,直到16:00到來。

但是,只要bot進入通道,它就會停止發送消息。

我認爲這是由套接字連接引起的,但我並不知道這個線索。

<?php 

// Time zone setting 
date_default_timezone_set('Asia/Tokyo'); 

// Our bot's configuration parameters. 
$server = '192.168.59.103'; 
$port = 6667; 
$nickname = 'Bot'; 
$ident = 'Bot'; 
$gecos = 'Bot v1.0'; 
$channel = '#bot-test'; 


// Connect to the network 
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 
$error = socket_connect($socket, $server, $port); 

// Add some error handling in case connection was not successful. 
if ($socket === false){ 
    $errorCode = socket_last_error(); 
    $errorString = socket_strerror($errorCode); 
    die("Error $errorCode: $errorString \n"); 
} 

// Send the registration info. 
socket_write($socket, "NICK $nickname\r\n"); 
socket_write($socket, "USER $ident * 8 :$gecos\r\n"); 

// Finally, loop until the socket closes. 
while (is_resource($socket)) { 

    // Fetch the data from the socket 
    $data = trim(socket_read($socket, 1024, PHP_NORMAL_READ)); 
    echo $data . "\n"; 

    // Splitting the data into chunks 
    $d = explode(' ', $data); 

    // Padding the array avoids ugly undefined offset erros. 
    $d = array_pad ($d, 10, ''); 

    // Our ping handler. 
    // Ping: $servername. 
    if ($d[0] === 'PING') { 
     socket_write($socket, 'PONG ' . $d[1] . "\r\n"); 
    } 

    if ($d[1] === '376' || $d[1] === '422') { 
     socket_write($socket, 'JOIN ' . $channel . "\r\n"); 
    } 

    // Bot collections 

    // "$d" parameter format 
    // [0]      [1]  [2]   [3] 
    // :[email protected] PRIVMSG #bot-test :@arukas. 

    // Scheduler bot 
    if (date("D") == "Tue" && date("H") == 15) { 
     $saying = "REALLY SLEEPY!!"; 
     socket_write($socket, 'PRIVMSG ' . "CIRC1989" . " :$saying\r\n"); 
    } 

} 

回答

1

你的代碼在讀/寫邏輯部分被破壞 - 你現在的代碼總是假設讀了一些東西(會睡覺直到發生什麼事),然後寫一些東西。您需要添加緩衝區並使用輪詢/選擇。我認爲PHP至少是其中之一。

僞代碼應工作:

readbuffer[] 
writebuffer[] 

while (no_error) 
{ 
    if (writebuffer not empty) 
    { 
    select(socket, want_to_write, want_to_read, timeout_until_next_event); 
    } else { 
    select(socket, 0, want_to_read, timeout_until_next_event); 
    } 
    if (select return can write) 
    { 
    retval = write(socket, writebuffer); 
    if (no_error) 
     writebuffer.removefromstart(retval); 
    } 
    if (select return can read) 
    { 
    retval = read(socket, readbuffer + offset already filled); 
    if (no_error) 
    { 
     parse as much as possible in readbuffer, removing data as parsed; 
    } 
    } 
    check_timers(); 
} 
+0

注意timeout_until_next_event要高,你真的想擺脫(儘可能多秒爲一個時鐘嘀噠爲您安排的事件,真的)。在while循環中循環太長,選擇超時時間過低可能會導致CPU使用率過高。 – braindigitalis