Hi, I was looking for a script that would display how many users are in a chat, also OPs. For example "There are currently 12 users and 1 op chatting.

I figure Id probly have to make a cron so the script would connect to the channel every so often to figure out how many users are in there and thats where I got stuck. I would I figure out how to get the number of users in a channel?

I did alot of searching and the closest thing I found was this.

Reads Channel-Listing of an IRC Server and saves it into Database. Listing will be refreshed every x-minutes. (create_table function is just to create an example table for saving data.)
made by:  favoo
<?php
    /**
      *    server configuration
      */
    define ('IRC_SERVER', 'irc.favo.tv');
    define ('IRC_PORT', 6667);
    define ('IRC_REFRESH', 30);        // minutes

/**
  *    DB Tables
  */
define ('T_CONFIG', 'irc_config');
define ('T_CHANNEL', 'irc_channel');

/**
  *    connect to database
  */
mysql_connect ("localhost", "login", "password");
mysql_select_db ("database");

/**
  *    uncomment to create tables on first run
  */
//    create_tables ();

/**
  *    get channels and output
  */
$arr_channels        =    db_get_channels ();
foreach ($arr_channels as $arr_channel)
{
    echo join ("<br>n", $arr_channel);
    echo "-----------------<br>n";
}


/**
  *    db_get_channels
  *    - return list of all channels either by asking database or IRC Server
  */
function db_get_channels ()
{
    /**
      *    get last update timestamp
      */
    $raw            =    mysql_query ("SELECT UNIX_TIMESTAMP(lastupdate) FROM ".T_CONFIG);
    list ($ts_lastupdate)    =    mysql_fetch_row ($raw);
    mysql_free_result ($raw);

    /**
      *    too old?
      */
    if ($ts_lastupdate < (time() - (60*IRC_REFRESH)))
    {
        /**
          *    block parallel processing by updating lastupdate to current time
          */
        mysql_query ("REPLACE INTO ".T_CONFIG." (lastupdate) VALUES (NOW())");

        /**
          *    get channels
          */
        if (($arr_channels = irc_get_channels ()) == false)
        {
            /**
              *    failed, return with db-source
              */
            return db_get_channels ();
        }

        /**
          *    clear existing list
          */
        mysql_query ("TRUNCATE ".T_CHANNEL);


        /**
          *    insert channels into database
          */
        reset ($arr_channels);
        $arr_insert[]        =    array ();
        foreach ($arr_channels as $str_channel => $arr_data)
        {
            $arr_insert[]        =    "('".mysql_escape_string($str_channel)."', ".intval($arr_data[0]).", '".mysql_escape_string ($arr_data[1])."')";

            if (sizeof ($arr_insert) > 25)
            {
                 mysql_query ("INSERT INTO ".T_CHANNEL." (channel, users, topic) VALUES ".join(',', $arr_insert));
                unset ($arr_insert);
            }

            $arr_return[]        =    array ($str_channel, $arr_data[0], $arr_data[1]);
        }
        unset ($arr_channels);

        /**
          *    some entries left?
          */
        if (sizeof ($arr_insert))
        {
            mysql_query ("INSERT INTO ".T_CHANNEL." (channel, users, topic) VALUES ".join(',', $arr_insert));
        }
        unset ($arr_insert);
    }
    /**
      *    get input from DB
      */
    else
    {
        $raw        =    mysql_query ("SELECT channel, users, topic FROM ".T_CHANNEL);
        while ($arr_return[] = mysql_fetch_assoc ($raw))
        { /* hi there :) */ }
        mysql_free_result ($raw);
    }

    /**
      *    return arary of channels
      *        [0]    =    #channel
      *        [1]    =    users
      *        [2]    =    topic
      */
    return $arr_return;
}
/**    <- end of db_get_channels () */


/**
  *    irc_get_channels
  *    - connects to IRC Server and returns a multidimensional array of all channels
  */
function irc_get_channels ()
{
    /**
      *    open socket to server
      */
    $hwnd_irc        =    fsockopen (IRC_SERVER, IRC_PORT);

    /**
      *    connection failed?
      */
    if (!$hwnd_irc)
        return false;

    /**
      *    use random nick & identification
      */
    $str_nick        =    chr(rand(65,90)).time().rand(1,10000);
    fputs ($hwnd_irc, "USER ".$str_nick." ".IRC_SERVER." ".IRC_SERVER." :Channelreaderrn");
    fputs ($hwnd_irc, "NICK ".$str_nick."rn");

    /**
      *    get data until we're finally connected & verified
      */
    $arr_channels        =    array ();
    while (!feof($hwnd_irc))
    {
        $str_line    =    fgets ($hwnd_irc, 1024);

        /**
          *    response to PING requests
          */
        if (substr($str_line,0,5) == 'PING ')
            fputs ($hwnd_irc, "PONG ".trim(array_pop(explode(':', $str_line)))."rn");

        /**
          *    switch between response ID's
          */
        $arr_line    =    explode(' ', $str_line);
        switch ($arr_line[1])
        {
            /**
              *    "End of Motd" (376)
              */
            case 376:
                /**
                  *    send LIST request
                  */
                fputs ($hwnd_irc, "LISTrn");
                break;

            /**
              *    channel list
              */
            case 322:
                /**
                  *    0 = sender
                  *    1 = ID
                  *    2 = target
                  *    3 = channels name
                  *    4 = users in channel
                  */
                $arr_channels[$arr_line[3]]    =    array ();
                $arr_channels[$arr_line[3]][0]    =    $arr_line[4];
                $arr_channels[$arr_line[3]][1]    =    trim (substr ($str_line, strpos($str_line, ':', 5)));
                break;

            /**
              *    End of List
              */
            case 323:
                fputs ($hwnd_irc, "QUITrn");
                break 2;
        }
    }
    fclose ($hwnd_irc);

    /**
      *    got no list?
      */
    if (!sizeof ($arr_channels))
        return false;

    /**
      *    return hash of all channels
      *        [#channel]
      *    with an array of users & topic
      *        [0]        =    users
      *        [1]        =    topic
      */
    return $arr_channels;
}
/**    <- end of irc_get_channels () */




/**
  *    create_tables
  *    - create table structure
  */
function create_tables ()
{
    $arr_query[]        =    "DROP TABLE IF EXISTS `irc_channel`";
    $arr_query[]        =    "CREATE TABLE `irc_channel` (
              `channel` varchar(32) NOT NULL default '',
              `users` smallint(5) unsigned NOT NULL default '0',
              `topic` varchar(255) NOT NULL default '',
              PRIMARY KEY  (`channel`)
            ) TYPE=MyISAM";

    $arr_query[]        =    "DROP TABLE IF EXISTS `irc_config`";
    $arr_query[]        =    "CREATE TABLE `irc_config` (
              `lastupdate` datetime NOT NULL default '0000-00-00 00:00:00'
            ) TYPE=MyISAM";

    foreach ($arr_query as $str_query)
        mysql_query ($str_query);

}
/**    <- end of create_tables () */
?>

Sorry if this is a long post but there was no way to shorten this without confusing you guys 🙁. Anyway How would I have that just grab the amount of users and ops in a specific channel. If finding the ops to hard then how would I just get the number of users?

Much thanks to whoever helps me.

    Well, since I feel like being nice tonight, I'm just trying to resolve old problems. So I'm going to figure out how to do this. I'll repost when I have it finished. 🙂

      Heh, I'm so stupid. I got this working the other day and never got around to posting it. Sorry... Give me a little bit to test it some more and I'll edit this post with the script. I'm on a new system (new box, new OS, the works), so it might be a while... Peace. 🆒

        I forgot to post back, I figured how to do this. One of my friends made up the log in sequence then had it do /names #channel and then just parse out the channel name and usernames and write how many users in a txt file.

        It would still be cool to see how you did it. Maby its done better then the way me and my friend did it.

          Okay, so I'll post it in case you want to see how I did it and in case anyone else wants this script. I made 2 scripts. One does it the easy way using the LIST command on the channel and taking the user list from there. The other does it the long way and JOINs the channel and parses the usernames. I also added a response for the VERSION and PING requests in case the server asks for it (although you're on for such a short time it's not that important).

          Take note: These scripts are HEAVILY COMMENTED! I don't actually comment that much, I just wanted to make everything unbelievably clear so that anyone interested can understand. All comments/critiquing will be accepted as these are not perfect. Also understand that because I wasn't planning on doing anything else with these, the requests and responses are all sent plainly. There are no functions made for notices, PMs, etc. I just used raw messages.

          KNOWN BUGS:
          Sometimes I connect to a server and it checks the hostname/ident, but never does anything past that. Any ideas?

          Finally, here's the one that uses LIST #channel for the user list. The number of ops cannot be attained this way.

          <?php
          
          /* CONFIGURATIONS! */
          $irc_server = 'irc.rizon.net';  // Server
          $irc_port = '6667';             // Port
          $irc_nick = 'mxRocksMySocks';   // Nick
          $irc_channel = '#anime-mx';     // Channel
          /* END CONFIGURATIONS! */
          
          $socket = fsockopen($irc_server,$irc_port);            // Connect to the server.
          fputs($socket,"USER SOCKS SOCKS SOCKS :SOCKS\r\n");    // Send the username.
          fputs($socket,"NICK $irc_nick \r\n");                  // Set our nick.
          fputs($socket,"LIST $irc_channel \r\n");               // List the provided channel.
          
          // $handle = fopen('log.txt',a);  // Log if you want.
          
          // Set initial value.
          $users = 0;
          
          // Receive the incoming data.
          while(1) {
              $sock_data = fgets($socket,1024);   // Get each line of data from the response.
              // fwrite($handle,"$sock_data\r\n");   // Write the log.
          
          // Get the information section of the desired responses.
          $sep = explode(':',$sock_data);  // Separate by colons.
          $info = $sep[1];  // After the first colon is the important information.
          $message = $sep[2];
          
          // Break down the response and get the id and who sent it.
          $info_sep = explode(' ',$info);  // Separate by spaces.
          $full_who = $info_sep[0];  // The person who sent it is the first item in the list.
          $id = $info_sep[1];  // The id is the second item in the list.
          $who_sep = explode('!',$full_who);  // Separate by exclamation points.
          $who = $who_sep[0];  // The nick of the person is the part before the exclamation point.
          
          // I saw some scripts checking for this, so...
          if ($who == 'PING') {
              fputs($socket,"PONG $message");
          }
          
          // PRIVMSG indicates someone is sending you a message.
          // We just need this to reply to the VERSION and PING requests.
          if ($id == 'PRIVMSG') {
              if (substr($message, 0, 8) == 'VERSION') {  // Reply to the version response.
              fputs($socket,"NOTICE $who :".chr(1)."VERSION getUsers v0.1b".chr(1)."\r\n");
              } elseif (strstr($message, 'PING') !== false) {  // Ping them back if needed.
                  fputs($socket,"NOTICE $who :$message");
              }
          }
          
          // 322 is the list response.
          // This should get the number of users on the provided channel.
          if ($id == '322') {
              $users = $info_sep[4];  // The number of users.
              // fclose($handle);  // Close the log.
              fclose($socket);  // Close the connection.
              break;  // End the loop.
          }
          
          // 323 is the end list response.
          // This is in case there is no 322 response (the channel doesn't exist, maybe?)
          if ($id == '323') {
              // fclose($handle);  // Close the log.
              fclose($socket);  // Close the connection.
              break;  // End the loop.
          }
          
          // 263 is the failed response.
          // Wait 2 seconds and retry.
          if ($id == '263') {
              sleep(2);  // Pause for 2 seconds.
              fputs($socket,"LIST $irc_channel \r\n");  // List the provided channel.
          }
          }
          
          // Display the results on the page.
          if ($users == '1') {
              echo "There is 1 user in $irc_channel.";
          } else {
              echo "There are $users users in $irc_channel.";
          }
          
          ?>
          

          Here is the other one which uses JOIN #channel and parses the user list looking for ops.

          <?php
          
          /* CONFIGURATIONS! */
          $irc_server = 'irc.rizon.net';  // Server
          $irc_port = '6667';             // Port
          $irc_nick = 'mxRocksMySocks';   // Nick
          $irc_channel = '#anime-mx';     // Channel
          $irc_op = '@';                  // The symbol that signifies an op (some servers change it)
          /* END CONFIGURATIONS! */
          
          $socket = fsockopen($irc_server,$irc_port);            // Connect to the server.
          fputs($socket,"USER SOCKS SOCKS SOCKS :SOCKS\r\n");    // Send the username.
          fputs($socket,"NICK $irc_nick \r\n");                  // Set our nick.
          fputs($socket,"JOIN $irc_channel \r\n");               // Join the provided channel.
          
          // $handle = fopen('log.txt',a);  // Log if you want.
          
          // Set initial count values.
          $op_count = 0;
          $total_count = 0;
          $user_count = 0;
          
          // Receive the incoming data.
          while(1) {
              $sock_data = fgets($socket,1024);   // Get each line of data from the response.
              // fwrite($handle,"$sock_data\r\n");   // Write the log.
          
          // Get the information section of the desired responses.
          $sep = explode(':',$sock_data);  // Separate by colons.
          $info = $sep[1];  // After the first colon is the important information.
          $message = $sep[2];
          
          // Break down the response and get the id and who sent it.
          $info_sep = explode(' ',$info);  // Separate by spaces.
          $full_who = $info_sep[0];  // The person who sent it is the first item in the list.
          $id = $info_sep[1];  // The id is the second item in the list.
          $who_sep = explode('!',$full_who);  // Separate by exclamation points.
          $who = $who_sep[0];  // The nick of the person is the part before the exclamation point.
          
          // I saw some scripts checking for this, so...
          if ($who == 'PING') {
              fputs($socket,"PONG $message");
          }
          
          // PRIVMSG indicates someone is sending you a message.
          // We just need this to reply to the VERSION and PING requests.
          if ($id == 'PRIVMSG') {
              if (substr($message, 0, 8) == 'VERSION') {  // Reply to the version response.
              fputs($socket,"NOTICE $who :".chr(1)."VERSION getUsers v0.1b".chr(1)."\r\n");
              } elseif (strstr($message, 'PING') !== false) {  // Ping them back if needed.
                  fputs($socket,"NOTICE $who :$message");
              }
          }
          
          // 366 is the end user list.
          // Close everything so we can display the results.
          if ($id == '366') {
              // fclose($handle);  // Close the log.
              fclose($socket);  // Close the connection.
              break;  // End the loop.
          }
          
          // 353 is the user list.
          // This should get the number of ops and users on the provided channel.
          if ($id == '353') {
              $users = explode(' ',$message);  // The array of users.
              $total_count = $total_count + count($users) - 1;  // Add the number of new users, subtract the blank one on the end.
              foreach($users as $status) {  // Run through the users looking for ops.
                  $pos = strstr($status,$irc_op);  // See if it's an op.
                  if ($pos !== false) {  // If we find an op, add 1.
                      $op_count = $op_count + 1;
                  }
              }
          }
          }
          
          // The total less the ops is how many other users are present.
          // The subtracted 1 is because I think the script is counting itself as well.
          $user_count = $total_count - $op_count - 1;
          
          // Display the number of users and ops.
          if ($user_count == 1) {
              echo "1 user and ";
          } else {
              echo "$user_count users and ";
          }
          if ($op_count == 1) {
              echo "1 op are in $irc_channel.";
          } else {
              echo "$op_count ops are in $irc_channel.";
          }
          
          ?>
          

            ahh Nice didnt even think about adding the OPs in my source.

            Try taking out all the ping, version and so on since it isnt making a connection for a long bit of time.
            That might solve your bug.

            Right now this is the heart of our irc code.

            while (!feof($irc_connection) OR !$irc_connection) {  
            $data = fgets($irc_connection, 1024); //echo str_replace("\n", "<br>", $data); $match = explode(" ", $data); if ($match[1] == "322") { //echo $match[4]; $PATH = $_ENV['DOCUMENT_ROOT']; $save_path=$PATH; #define target path $data=$match[4]; $dest='irc_count.txt'; $fp = fopen($save_path . $dest, "w", 0); fputs($fp, $data); fclose($fp); sleep(*60); fputs($irc_connection, "LIST #tda \r\n");

            Credits to my friend (Psychotik,W|cked).

              The connection problem has nothing to do with the PING/VERSION, it's been doing it since before I added that. The reason I added it was because I was testing on Rizon, which automatically does the VERSION request. So, I figured I'd add that bit of code so that it wouldn't ever have problems of being disconnected for not responding. But, honestly it was more of just me messing around. I used this project to learn more about the workings of IRC. :p

              But, my script should be pretty error proof. The connection problem occurs usually if you keep running the script over and over because I guess certain servers obviously would recognize you as a bot and stop allowing you to connect. Or maybe they'd just require you to wait a minute before reconnecting. But, I logged everything and I'm not entirely sure. But, nonetheless, I hope this is useful for someone. Later.

                Well I thank you. Your OP code helped me out. I was having a problem trying to figure out what to do that.

                Ya after testing my cron every 4 mins I got auto banned on a few servers for (proxy) use. If you set it to 20 mins or so it seems to do just fine.

                Thanks for your help.

                  Write a Reply...