Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: UTF-8 -*-
- import socket
- import sys
- import os
- import time
- from packet import *
- import struct
- import urllib2
- import hashlib
- import threading
- import config
- from debug import *
- class Irc:
- def __init__(self):
- self.activeConnexion = None
- self.ircUsername = ''
- self.ircChannel = ''
- self.ircChannels = []
- self.ircServeur = ''
- self.ircGreeting = "Hi im Imrubot. bye"
- self.ircWhoIm = "IDK"
- self.ircLogger = open('logs.txt', 'a')
- self.ircSpliter = {'name':'Íèê','tribe':'Ïëåìÿ','title':'Òèòóë','rounds':'Ðàóíäû','cheese':'Ñûð','sham_':'Øàìàí ','saves':'Ñåéâû','hard_':'Ãîëä ','first':'Ôåñòû','rank':'Ðàíã'}
- self.ircList = ['name', 'tribe', 'title', 'rounds', 'cheese', 'sham_', 'saves', 'hard_', 'first', 'rank']
- def ircConnexion(self, host, port):
- self.ircServeur = host
- self.activeConnexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- debug('Connection to:%s:%s'%(host, port))
- self.activeConnexion.connect( (host, port) )
- def ircAurh(self, username, password, privatechannel, channels, logchannel):
- self.ircChannel = privatechannel
- self.ircChannels = channels
- self.ircChannels.append(self.ircChannel)
- debug('auth...')
- debug("USER %s %s bla :%s\r\n"%(username, self.ircServeur, username))
- self.activeConnexion.send("USER %s %s bla :%s\r\n"%(username, self.ircServeur, username))
- self.activeConnexion.send("NICK %s\n"%username)
- debug("NICK %s\n"%username)
- self.ircSendMessage(self.ircChannel, self.ircGreeting)
- self.activeConnexion.send("JOIN %s\n"%self.ircChannel)
- debug("JOIN %s\n"%self.ircChannel)
- for channel in channels:
- self.activeConnexion.send("JOIN %s\n"%channel)
- debug("JOIN %s\n"%channel)
- self.ircSendMessage(channel, self.ircGreeting)
- def ircSendMessage(self, channel, message):
- self.activeConnexion.send("PRIVMSG %s :%s\r\n"%(channel, message))
- debug("PRIVMSG %s :%s\r\n"%(channel, message))
- def ircRecvMessage(self, user, message):
- bot.private(user, message)
- def ircLog(self, string):
- now = time.localtime(time.time())
- datetime = time.strftime("%y/%m/%d %H:%M", now)
- self.ircLogger.write('[%s] %s'%(datetime, string) )
- self.ircLogger.close()
- def ircParser(self, packet):
- #select type
- if 'PRIVMSG' in packet:
- try:
- packet = packet.split(' ')
- print packet
- user = packet[0].split('!')[0].strip(':')
- channel = packet[2]
- #message = ':'.join(packet[2])
- message = ' '.join(packet[3:]).strip('\n\r').strip(':')
- print bytes([message])
- debug('%s:%s'%( user, message ))
- if '!stat' in message:
- self.ircTFMAPI(message.split(' ')[1], channel)
- elif '!c' in message:
- who = message.split(' ')[1]
- text = ' '.join(message.split(' ')[2:])
- debug('[MODERATION]: %s > %s'%(who, text))
- if 'irc.' not in message:self.ircRecvMessage(who, text)
- except:debug('Error unpacking')
- elif "PING :" in packet:self.ircPingPong(packet.split(' ')[1])
- def ircTFMAPI(self, nick, channel):
- tfmAPI = urllib2.urlopen("http://api.formice.com/mouse/stats.json?n=%s"%nick)
- statapi = tfmAPI.read()
- tfmAPI.close()
- statapi = statapi.replace('"', '').replace('}', '').replace('{' , '').replace(':', '::')
- for i in self.ircList:
- try:statapi = statapi.replace(i, self.ircSpliter[i])
- except:pass
- statapi = ' | '.join(statapi.split(','))
- self.ircSendMessage(channel, 'Profile %s: %s'%(nick, statapi))
- print statapi
- def ircPingPong(self, packet):
- self.activeConnexion.send("PONG %s\n"%packet)
- debug("PONG %s\n"%packet)
- def ircListener(self):
- data = ''
- try:data = self.activeConnexion.recv(4096)
- except:self.debug('Socket problem...')
- if data!='':
- debug(data)
- self.ircParser(data)
- class MyBot:
- def __init__(self, login, password,
- room, comm):
- self.login = login
- self.password = password
- self.room = room
- self.community = comm
- self.Bulle_diconnexion = False
- self.Main_diconnexion = False
- self.Bulle_connexion = False
- self.Main_socket = None
- self.Bulle_cocket = None
- self.Dummy_time = time.time()
- self.Null_Prefix = struct.pack('!l', 0)
- self.state = None
- self.read_data = ""
- self.Main_fingerprint = None
- self.Bulle_fingerprint = None
- self.dummy_last_time = time.time()
- self.mstate = None
- self.r_data = ''
- self.afk_last_time = time.time()
- self.b = RawData()
- self.community = {0:"en", 1:"fr", 2:"ru", 3:"br", 4:"es", 5:"cn", 6:"tr", 7:"vk", 8:"pl", 9:"hu", 10:"nl"}
- self.modlist = {}
- self.command = {'en':['modlist', 'helperlist', 'event', 'update', 'badmap', 'mod', 'help'], 'ru':['ìîäëèñò', 'õåëïåðû', 'ýâåíò', 'îáíîâëåíèå', 'êàðòà', 'ìîä', 'ïîìîùü']}
- self.helperlist = {}
- def GetVK(self):
- data = urllib2.urlopen('http://kikoo.formice.com/data.txt').readline()
- recvkikoo = data.split('\x20')
- kikoo = []
- kikoo.append(recvkikoo[1])
- kikoo.append(recvkikoo[2])
- return kikoo
- def Main_Connexion(self, serveur):
- self.Main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- try:self.Main_socket.connect(serveur)
- except: debug("Main connexion failed!", Exit=True)
- Data = self.GetVK()
- try:self.First_Packet_data(Data[0], Data[1])
- except:debug("Failed to send First Packet", Exit=True)
- self.Main_socket.setblocking(False)
- debug("Done", Exit=False)
- return True
- def Bulle_Connexion(self, key, ip):
- self.Bulle_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- portwithip = (ip[1:], 443)
- try:self.Bulle_socket.connect(portwithip)
- except: debug("Bulle connexion Failed!", Exit=True)
- debug("Bulle connexion completed!", Exit=False)
- self.Bulle_send_key(key)
- debug("In game!", Exit=False)
- self.Bulle_socket.setblocking(False)
- self.Bulle_diconnexion = False
- self.Bulle_connexion = True
- def First_Packet_data(self, Version, Key):
- Packet = MyPack()
- Packet.add('\x1c\x01')
- Packet.addint(int(Version), 2)
- Packet.addstr(Key.replace('\x0A', ''))
- Packet.add('\x17\xed')
- self.send(Packet, Prefix=False, serveur="Main")
- def Bulle_send_key(self, key):
- Bulle_Packet = MyPack()
- Bulle_Packet.add(key)
- self.send(Bulle_Packet, Prefix=False, serveur="Bulle")
- def send(self, packet, Prefix=True,
- serveur="Main", RawBytes = ''):
- p_size = packet.size() + 8
- if packet.Protocol == 'old': p_size += 4
- data = MyPack()
- data.addint(p_size, 4)
- if Prefix:
- if serveur == 'Main': prefix = self.Main_fingerprint()
- else: prefix = self.Bulle_fingerprint()
- data.add(prefix)
- else: data.add(self.Null_Prefix)
- if packet.Protocol == 'old':
- data.add(RawBytes)
- data.addint(packet.size(), 2)
- data.add(packet.data)
- debug(serveur.upper() + " SENDING >%s"% bytes([data.data]), Exit=False)
- try:
- if serveur == 'Main': self.Main_socket.send(data.data)
- else: self.Bulle_socket.send(data.data)
- except: debug("'%s' server error. Sending failed!"% serveur, Exit=True)
- def auth(self):
- passhash = hashlib.sha256(self.password).hexdigest()
- packet = MyPack()
- packet.add('\x1A\x04')
- packet.add('\x01')
- packet.add(self.login)
- packet.add('\x01')
- packet.add(passhash)
- packet.add('\x01')
- packet.add(self.room)
- packet.add('\x01')
- packet.add('http://www.transformice.com/Transformice.swf?d='+str(time.time()).split('.')[0])
- #packet.add('StandAlone\x00\x01-')
- packet.Protocol = 'old'
- self.send(packet, Prefix=True, serveur="Main", RawBytes=self.b.login)
- self.state = "not"
- self.mstate = 'logIn'
- def change_community(self):
- community = MyPack()
- community.add(self.b.community)
- #community.addint(self.community, 1)
- community.add('\x02')
- self.send(community, Prefix=True, serveur="Main")
- def antiAFK_die(self):
- afk = MyPack(self.b.die)
- afk.add(struct.pack('!l', 1))
- self.send(afk, Prefix=True, serveur="Bulle")
- self.afk_last_time = time.time()
- def DUMMY(self):
- self.dummy_last_time = time.time()
- Pack = MyPack(self.b.login)
- Pack.add('\x00\x02')
- Pack.add('\x1A\x02')
- self.send(Pack, Prefix=True, serveur="Main")
- self.send(Pack, Prefix=True, serveur="Bulle")
- def Parsing(self, packet):
- Packet_type = packet.seek(2)
- if Packet_type == "\x1a\x1b":
- packet_finish = packet.oldProtocolSplit()
- debug('Mice on server: %s'%packet_finish[1], Exit=False)
- debug('MDT: %s'%packet_finish[2], Exit=False)
- debug('CMDTEC: %s'%packet_finish[3], Exit=False)
- self.Main_fingerprint = MainPrefixGen(packet.data)
- try:self.change_community()
- except: debug("Change community error")
- self.mstate = 'ready'
- elif Packet_type == '\x2c\x01':
- data_e = packet.data.split('\x00')
- debug(data_e[0], Exit=False)
- self.Bulle_Connexion(data_e[0], data_e[1])
- self.state = 'logged'
- elif Packet_type == '\x2c\x02':
- p_fin = packet.oldProtocolSplit()
- p_fin = p_fin[0][2:]
- CMDTEC = p_fin[1:11]
- MDT = str(struct.unpack('!h', p_fin[11:]))
- MDT = int(MDT[1:len(MDT)-2])
- self.Bulle_fingerprint = BullePrefixGen(CMDTEC, MDT)
- self.mstate = 'logged'
- self.state = 'logged'
- debug('In Game *-*', Exit=False)
- elif Packet_type == '\x06\x07':
- packet.read(2)
- sent_by_me = not bool(packet.readint(1))
- who = packet.readstring()
- comm = packet.read(1)
- comm = struct.unpack('!b', comm)[0]
- try:whispered = packet.readstring()
- except:whispered = ""
- if not sent_by_me:self.e_private(who, whispered, comm)
- if Packet_type == '\x06\x14':
- msg = packet.oldProtocolSplit()
- self.e_servermessage(msg[1])
- if Packet_type == '\x1A\x05':
- msg = packet.oldProtocolSplit()
- self.e_servermessage(msg[2])
- if Packet_type == '\x1A\x06':
- msg = packet.oldProtocolSplit()
- self.e_servermessage(msg[2])
- if Packet_type == '\x1C\x58':
- msg = packet.oldProtocolSplit()
- self.e_serverrestart(msg[0])
- #@arg1 Array of string -> [username, community]
- #@arg2 Array of string -> [type, argument]
- def functionMsgSplitter(self, arg1, arg2):
- print type(self.command['en'])
- print self.command['en']
- if arg2[0]==self.command['en'][0] or self.command['ru'][0]:
- if len(arg2)==2:self.getModlist(arg1[0], arg2[1])
- else:self.getModlist(arg1[0], arg1[1])
- elif arg2[0]==self.command['en'][1] or self.command['ru'][1]:
- if len(arg2)==2:self.getHelpers(arg1, arg2[1])
- else:self.getHelpers(arg1[0], arg1[1])
- elif arg2[0]==self.command['en'][2] or self.command['ru'][2]:self.getEvent(arg1[0]) #Now one argument
- elif arg2[0]==self.command['en'][3] or self.command['ru'][3]:self.getVersion(arg1[0])
- elif arg2[0]==self.command['en'][4] or self.command['ru'][4]:
- if len(arg2) == '3':self.getBadmap(arg1, arg2[1], arg2[2])
- else:self.getError(arg1[0], args=True)
- elif arg2[0]==self.command['en'][5] or self.command['ru'][5]:
- if len(arg2) == '3':self.getIrc(arg1, arg2[1])
- else:self.getError(arg1[0], args=True)
- #@arg1 String - username
- #@arg2 String - community
- def getModlist(self, arg1, arg2):
- self.returnUnawaible(arg1, 'modlist')
- #@arg1 String - username
- #@arg2 String - community
- def getHelpers(self, arg1, arg2):
- self.returnUnawaible(arg1, 'helpers')
- #@arg1 String - username
- def getEvent(self, arg1):
- self.returnUnawaible(arg1, 'event')
- #@arg1 String - username
- def getVersion(self, arg1):
- self.returnUnawaible(arg1, 'version')
- #@arg1 Array of string - username, community
- #@arg2 String - number
- #@arg3 String - reason
- def getBadmap(self, arg1, arg2, arg3):
- Ircbott.ircSendMessage(Ircbott.ircChannel, '\x038\x02 [Imrubot] Ïëîõàÿ êàðòà äåòåêòåä! Íîìåð: %s, ïîæàëîâàëñÿ: [%s]%s, ïðè÷èíà: %s'%(arg2, arg1[0], arg1[1], arg3))
- self.private(arg1, 'Ñïàñèáî çà ïîìîùü. <3')
- #@arg1 Array os string - username, community
- #@args boolean - Erro type
- #@selector boolean - same
- def getError(self, arg1, args=False, selector=False):
- if args: self.private(arg1, 'Wrong arguments...')
- if selector: self.private(arg1, 'Wrong community...')
- #@arg1 - Array of string - username, community
- #@arg2 - String - text
- def getIrc(self, arg1, arg2):
- Ircbott.ircSendMessage(Ircbott.ircChannel, '\x037\x02> [' + self.community[arg1[0]].upper() + '][' + str(arg1[1]) + '] ' + str(arg2))
- self.private(arg1, 'Æäèòå, âàì îòâåòÿò...')
- #@arg1 String - username
- #@arg2 String - command
- def returnUnawaible(self, arg1, arg2):
- print arg1
- print arg2
- self.private(arg1, 'Êîìàíäà "%s" âðåìåííî íåäîñòóïíà :('%arg2)
- def e_private(self, who, text, comm):
- print who
- print text
- arg1 = []
- arg2 = []
- arg1.append(who); arg1.append(comm)
- arg2.append(text)
- if text == 'make':
- for channels in Ircbott.ircChannels:
- Ircbott.ircSendMessage(channels, '\x0310[TFM] \x0313\x02 [SERVER] The server will restart in 2 minutes')
- #else:Ircbott.ircSendMessage(Ircbott.ircChannel, '\x037\x02> [' + self.community[comm].upper() + '][' + str(who) + '] ' + str(text))
- else:
- print arg2
- if text in self.command['en'] or self.command['ru']:self.functionMsgSplitter(arg1, arg2)
- else:self.private(who, 'Ñåðâèñ âðåìåííî íåäîñòóïåí :(')
- def e_servermessage(self, msg):
- for channels in Ircbott.ircChannels:
- Ircbott.ircSendMessage(channels, msg)
- def e_serverrestart(self, time):
- for channels in Ircbott.ircChannels:
- Ircbott.ircSendMessage(channels, '\x0310[TFM] \x0313\x02 [SERVER] The server will restart in '+str(time)+' minutes')
- def private(self, who, text):
- try:text = text.decode('cp1251').encode('utf-8')
- except:print 'bad charset'
- Pack = MyPack(self.b.chat)
- Pack.addstr(who)
- Pack.addstr(text)
- self.send(Pack, Prefix=True, serveur="Main")
- self.command('c ' + who + '\x20' + text)
- def command(self, str):
- Pack = MyPack(self.b.login)
- Pack.addstr(str)
- self.send(Pack, Prefix=True, serveur="Main")
- def Mainrecv(self):
- data = ''
- try:
- data = self.Main_socket.recv(2*1024)
- except socket.error:
- pass
- self.r_data += data
- if self.r_data != "":
- try:
- packet_size = struct.unpack('!L', self.r_data[:4])[0]
- except:
- self.r_data = ""
- return
- if packet_size <= len(self.r_data):
- p_data = self.r_data[:packet_size]
- self.r_data = self.r_data[packet_size:]
- p = Packet(p_data)
- p.read(4)
- if p.seek(2) == '\x01\x01':
- p.read(4)
- p.setProtocol('old')
- if not (p.seek(2) in ['\x04\x03']):
- pass
- self.Parsing(p)
- def Bullerecv(self):
- data = ''
- if self.mstate == "logged" and time.time()-self.dummy_last_time >= 10:self.DUMMY()
- if self.mstate == "logged" and time.time()-self.afk_last_time >=100:self.antiAFK_die()
- try:
- data = self.Bulle_socket.recv(2*1024)
- except socket.error:
- pass
- self.r_data += data
- if self.r_data != "":
- try:
- packet_size = struct.unpack('!L', self.r_data[:4])[0]
- except:
- self.r_data = ""
- return
- if packet_size <= len(self.r_data):
- p_data = self.r_data[:packet_size]
- self.r_data = self.r_data[packet_size:]
- p = Packet(p_data)
- p.read(4)
- if p.seek(2) == '\x01\x01':
- p.read(4)
- p.setProtocol('old')
- if not (p.seek(2) in ['\x04\x03']):
- pass
- self.Parsing(p)
- if __name__ == '__main__':
- class Start(MyBot):
- def __init__(self, *args, **kwargs):
- MyBot.__init__(self, *args, **kwargs)
- def Okay():
- while True:
- Ircbott.ircListener()
- server = ('37.59.43.48', 443)
- Ircbott = Irc()
- Ircbott.ircConnexion(config.accountData[3], config.accountData[4])
- Ircbott.ircAurh(config.accountData[0], 'password', config.privatechannel, config.channels, config.logchannel)
- IrcTrue = threading.Thread(target=Okay)
- IrcTrue.start()
- bot = Start(config.accountData[0], config.accountData[1], config.accountData[2], 2)
- success = bot.Main_Connexion(server)
- if not success:
- raw_input("Press Enter to continue...")
- sys.exit(1)
- while True:
- time.sleep(0.001)
- if bot.state == 'logged':
- bot.Bullerecv()
- bot.Mainrecv()
- else: bot.Mainrecv()
- if bot.mstate == "ready":
- bot.auth()
- if bot.Main_diconnexion or bot.Bulle_diconnexion:
- time.sleep(15)
- success = bot.connect(server)
- if not success:
- print "error"
- bot.sock.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement