<actions>
  <!-- call it with 
     xidel --template-file reddit-robobutler.xml 
  -->
  <action>  
    <s> if (empty(get("user", ()))) then $user := (trace((), "Username: "), read()) else () </s>
    <s> if (empty(get("passwd", ()))) then $passwd := (trace((), "Password: "), read()) else () </s>
 
    <page url="https://www.reddit.com/api/login">
      <post name="user" value="{$user}"/>
      <post name="passwd" value="{$passwd}"/>
      <post name="api_type" value="json"/>
    </page>    
    
    <page url="https://www.reddit.com/api/me.json">
      <template><t:s>modhash := jn:parse-json($raw)//modhash</t:s></template>
    </page>
        
    <loop test="true()">
      <page url="https://www.reddit.com/message/unread.json">
        <template><t:s>letters := jn:parse-json($raw)/data/children/data</t:s></template>
      </page>
<!--    <s>letters := ("/u/butler bring soda")</s>-->
    <!--<loop var="rep" list="1 to 10">-->
    <loop var="letter" list="$letters">
      <s> declare variable $rand-seed := seconds-from-time(current-time()) mod 7;
             declare function rand-text($list) { let $i := floor((random()+$rand-seed)*count($list)) mod count($list) + 1 return $list[$i] };
             declare function is-plural($word) { if (ends-with($word, "s")) then true() else false() };
         trace($letter/body, "letter: "), 
         $bring := extract($letter/body, "(bring|get)\s*(me)?\s*(my|the|an?)?\s*([^,.:;!?\n]+)",4),
         $response := if ($bring) then "[*" ||
           replace(rand-text(("Enjoy your %!",
             if (is-plural($bring)) then ("Here are your %!")
             else ("Here is your %!")
           )), "%", $bring) || "*](/robobutler-in)"
         else (),
         trace($response,"===> response")        
      </s>
      
      <page test="$response" url="https://www.reddit.com/api/comment.json">
        <header name="X-Modhash" value="{$modhash}"/>
        <post name="api_type" value="json"/>
        <post name="text" value="{$response}"/>
        <post name="thing_id" value="{$letter/name}"/>
      </page>
      
    </loop>
    
    <page test="exists($letters)" url="https://www.reddit.com/api/read_message">
      <header name="X-Modhash" value="{$modhash}"/>
      <post name="id" value="{join($letters/name, ',')}"/>
    </page>
    
    <s>sleep(1000*60*5)</s>
    </loop>
    
  </action>
</actions>
