# -*- coding: cp1252 -*-
#Imports

import ch
import random
import time
import re
import sys
from random import randint

if sys.version_info[0] > 2:
  import urllib.request as urlreq
else:
  import urllib2 as urlreq
file = open("data/trusted.txt", 'r')
print("NOTE: Trusted Users loaded...")
file.close()
 
file = open("data/mod.txt", 'r')
print("NOTE: Mod list loaded...")
file.close()
 
file = open("data/friends.txt", 'r')
print("NOTE: Your Ownership loaded...")
file.close()

print("Loading Username from chatango")
file.close()
 
print("Loading passwords from the bot")
file.close()
 
print("Loading up teh commands")
file.close()

print("Loading the owner of Sthblueblur")
file.close()
 
print("Loading up the PM from chatango rooms and PM")
file.close()
 
print("Loading up the checking status..")
file.close()

print("You may type in Username: Sthblueblurbot password: supahsonicbot and the chatango room cause its finished yo <3")
file.close()

 
owners=['Sthblueblur']


owners = ['Sthblueblur']   #Put your chatango name here
error = ("Oops. Something went wrong D:")    #Error message
dictionary = dict()


#setting colors

class TestBot(ch.RoomManager):
  def onInit(self):
    self.setNameColor("5F5F5F")
    self.setFontColor("0011FF")
    self.setFontFace("1")
    self.setFontSize(11)
    self.enableBg()  
    self.enableRecording()

#connecting and disconnecting crap
  def onConnect(self, room):
    print("[+] Connected to "+room.name)
    room.message("**Online**")

  def onReconnect(self, room):
    print("[+] Reconnected to "+room.name)
    room.message("**Reconnecting**")
  
  def onDisconnect(self, room):
    print("[+] Disconnected from "+room.name)
    room.message("**Disconnected**")

    

#setting up commands

  def onMessage(self, room, user, message):
    print(room.name + ":" + user.name + ":" + message.body)
    if self.user == user: return
    if message.body[0] == "!":
      data = message.body[1:].split(" ", 1)
      if len(data) > 1:
        cmd, args = data[0], data[1]
      else:
        cmd, args = data[0], ""

# Don't use | in a sentence, I don't know how to fix the error...
#Say thank you to me for copying the PM command on TH Husky's Skype.. >_> (Sthblueblur)

      if cmd == "rn":
        room.message(str(randint(1,50000)))

      elif cmd == "shutdown":
        if room.getLevel(user) > 0:
          self.stop()
        else:
         room.message("Shit, Something went wrong ;~;")

         

       #Check if Mod
      elif cmd == "ismod":
       user = ch.User(args)
       if room.getLevel(user) > 0:
         room.message("Mod: Yes")
       else:
         room.message("Mod: No")

      #List Mods
      elif cmd == "mods":
       room.message(", ".join(room.modnames + [room.ownername]))


      #Check Level
      elif cmd == "mylvl":
       room.message("Your current mod level: %i" %(room.getLevel(user)))

      #Search the Wikipedia
      elif cmd == "wiki":
         if args == "":
           room.message("Type something to search")
         else:
           room.message("http://en.wikipedia.org/wiki/"+args)

      elif cmd == "join":
       with open('data/trusted.txt', 'r') as file:
         if user.name in owners or user.name in file.read():
          self.joinRoom(args)
          file.close()
          print("Joined " + args)
          room.message("Joined " +args)
         else:
          print("Error while trying to join " + args)
          room.message("Cant find that room!")


      if cmd == "addme":
        if user.name in owners:
         with open('data/trusted.txt', 'r') as file:
          if not user.name in file.read():
           print("Note: Adding new username....")
           file.close()
           time.sleep(1)
           file = open('data/name.txt', 'a')
           file.write(user.name + '\n')
           file.close()
           room.message("Added " + user.name + " to trusted")
          else:
           room.message("The user is already in trusted!")

          #Friends#
      elif cmd == "addfriend":
        if user.name in owners:
         with open('data/friends.txt', 'r') as file:
          if not args in file.read():
           print("Note: Adding new username....")
           file.close()
           time.sleep(1)
           file = open('data/friends.txt', 'a')
           file.write(args + '\n')
           file.close()
           room.message("Added " + args + " to friends list. Hooray you can use me:)")
          else:
           room.message("The user is already my friend ;o ")

     
      if cmd == "addmod":
       with open('Data/owners.txt', 'r') as file:
        if user.name in owner or user.name in file.read():
         file = open("Data/owners.txt", 'a')
         file.write("" + args + '\n')
         file.close()
         room.message("successfully added " + args + " to the moderator file")
       

      elif cmd == "define":
        if args.find(":") != -1: #if there's a colon somewhere
                word, definition = args.split(":", 1)

                if word in dictionary:
                        room.message(word + ": already defined")
                else:
                        dictionary[word] = definition
                        room.message(word + ": " + definition)
        else:
                word = args
                if word in dictionary:
                        room.message(word + ": " + dictionary[word])
                else:
                        room.message(word + ": not found")

      
      elif cmd == "slap":
        if not args == "":
          if args in owners:
            room.message("No! I wont slap my owner!")
          else:
            room.message("*slaps "+args+"*")
        else:
          room.message("Who do I slap? O.o")


#Don't add Raw Comments.          
      elif cmd == 'pm':
        if len(args)>=3:
               name,message = args.split(" ", 1)
               self.pm.message(ch.User (name), message)
               room.message("**MESSAGE SENT** Make sure not to use < symbol for your messages, it won't send though")
        else:
               room.message("use command like this: !pm chatangoname message")

#Say thanks to Fagz Mcgee for blocking me on Chatango [Tryhardfucksky]
#extra crap

  def onUserCountChange(self, room):
    print("Users: " + str(room.usercount))
    room.message("Users: "+ str(room.usercount))

  def onMessageDelete(self, room, user, msg):
      print("a message got deleted! " + user.name + ": " + msg.body)


  def onFloodWarning(self, room):
    room.reconnect()
    print("[+] Reconnecting...")


  def onPMMessage(self, pm, user, body):
    print("[INF][PM]["+user.name+"]["+body+"]")
    if body[0] == "!":
      data = body[1:].split(" ", 1)
      if len(data) > 1:
        cmd, args = data[0], data[1]
      else:
        cmd, args = data[0], ""
      if cmd == "pm":
        if len(args) >= 3:
          name, message = args.split(" ", 1)
          self.pm.message(ch.User(name), message)
        else:
          self.pm.message(user, "use command like this: !pm chatangoname message")


if __name__ == "__main__":
        TestBot.easy_start()
