#!/usr/bin/env python

#
# pymnkbot - lame irc bot. 
#
# Copyright (c) 2008, Patrick MARIE <mycroft@monkeyz.eu>
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

"""
You must create the configuration file before launching:

cat > pymnkbot.conf << EOF
[pymnkbot]
irc_server = irc.freenode.net
irc_port = 6667
nickname = zibot
nickpass =
realname = zibot - Powered by pymnkbot
channel = #oldschool
nickserv_password = thypassword!
admin_mask = =mycroft@
EOF

"""

import sys, os, random
import ConfigParser
import urllib
from twyt import twitter, data

server = []
irc_server_name = ''
irc_server_port = ''
admin_mask = ''
nickname = ''
nickpass = ''
realname = ''
channel = ''
nickserv_password = ''

talk_lines = []

try:
  from ircbot import SingleServerIRCBot
  import irclib
except ImportError, e:
  print e
  sys.exit(1)

class pybot(SingleServerIRCBot):
  def __init__(self, server, nick, realname, chan):
    SingleServerIRCBot.__init__(self, server, nick, realname)
    self.chan = chan
    self.nick = nick

  ##
  ## Event callbacks
  ##
  def on_welcome(self, c, e):
    if self.chan:
      c.privmsg("nickserv", "identify " + nickserv_password)
      c.join(self.chan)
      c.privmsg("chanserv", "op #oldschool zibot")

  def on_join(self, c, e):
    who = e.source().split('!', 1)
    if who[0] == self.nick:
      c.privmsg(e.target(), 'Hello world!')

  # c is irclib.ServerConnection
  # e is irclib.Event
  def on_privmsg(self, c, e):
    msg = e.arguments()[0].strip()
    source = e.source().split('!')[0]
    if msg.startswith("twitt_auth"):
      t_auth_array = msg.split(' ');
      if(len(t_auth_array) == 3):
        auth_array[source] = [t_auth_array[1], t_auth_array[2]]
        c.privmsg(source, "You're auth as " + t_auth_array[1]) 
    if msg.startswith("help"):
      c.privmsg(source, "Private commands:")
      c.privmsg(source, "twitt_auth <nick> <password>")
      c.privmsg(source, "Public commands:")
      c.privmsg(source, ".snip <url>")
      c.privmsg(source, ".tweet [your tweet !]")

  def on_pubmsg(self, c, e):
    msg = e.arguments()[0].strip()

    if msg.startswith('.'):
      cmd = msg[1:].split(' ', 1)[0]
      self.user_trigger(c, e, cmd)

    if msg.startswith('!'):
      cmd = msg[1:].split(' ', 1)[0]
      self.trigger(c, e, cmd)

    if msg.startswith(self.nick+":"):
      dst_src = e.source().split("!", 1)[0].strip()
      my_str = msg.split(self.nick + ":", 1)[1].strip()
      if my_str not in talk_lines:
        talk_lines.append(my_str)
        print>>fd, my_str
      c.privmsg(e.target(), dst_src + ": " + talk_lines[random.randint(0, len(talk_lines) - 1)])

  ##
  ## Command triggers
  ##
  def user_trigger(self, c, e, cmd):
    try:
      getattr(self, 'user_cmd_%s' % cmd)(c, e)
    except AttributeError:
      pass

  def trigger(self, c, e, cmd):
    try:
      if e.source().find(admin_mask) != -1:
        getattr(self, 'cmd_%s' % cmd)(c, e)
    except AttributeError, e:
      # print e
      # c.privmsg(e.target(), 'Command not found.')
      pass

#    >>> s = data.Status()
#    >>> s.load_json(return_val)
#    >>> print s
#    [568644162] Andy Price: Test (Sun Jan 06 16:10:53 +0000 2008 via web)
#    >>> print s.id
#    568644162
#    >>> t.status_destroy(s.id)

  ##
  ## Commands for everyone
  ##
  def user_cmd_tweet(self, c, e):
    self.user_cmd_twitter(c, e)

  def user_cmd_twitter(self, c, e):
    try:
      source = e.source().split('!')[0]
      if source not in auth_array:
        c.privmsg(e.target(), "Can't tweet ... please auth yourself !")
      else:
        t = twitter.Twitter()
        t.setauth(auth_array[source][0], auth_array[source][1])
        msg = e.arguments()[0].split(' ', 1)[1]
        msg_unc = unicode(msg, "iso8859-15")
        msg_utf8 = msg_unc.encode("utf-8")
        t.status_update(msg_utf8)
    except Exception, inst:
      c.privmsg(e.target(), "Can't tweet ... please retry later!")

  def user_cmd_snip(self, c, e):
    try:
      uri = "http://snipr.com/site/snip?r=simple&link="
      uri = uri + e.arguments()[0].split(' ', 1)[1]
      u = urllib.urlopen(uri)
      bytes = u.read()
      u.close()
      c.privmsg(e.target(), bytes)
    except Exception, inst:
      c.privmsg(e.target(), "Can't get snipurl... Please retry later!")

  ##
  ## Commands for admins.
  ##
  def cmd_cycle(self, c, e):
    chan = e.target()
    c.part(chan)
    c.join(chan)

  def cmd_die(self, c, e):
    fd.close()
    SingleServerIRCBot.die(self, 'Argh')

  def cmd_tamere(self, c, e):
    c.privmsg(e.target(), 'Mais ta mere quoi !')

  def cmd_eval(self, c, e):
    msg = e.arguments()[0].split(' ', 1)[1]
# e.target() == salon ou est envoye le message
# e.source() == source du message
# e.arguments()[0] == message
# cmd = msg[1:].split(' ', 1)[0]
# line = msg[1:].split(' ', 1)[1]
    print e.target()
    c.privmsg(e.target(), eval(msg))

  def cmd_reload(self, c, e):
    reload(functions)
    c.privmsg(e.target(), 'Modules reloaded.')

## Here comes the real script
if __name__ == '__main__':
  configfile = "pymnkbot.conf"
  c = ConfigParser.ConfigParser()
  c.read(configfile)
  cfgsect = 'pymnkbot'

  irc_server_name = c.get(cfgsect, 'irc_server')
  irc_server_port = c.get(cfgsect, 'irc_port')
  nickname = c.get(cfgsect, 'nickname')
  nickpass = c.get(cfgsect, 'nickpass')
  channel  = c.get(cfgsect, 'channel')
  realname = c.get(cfgsect, 'realname')
  admin_mask = c.get(cfgsect, 'admin_mask')

  nickserv_password = c.get(cfgsect, 'nickserv_password')

  server = [(irc_server_name, int(irc_server_port))]

  filename = "log.txt"
  fd = open(filename, "rw+")

  auth_array = {} 

  for line in fd:
    if line not in talk_lines:
      talk_lines.append(line)
 
  bot = pybot(server, nickname, realname, channel)
  try:
    bot.start()
  except KeyboardInterrupt:
    bot.connection.disconnect("Ctrl-C m'a tuer")
    bot.connection.close()
    fd.close()

