【发布时间】:2012-02-21 18:21:33
【问题描述】:
我正在用 PHP 构建一个 IRC 机器人。它给我的错误是第 45 行和第 50 行的错误“未定义的偏移量:4 in /****///Grue.php on line 50”
以下是这些行:
第 45 行:$command = str_replace(array(chr(10), chr(13)), '', $this -> ex[3]);
第 50 行:switch($this -> ex[4]) {
这是他剩下的代码:
<?php
//So the bot doesn't stop.
set_time_limit(0);
ini_set('display_errors', 'on');
//Sample connection.
$config = array('server' => 'irc.foonetic.net', 'port' => 6667, 'channel' => '#lingubender', 'name' => 'KiBot', 'nick' => 'Grue', 'pass' => '',);
class Grue {
var $socket; // TCP/IP Connection
var $ex = array(); // Messages
function __construct($config)
{
$this -> socket = fsockopen($config['server'], $config['port']);
$this -> login($config);
$this -> main($config);
}
/* Log into server
@param array
*/
function login($config)
{
$this -> write_data('USER', $config['nick'].' :'.$config['name']);
$this -> write_data('NICK', $config['nick']);
$this -> enter_channel($config['channel']);
}
//* Grabs/displays data
function main($config)
{
$data = fgets($this -> socket, 256);
echo nl2br($data);
flush();
$this -> ex = explode(' ', $data);
if ($this -> ex[0] == 'PING') {
write_data('PONG', $this -> ex[1]);
}
$command = str_replace(array(chr(10), chr(13)), '', $this -> ex[3]);
strtolower($command);
if ($command == ':grue' || ':gu') {
switch($this -> ex[4]) {
case 'join':
enter_channel($this -> ex[5]);
break;
case 'part':
$this -> write_data('PART'.$this -> ex[5].' :', $this -> ex[6]);
break;
case 'repeat':
$message = "";
for ($i = 5; $i <= (count($this -> ex)); $i++) {
$message .= $this -> ex[$i]." ";
}
$this -> write_data('PRIVMSG '.$this -> ex[4].' :', $message);
break;
case 'restart':
echo "<meta http-equiv=\"refresh\" content=\"5\">";
exit;
case 'shutdown':
$this -> write_data('QUIT', $this -> ex[5]);
exit;
}
}
$this -> main($config);
}
function write_data($cmd, $msg = null) {
if ($msg == null) {
fputs($this -> socket, $cmd."\r\n");
echo '<strong>'.$cmd.'</strong><br>';
} else {
echo '<strong>'.$cmd.' '.$msg.'</strong><br>';
}
} function enter_channel($channel) {
if (is_array($channel)) {
foreach ($channel as $chan) {
$this -> write_data('JOIN', $chan);
}
} else {
$this -> write_data('JOIN', $channel);
}
}
}
$bot = new Grue($config);
?>
我已经检查了所有的括号和括号;我能想到的一切都没有用。如果它有帮助,当我运行它时,它会播放上述错误(45 和 50)大约 60 次。
【问题讨论】:
-
这意味着在它运行的上下文中,
$this->ex[4](或 3)不存在,您试图访问一个不存在的数组元素,因此出现错误。您应该打印一个调试堆栈 (print_r(debug_backtrace())) 并查看它的结果。 -
另外,我有一个工作的 PHP IRC 机器人,它比你的要复杂得多(每个用户都是一个对象,每个频道都是一个对象,良好的动态用户跟踪和频道监控,连接工作等),如果你愿意,我可以与你分享。