Advertisement
Guest User

welcomepony v1.1

a guest
Jun 15th, 2013
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.11 KB | None | 0 0
  1. #!/usr/bin/php
  2. <?php
  3. /****** ULTRA LAZY CODE GOOOOOOO ******/
  4.  
  5. /* Database structure:
  6.  *
  7.  * 'messages':
  8.  * - 'enabled' - BOOLEAN
  9.  * - 'user' ---- VARCHAR(64)
  10.  * - 'notice' -- INT
  11.  * - 'message' - LONGVARCHAR(1000)
  12.  *
  13.  * 'admins':
  14.  * - 'id' ------ INT
  15.  */
  16.  
  17.  
  18. // Allowed arguments & their defaults
  19. $runmode = array(
  20.     'no-daemon' => false,
  21.     'help' => false,
  22.     'write-initd' => false,
  23. );
  24.  
  25. // Scan command line attributes for allowed arguments
  26. foreach($argv as $k=>$arg) {
  27.     if (substr($arg, 0, 2) == '--' && isset($runmode[substr($arg, 2)])) {
  28.         $runmode[substr($arg, 2)] = true;
  29.     }
  30. }
  31.  
  32. // Help mode. Shows allowed argumentents and quit directly
  33. if($runmode['help'] == true) {
  34.     echo 'Usage: '.$argv[0].' [runmode]' . "\n";
  35.     echo 'Available runmodes:' . "\n";
  36.     foreach ($runmode as $runmod=>$val) {
  37.         echo ' --'.$runmod . "\n";
  38.     }
  39.     die();
  40. }
  41.  
  42. // Include Class
  43. error_reporting(E_STRICT);
  44. require_once 'System/Daemon.php';
  45.  
  46. // Setup
  47. $options = array(
  48.     'appName' => 'welcomed',
  49.     'appDir' => dirname(__FILE__),
  50.     'appDescription' => 'Parses StatusNet public events and welcomes users with 1 notice.',
  51.     'authorName' => 'Tylian',
  52.     'authorEmail' => 'immatyger@gmail.com',
  53.     'sysMaxExecutionTime' => '0',
  54.     'sysMaxInputTime' => '0',
  55.     'sysMemoryLimit' => '512M',
  56.     'appRunAsGID' => 1000,
  57.     'appRunAsUID' => 1000,
  58. );
  59.  
  60. System_Daemon::setOptions($options);
  61.  
  62. // This program can also be run in the forground with runmode --no-daemon
  63. if(!$runmode['no-daemon']) {
  64.     System_Daemon::start();
  65. } else {
  66.     System_Daemon::info('running in no-daemon mode');
  67. }
  68.  
  69. // With the runmode --write-initd, this program can automatically write a
  70. // system startup file called: 'init.d'
  71. // This will make sure your daemon will be started on reboot
  72. if(!$runmode['write-initd']) {
  73.     System_Daemon::info('not writing an init.d script this time');
  74. } else {
  75.     if(($initd_location = System_Daemon::writeAutoRun()) === false) {
  76.         System_Daemon::notice('unable to write init.d script');
  77.     } else {
  78.         System_Daemon::info('sucessfully written startup script: %s',
  79.             $initd_location);
  80.     }
  81. }
  82.  
  83. // ----------------------------------------------------------------------
  84. // Bot config
  85.  
  86. // Site configuration
  87.  
  88. $apiBase  = 'http://rainbowdash.net/api';
  89. $username = 'welcomepony';
  90. $password = 'YOURFACEISLIKEABUTT';
  91.  
  92. // MySQL configuration
  93. $mysqlHost = 'localhost';
  94. $mysqlUsername = 'MAGICFRIENDSHIPHORSES';
  95. $mysqlPassword = 'IUSEDTOWONDERWHATFRIENDSHIPCOULDBE';
  96. $mysqlDatabase = 'welcomebot';
  97.  
  98. $admins = array();/*
  99. $admins[] = 'minti';
  100. $admins[] = 'colfax';
  101. $admins[] = 'redenchilada';
  102. $admins[] = 'nerthos';
  103. $admins[] = 'ceruleanspark';
  104. $admins[] = 'widget';*/
  105.  
  106. initAdmins();
  107. $admins[798] = 'a';
  108.  
  109. // Time to wait between each check
  110. $refreshDelay = 30;
  111. $commandDelay = 60;
  112.  
  113. // Global variables
  114. $lastNoticeId = 0;
  115. $lastCommandTime = 0;
  116.  
  117. // Random crap
  118. $welcomeToggle = true;              // Toggle on/off for welcome me command
  119. $uniqueIds = array();               // Array of unique users
  120. $lastReset = "";                    // Last day that the unique users thing was reset. It's text cause I can, and did.
  121. $postingFrom = "Gravity Falls, OR"; // Source
  122.  
  123. // -----------------------------------------------------------------------
  124. // Bot entry point
  125.  
  126. // Prepare posts to get the last notice ID.
  127. $posts = getTimeline();
  128. foreach($posts as $post) {
  129.     if($post->id > $lastNoticeId) {
  130.         $lastNoticeId = $post->id;
  131.     }
  132. }
  133.  
  134. while(!System_Daemon::isDying()) {
  135.     $posts = getTimeline();
  136.     foreach($posts as $post) {
  137.         // Store the ID so we don't reparse notices we've already seen
  138.         if($post->id > $lastNoticeId)
  139.             $lastNoticeId = $post->id;
  140.    
  141.         // Check if we need to empty the unique users array
  142.         if(date('j') != $lastReset) {
  143.             $lastReset = date('j');
  144.             System_Daemon::info('$s users posted today.', count($uniqueIds);
  145.             $uniqueIds = array();
  146.         }
  147.    
  148.         // Check if the user is unique, if so add them to the unique user array
  149.         if(!in_array($post->user->id, $uniqueIds)) {   
  150.             $uniqueIds[] = $post->user->id;
  151.         }
  152.        
  153.         // Send a welcome if they have only one notice
  154.         if($post->user->statuses_count == 1) {
  155.             System_Daemon::info('new user found: %s', $post->user->screen_name);
  156.             postNotice(getMessage($post->user->screen_name), $post->id);
  157.             continue;
  158.         }
  159.        
  160.         $postText = strtolower($post->text);
  161.        
  162.         // This message doesn't reference us, ignore it!
  163.         if(strpos($postText, strtolower("@$username")) === false)
  164.             continue;
  165.        
  166.         // Store if they're an admin
  167.         $isAdmin = isset($admins[$post->user->id]);
  168.        
  169.         // SUPER HAPPY CRAZY LET EVERYONE DO EVERYTHING MODE
  170.         $isAdmin = true;
  171.        
  172.         // Add message to Queue if they request it
  173.         if(substr($postText, 0, strlen($username) + 6) == "@$username add ") {
  174.             System_Daemon::info('adding message from %s to database', $post->user->screen_name);
  175.            
  176.             $message = substr($post->text, strlen($username) + 6);
  177.             $reply = sprintf('@%s Thank you for the suggestion! The message has been sent to a queue to be approved, and once it is you\'ll see it being sent to newponies!', $post->user->screen_name);
  178.            
  179.             addMessage($message, $post->user->screen_name, $post->id);
  180.             postNotice($reply, $post->id);
  181.             continue;
  182.         }
  183.        
  184.         // Commands that have a limit
  185.         if((time() - $lastCommandTime >= $commandDelay) || $isAdmin) {
  186.             if(strpos($postText, 'ping') !== false) {
  187.                 System_Daemon::info('responding to ping from %s', $post->user->screen_name);
  188.                 $message = sprintf('@%s pong!', $post->user->screen_name);
  189.                 postNotice($message, $post->id);
  190.                
  191.                 $lastCommandTime = time();
  192.                 continue;
  193.             }
  194.             if(strpos($postText, 'ell me a story') !== false) {
  195.                 System_Daemon::info('telling %s the story of welcomepony', $post->user->screen_name);
  196.                 $message = sprintf('@%s Once upon a time there was a pony who felt very sad because she didn\'t know what to do with her life. Then she found out that her special talent was welcoming people! So she began welcoming all the newponies who showed up around town. The end!', $post->user->screen_name);
  197.                 postNotice($message, $post->id);
  198.                
  199.                 $lastCommandTime = time();
  200.                 continue;
  201.             }
  202.            
  203.             if(strpos($postText, 'welcome me') !== false) {
  204.                 // Deny the welcome if a mod has turned welcomes off
  205.                 if(!$welcomeToggle) continue;
  206.                
  207.                 System_Daemon::info('sending a forced welcome to %s', $post->user->screen_name);
  208.                 postNotice(getMessage($post->user->screen_name), $post->id);
  209.                
  210.                 $lastCommandTime = time();
  211.                 continue;
  212.             }
  213.            
  214.             if(strpos($postText, 'users') !== false) {
  215.                 System_Daemon::info('sending unique user stats to %s', $post->user->screen_name);
  216.                 $message = sprintf('@%s Wowie, %d unique users have posted today!!', $post->user->screen_name, count($uniqueIds));
  217.                 postNotice($message, $post->id);
  218.                
  219.                 $lastCommandTime = time();
  220.                 continue;
  221.             }
  222.            
  223.             if(strpos($postText, 'You\'re ugly') !== false ||
  224.                 strpos($postText, 'you\'re ugly') !== false ||
  225.                 strpos($postText, 'Your ugly') !== false ||
  226.                 strpos($postText, 'your ugly') !== false) {
  227.                 System_Daemon::info('getting mad at %s', $post->user->screen_name);
  228.                 $message = sprintf('@%s #banned', $post->user->screen_name);
  229.                 postNotice($message, $post->id);
  230.                
  231.                 $lastCommandTime = time();
  232.                 continue;
  233.             }
  234.         }
  235.        
  236.         // The following commands are admin only.
  237.         if(!$isAdmin) continue;
  238.  
  239.         if(strpos($postText, 'approve welcome') !== false) {
  240.             System_Daemon::info('%s approved welcome notice %s', $post->user->screen_name, $post->in_reply_to_status_id);
  241.             $message = sprintf('@%s Okey dokey lokey! I\'ll start sending this message to newponies!', $post->user->screen_name);
  242.             postNotice($message, $post->id);
  243.            
  244.             approveMessage($post->in_reply_to_status_id);
  245.             continue;
  246.         }
  247.  
  248.         if(strpos($postText, 'welcome off') !== false) {
  249.             System_Daemon::info('%s disabled welcome messages', $post->user->screen_name);
  250.             $message = sprintf('@%s Okey dokey lokey! I won\'t welcome ponies who want me to!', $post->user->screen_name);
  251.             postNotice($message, $post->id);
  252.            
  253.             $welcomeToggle = false;
  254.             continue;
  255.         }
  256.            
  257.         if(strpos($postText, 'welcome on') !== false) {
  258.             System_Daemon::info('%s enabled welcome messages', $post->user->screen_name);
  259.             $message = sprintf('@%s Okey dokey lokey! I\'ll welcome ponies who want me too!', $post->user->screen_name);
  260.             postNotice($message, $post->id);
  261.            
  262.             $welcomeToggle = true;
  263.             continue;
  264.         }
  265.        
  266.         if(strpos($postText, 'unique reset') !== false) {
  267.             System_Daemon::info('%s resetted unique user list manually.', $post->user->screen_name);
  268.             $message = sprintf('@%s Okey dokey lokey! I\'ll reset my list of unique ponies!', $post->user->screen_name);
  269.             postNotice($message, $post->id);
  270.            
  271.             $uniqueIds = array();
  272.             continue;
  273.         }
  274.        
  275.         if(strpos($postText, 'shut down') !== false) {
  276.             System_Daemon::info('stopping due to command from '. $post->user->screen_name);
  277.             $message = sprintf('@%s Okay.. If you insist.. Goodbye cruel Equestria!!', $post->user->screen_name);
  278.             postNotice($message, $post->id);
  279.            
  280.             System_Daemon::stop();
  281.             exit();
  282.         }
  283.        
  284.         if(substr($postText, 0, strlen($username) + 10) == "@$username promote ") {
  285.        
  286.             $promoting = intval(substr($post->text, strlen($username) + 10));
  287.            
  288.             System_Daemon::info('%s is promoting user ID %s to bot admin', $post->user->screen_name, $promoting);
  289.            
  290.             $message = "";
  291.             if(addAdmin($promoting))
  292.                 $message = '@%s This user has been promoted.';
  293.             else
  294.                 $message = '@%s This user could not be promoted.';
  295.                
  296.             $reply = sprintf($message, $post->user->screen_name);
  297.            
  298.             postNotice($reply, $post->id);
  299.             continue;
  300.         }
  301.        
  302.         if(substr($postText, 0, strlen($username) + 9) == "@$username demote ") {
  303.        
  304.             $demoting = intval(substr($post->text, strlen($username) + 9));
  305.            
  306.             System_Daemon::info('%s is demoting user ID %s from bot admin', $post->user->screen_name, $demoting);
  307.            
  308.             $message = "";
  309.             if(removeAdmin($demoting))
  310.                 $message = '@%s This user has been demoted.';
  311.             else
  312.                 $message = '@%s This user could not be demoted.';
  313.                
  314.             $reply = sprintf($message, $post->user->screen_name);
  315.            
  316.             postNotice($reply, $post->id);
  317.             continue;
  318.         }
  319.         /*
  320.         if(strpos($postText, 'debug') !== false) {
  321.             $message = sprintf('@%s Debug information has been printed to the log.', $post->user->screen_name);
  322.             postNotice($message, $post->id);
  323.            
  324.             System_Daemon::info('Bot admins:');
  325.             foreach($admins as $k => $v)
  326.                 System_Daemon::info($k . $v);
  327.            
  328.             System_Daemon::info('Unique users:');
  329.             foreach($uniqueIds as $i)
  330.                 System_Daemon::info($i);
  331.            
  332.             continue;
  333.         }
  334.         */
  335.         if(substr($postText, 0, strlen($username) + 9) == "@$username source ") {
  336.        
  337.             $postingFrom = substr($post->text, strlen($username) + 9);
  338.            
  339.             System_Daemon::info('%s changed source to %s', $post->user->screen_name, $postingFrom);
  340.                
  341.             $reply = sprintf('@%s Okey, I\'ll start talking from "%s"!', $post->user->screen_name, $postingFrom);
  342.            
  343.             postNotice($reply, $post->id);
  344.             continue;
  345.         }
  346.     }
  347.  
  348.     System_Daemon::iterate($refreshDelay);
  349. }
  350.  
  351. System_Daemon::info('stopping');
  352. System_Daemon::stop();
  353.  
  354. // ----------------------------------------------------------------------
  355. // Bot helper functions below this line
  356.  
  357. // Gets the public timeline as an object
  358. function getTimeline() {
  359.     global $lastNoticeId, $apiBase;
  360.    
  361.     $curl = curl_init();
  362.    
  363.     curl_setopt($curl, CURLOPT_URL, "$apiBase/statuses/public_timeline.json?since_id=$lastNoticeId");
  364.     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  365.     curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
  366.    
  367.     $data = curl_exec($curl);
  368.     curl_close($curl);
  369.    
  370.     return json_decode($data);
  371. }
  372.  
  373. // Gets a random welcome message from the database.
  374. function getMessage($name) {
  375.     global $mysqlHost, $mysqlUsername, $mysqlPassword, $mysqlDatabase;
  376.    
  377.     mysql_connect($mysqlHost, $mysqlUsername, $mysqlPassword);
  378.     mysql_select_db($mysqlDatabase);
  379.    
  380.     $result = mysql_query('SELECT * FROM messages WHERE enabled=1 ORDER BY RAND() LIMIT 1');
  381.     $row = mysql_fetch_object($result);
  382.    
  383.     mysql_close();
  384.    
  385.     return sprintf($row->message, $name);
  386. }
  387.  
  388. // Adds a welcome message to the database
  389. function addMessage($message, $user, $id) {
  390.     global $mysqlHost, $mysqlUsername, $mysqlPassword, $mysqlDatabase;
  391.    
  392.     mysql_connect($mysqlHost, $mysqlUsername, $mysqlPassword);
  393.     mysql_select_db($mysqlDatabase);
  394.    
  395.     $query = sprintf("INSERT INTO `%s`.`messages` (`enabled`, `user`, `notice`, `message`)
  396.         VALUES (0, '%s', '%s', '%s')",
  397.         $mysqlDatabase,
  398.         mysql_real_escape_string($user),
  399.         mysql_real_escape_string($id),
  400.         mysql_real_escape_string($message));
  401.        
  402.     $result = mysql_query($query);
  403.    
  404.     mysql_close();
  405.     return true;
  406. }
  407.  
  408. function approveMessage($id) {
  409.     global $mysqlHost, $mysqlUsername, $mysqlPassword, $mysqlDatabase;
  410.    
  411.     mysql_connect($mysqlHost, $mysqlUsername, $mysqlPassword);
  412.     mysql_select_db($mysqlDatabase);
  413.    
  414.     $query = sprintf("UPDATE `%s`.`messages` SET `enabled`=1 WHERE notice=%s",
  415.         $mysqlDatabase,
  416.         mysql_real_escape_string($id));
  417.        
  418.     $result = mysql_query($query);
  419.    
  420.     mysql_close();
  421.     return true;
  422. }
  423.  
  424. // Posts a notice to the service using the auth provided on config
  425. function postNotice($notice, $replyId) {
  426.     global $apiBase, $username, $password, $postingFrom;
  427.     $curl = curl_init();
  428.  
  429.     System_Daemon::info('sending notice: %s', $notice);
  430.    
  431.     $data = array('status' => $notice, 'source' => $postingFrom, 'in_reply_to_status_id' => $replyId);
  432.    
  433.     curl_setopt($curl, CURLOPT_URL, "$apiBase/statuses/update.json");
  434.     curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
  435.     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  436.     curl_setopt($curl, CURLOPT_POST, 1);
  437.     curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data, '&'));
  438.     curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
  439.  
  440.     curl_exec($curl);
  441.     curl_close($curl);
  442.    
  443.     return true;
  444. }
  445.  
  446. function initAdmins() {
  447.     global $mysqlHost, $mysqlUsername, $mysqlPassword, $mysqlDatabase, $admins;
  448.    
  449.     mysql_connect($mysqlHost, $mysqlUsername, $mysqlPassword);
  450.     mysql_select_db($mysqlDatabase);
  451.    
  452.     $result = mysql_query('SELECT * FROM admins');
  453.     while($row = mysql_fetch_array($result))
  454.         $admins[intval($row['id'])] = 'm';
  455.    
  456.     mysql_close();
  457. }
  458.  
  459. function addAdmin($id) {
  460.     global $mysqlHost, $mysqlUsername, $mysqlPassword, $mysqlDatabase, $admins;
  461.    
  462.     if(isset($admins[$id]))
  463.         return false;
  464.    
  465.     mysql_connect($mysqlHost, $mysqlUsername, $mysqlPassword);
  466.     mysql_select_db($mysqlDatabase);
  467.    
  468.     $query = sprintf("INSERT INTO `%s`.`admins` (`id`)
  469.         VALUES ('%s')",
  470.         $mysqlDatabase,
  471.         mysql_real_escape_string($id));
  472.        
  473.     $result = mysql_query($query);
  474.    
  475.     $admins[$id] = 'm';
  476.    
  477.     mysql_close();
  478.     return true;
  479. }
  480.  
  481. function removeAdmin($id) {
  482.     global $mysqlHost, $mysqlUsername, $mysqlPassword, $mysqlDatabase, $admins;
  483.    
  484.     if(!isset($admins[$id]) || $admins[$id] == 'a')
  485.         return false;
  486.    
  487.     mysql_connect($mysqlHost, $mysqlUsername, $mysqlPassword);
  488.     mysql_select_db($mysqlDatabase);
  489.    
  490.     $query = sprintf("DELETE FROM `%s`.`admins` WHERE `id`=`%s`",
  491.         $mysqlDatabase,
  492.         mysql_real_escape_string($id));
  493.        
  494.     $result = mysql_query($query);
  495.    
  496.     unset($admins[$id]);
  497.    
  498.     mysql_close();
  499.     return true;
  500. }
  501.  
  502. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement