Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- #For 3phasegaming.net
- #BeamNG Made by Dan Jones, MrBill, Brocky, BadSol and tdev
- import socket
- import sys
- import re
- import urllib
- import urllib2
- class IRCClient:
- socket = None
- connected = False
- nickname = 'BeamBot'
- channels = ['#BeamNG']
- def __init__(self):
- self.socket = socket.socket()
- self.socket.connect(('3phasegaming.net', 6667))
- self.send("NICK %s" % self.nickname)
- self.send("USER %(nick)s %(nick)s %(nick)s :%(nick)s" % {'nick':self.nickname})
- links = 0
- self.send("join #beamng")
- self.send("join #dan'shangout")
- self.send("join #tests")
- fun = 1
- def get_data(seed): # function for getting json data on the seed provided
- import urllib2
- response = urllib2.urlopen('http://api.randomuser.me/?seed=' + seed) # fetches the websites data
- html = response.read() # saves the data into a string
- parse_data(html) # sends data to be parse_data
- def parse_data(data): # function that parses the json file recieved
- gender = data.split('gender":"')[1].split('"')[0]
- title = data.split('title":"')[1].split('"')[0]
- fname = data.split('first":"')[1].split('"')[0]
- lname = data.split('last":"')[1].split('"')[0]
- street = data.split('street":"')[1].split('"')[0]
- city = data.split('city":"')[1].split('"')[0]
- state = data.split('state":"')[1].split('"')[0]
- email = data.split('email":"')[1].split('"')[0]
- username = data.split('username":"')[1].split('"')[0]
- password = data.split('password":"')[1].split('"')[0]
- phone = data.split('phone":"')[1].split('"')[0]
- cell = data.split('cell":"')[1].split('"')[0]
- picture = data.split('picture":"')[1].split('"')[0]
- tosay = '\x02Name:\x02 ' + title.title() + ' ' + fname.title() + ' ' + lname.title() + ' \x02Picture:\x02 ' + picture
- tosay = str((tosay))
- self.say((tosay), target)
- while True:
- buf = self.socket.recv(4096)
- lines = buf.split("\n")
- for data in lines:
- data = str(data).strip()
- if data == '':
- continue
- print "I<", data
- # Ping/Pong script
- if data.find('PING') != -1:
- n = data.split(':')[1]
- self.send('PONG :' + n)
- if self.connected == False:
- self.perform()
- self.connected = True
- args = data.split(None, 3)
- if len(args) != 4:
- continue
- ctx = {}
- ctx['sender'] = args[0][1:]
- ctx['type'] = args[1]
- ctx['target'] = args[2]
- ctx['msg'] = args[3][1:]
- names = ctx['sender'].split("!")[0]
- from datetime import datetime
- t = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- # Target
- target = ctx['target']
- if ctx['target'] == self.nickname:
- target = ctx['sender'].split("!")[0]
- #variable for display of name is below
- #name = (ctx['msg'].split(":") [1]) name =
- #(ctx['sender'].split("!") [0])
- user = (target)
- new = (ctx['msg'] + ': ')
- newsay = (ctx['msg'])
- new2 = (ctx['sender'])
- name = (new2.split("!")[0])
- logname = (new2)
- say = (new)
- log = "yes"
- # For URLs, split into only 2 parts instead of individual words
- nick = ctx['sender'].split("!")[0]
- #clear = (ctx['msg'])
- password = '911SECRET'
- password2 = 'FOROPSONLY'
- password3 = ''
- # LOG WRITING
- #self.say("\x02 https://www.google.com/search?q=" + (url.lower())[5:] + "&" + "btnI=I'm+Feeling+Lucky" + '\x02', target)
- if log == "yes":
- if data.find('#beamng') != -1:
- #logged = ("\n |*****Chat Detected: " + '\x02' + (ctx['msg']) + '\x02' + " By IRC user: " + '\x02' + (ctx['sender'].split("!") [0] + "*****|\n"))
- #log = ((ctx['msg']) + '\x02' + " By IRC user: " + '\x02' + (ctx['sender'].split("!") [0]))
- log = (t) + ' ' + (logname) + ": > " + (ctx['msg']) + "\n"
- file = open("BeamNG.txt", "ab+")
- file.write('\n' + (log))
- file.close()
- if data.find('#tests') != -1:
- #logged = ("\n |*****Chat Detected: " + '\x02' + (ctx['msg']) + '\x02' + " By IRC user: " + '\x02' + (ctx['sender'].split("!") [0] + "*****|\n"))
- #log = ((ctx['msg']) + '\x02' + " By IRC user: " + '\x02' + (ctx['sender'].split("!") [0]))
- log = (t) + ' ' + (logname) + ": > " + (ctx['msg']) + "\n"
- file = open("tests.txt", "ab+")
- file.write('\n' + (log))
- file.close()
- # LOG END
- print "\n |*****Chat Detected: " + '\x02' + (ctx['msg']) + '\x02' + " From: " + '\x02' + (ctx['sender'].split("!") [0] + "*****|\n")
- say2 = (say.split(" ")[0])
- # Commands start here
- # Testing PRIVMSG filtering, for special occasions, ops etc
- #respond = ctx['msg']
- if data.find('BeamBot') != -1:
- ctx['msg'] = ctx['msg'].replace(((new)[5:]), 'BeamNG')
- target = '#BeamNG'
- if ctx['msg'].upper().split(" ")[0] == (password):
- self.say((newsay)[10:], target)
- #if ctx['msg'].upper().split(" ")[0] == (password2):
- #self.send((newsay)[10:])
- if data.find('BeamBot') != -1:
- ctx['msg'] = ctx['msg'].replace(((new)[5:]), 'BeamNG')
- target = '#BeamNG'
- if ctx['msg'].upper().split(" ")[0] == (password2):
- self.send((newsay)[10:])
- # Self help section, baiscally i'm kind of tired of the same old questions, so I let the bot do some work
- raw = (data).upper()
- if raw.find('X3DAUDIO1_7.DLL') != -1 and raw.find('MISSING') != -1 :
- self.say('\x02' + (name) + ': ' '\x02' + 'DirectX error: DirectX errors can be resolved by following this link - http://www.microsoft.com/en-us/download/details.aspx?id=35', target)
- # Detect when a user connects, and if they have a tell to read
- if data.find('!') != -1 and data.find('@') != -1 and data.find('#') != -1 and data.find('#BeamNG') != -1 :
- already = "tells/annoy/" + (nick) + ".txt"
- from os import path, access, R_OK
- if path.isfile(already) and access((already), R_OK):
- print "user already recieved warning"
- else:
- from os import path, access, R_OK
- exist = "tells/" + (nick) + ".txt"
- if path.isfile(exist) and access((exist), R_OK):
- self.send('PRIVMSG ' + '#BeamNG ' + '\x02' + (nick) + '\x02 You have tells pending, type !showtells to view them.')
- already1 = "tells/annoy/" + (nick) + ".txt"
- already2 = open((already1), "ab+")
- already2.write('dont annoy him')
- already2.close()
- commandprefix = ("?", "!")
- if ctx['msg'].startswith(commandprefix):
- message = ctx['msg'].split(" ", 1)
- urltuple = ('?YOUTUBE', '?WIKIPEDIA', '?GOOGLE4U', '?GOOGLE4U2', '?GOOGLE', '?URBAN', '?USER')
- command = message[0].upper()
- if command in urltuple:
- if command == '?YOUTUBE':
- self.say("\x02" + "http://www.youtube.com/results?search_query=" + self.delimit(message[1], "+") + "&sm=3" + '\x02', target)
- if command == '?WIKIPEDIA':
- self.say("\x02" + "http://en.wikipedia.org/wiki/" + self.delimit(message[1], "_") + '\x02', target)
- if command == '?GOOGLE4U':
- self.say("\x02" + "http://lmgtfy.com/?q=" + self.delimit(message[1], "+") + '\x02', target)
- if command == '?GOOGLE4U2':
- self.say("\x02" + "http://lmgtfy.com/?q=" + self.delimit(message[1], "+") + '&l=1' '\x02', target)
- if command == '?GOOGLE':
- self.say("\x02" + "http://www.google.com/search?q=" + self.delimit(message[1], "+") + '\x02', target)
- if command == '?URBAN':
- self.say("\x02" + "http://www.urbandictionary.com/define.php?term=" + self.delimit(message[1], "+") + '\x02', target)
- if command == '?USER':
- self.say("http://www.beamng.com/member.php?username=" + self.delimit(message[1], "%20"), target)
- #self.say("\x02 http://www.google.com/webhp#q=" +(url.lower())[7:] + "&btnI", target)
- else:
- if len(message) > 1:
- body = message[1].split()
- else:
- body = [""]
- if command == '?DEBUG':
- # self.say(len(ctx['msg']), target)
- # self.say(len(url5), target)
- # self.say(len(message), target)
- print locals()
- if command == '?LASTORDER' or command == '?LOSTCODE' or command == '?LATESTORDER':
- self.say(self.format(body[0]) + 'To retrieve a lost download please visit http://www.beamng.com/service/latestorder - Check your e-mail for information on your Order ID (if necessary)', target)
- #if command == '?SAY':
- # self.say((newsay)[5:], target)
- if command == '?SERVERTIME':
- self.say((t), target)
- if command == '?PLAYING':
- self.say(self.format(body[0]) + 'For information about playing, see http://wiki.beamng.com/Playing', target)
- if command == '?MAC':
- self.say(self.format(body[0]) + 'Mac users: You cannot play BeamNG natively on OS X. You can however do it through Wine or Parallels.', target)
- if command == '?D3D' or command == '?DIRECTX':
- self.say(self.format(body[0]) + 'DirectX error: DirectX errors can be resolved by following this link - http://www.microsoft.com/en-us/download/details.aspx?id=35', target)
- if command == '?WIKI':
- self.say(self.format(body[0]) + 'The BeamNG Wiki answers a lot of questions you may have: - http://wiki.beamng.com/', target)
- if command == '?FAQ':
- self.say(self.format(body[0]) + 'The FAQ (Frequently Asked Questions) is a useful resource for resolving issues! - http://wiki.beamng.com/BeamNG_FAQ', target)
- if command == '?SYMBOLS':
- self.say(self.format(body[0]) + '[@] - Intended for official BeamNG developers; [%] - Intended for channel operators, A.K.A moderators; [+] - Intended for respected members of the community', target)
- if command == '?DEMO':
- self.say(self.format(body[0]) + 'BeamNG has a free-to-play tech demo, perfect for evaluating the quality of gameplay on your system! - http://www.beamng.com/techdemo', target)
- if command == '?MODS':
- self.say(self.format(body[0]) + 'There are a wide variety of game modifications and new amazing levels made by the community available to download, these are however restricted to members of the alpha stage of BeamNG.', target)
- if command == '?BUGS':
- self.say(self.format(body[0]) + 'A list of known bugs is available at: http://www.beamng.com/threads/1479-List-of-known-bugs-(please-read-before-posting!)', target)
- if command == '?CONTROLLER':
- self.say(self.format(body[0]) + 'Setting up a controler with BeamNG can be difficult. A full list of instructions are available here: http://wiki.beamng.com/Playing#Configuring_your_own_controller', target)
- if command == '?CHANGELOG':
- self.say(self.format(body[0]) + 'A changelog is available here: http://wiki.beamng.com/Changelog', target)
- if command == '?ALPHA':
- self.say(self.format(body[0]) + 'The Alpha version of BeamNG is available for purchase by following this link: http://beamng.com/store', target)
- if command == '?VEHICLES':
- self.say(self.format(body[0]) + 'Downloadable vehicles are available here (Alpha users only): http://www.beamng.com/forums/26-Vehicles', target)
- if command == '?MAPS':
- self.say(self.format(body[0]) + 'Downloadable maps are avaiable here (Alpha users only): http://www.beamng.com/forums/27-Terrains', target)
- if command == '?FOLDER':
- self.say(self.format(body[0]) + 'To access the BeamNG folder, press your Windows key + R key and type this: %userprofile%\\appdata\local\BeamNG\BeamNG-DRIVE-0.3', target)
- if command == '?CPU':
- self.say(self.format(body[0]) + 'To check what CPU you have, visit this site: http://www.wikihow.com/Tell-What-Kind-of-Processor-You-Have', target)
- if command == '?GPU':
- self.say(self.format(body[0]) + 'To check what GPU you have, visit this site: http://www.wikihow.com/Find-Out--What-Graphics-Card-You-Have', target)
- if command == '?CONTACT':
- self.say(self.format(body[0]) + 'Contacting the BeamNG team will allow certain issues to be fixed directly! - http://www.beamng.com/contactus/', target)
- if command == '!SHOWTROLLS':
- with open ("trolls.txt", "r") as myfile:
- troll=myfile.read().replace('\n', ' ')
- self.say('Trolls: ' + (troll), target)
- if command == '!LINECOUNT':
- count = 0
- textfile = open('BeamNG.txt', 'r')
- file = textfile
- for line in file:
- count += 1
- file.close()
- count = str((count))
- self.say('The log is ' + count + ' lines big', target)
- if command == '?ANNOUNCEMENT':
- html = self.webrequest('http://www.beamng.com')
- announce = self.htmlfind(html, '<b>', '</b>')
- self.say((announce), target)
- if command == '!LINKS':
- if data.find('daniel_j') != -1:
- if links == 0:
- self.say('Links now enabled.', target)
- links = 1
- else :
- self.say('Links now disabled.', target)
- links = 0
- else:
- print "nope"
- if command == '!FUN':
- if data.find('daniel_j') != -1:
- if fun == 0:
- self.say('Fun enabled.', target)
- fun = 1
- else :
- self.say('Fun now disabled.', target)
- fun = 0
- else:
- print "nope"
- if command == '?WHUT':
- if fun == 1:
- import random
- s_nouns = ["A dude", "My mom", "The king", "Some guy", "A cat with rabies", "A sloth", "Your homie", "This cool guy my gardener met yesterday", "Superman"]
- p_nouns = ["These dudes", "Both of my moms", "All the kings of the world", "Some guys", "All of a cattery's cats", "The multitude of sloths living under your bed", "Your homies", "Like, these, like, all these people", "Supermen"]
- s_verbs = ["eats", "kicks", "gives", "treats", "meets with", "creates", "hacks", "configures", "spies on", "retards", "meows on", "flees from", "tries to automate", "explodes"]
- p_verbs = ["eat", "kick", "give", "treat", "meet with", "create", "hack", "configure", "spy on", "retard", "meow on", "flee from", "try to automate", "explode"]
- infinitives = ["to make a pie.", "for no apparent reason.", "because the sky is green.", "for a disease.", "to be able to make toast explode.", "to know more about archeology.", "because daniel_j is awesome", "to hack the database"]
- random = random.choice(s_nouns), random.choice(s_verbs), random.choice(s_nouns).lower() or random.choice(p_nouns).lower(), random.choice(infinitives)
- random = str(random).replace('(', "")
- random = str(random).replace(')', "")
- random = str(random).replace("'", "")
- random = str(random).replace(",", "")
- self.say((random), target)
- if len(message) <= 1:
- break
- ####################################################################################################################################################################################################################################
- ########### Commands below this line will NOT work without arguments. If you need a command that works without an argument, add it ABOVE this line. #######################################################################
- ####################################################################################################################################################################################################################################
- if command == '!ADD':
- file = open("trolls.txt", "ab+")
- file.write(' ' + (body[0]))
- file.close()
- self.say('Added \x02' + (body[0]) + '\x02 to troll list.', target)
- if command == '!REMOVE':
- self.say('Removed \x02' + (body[0]) + '\x02 from troll list.', target)
- import fileinput
- files = "trolls.txt"
- for line in fileinput.input(files, inplace = 1):
- print line.replace((body[0]), ""),
- # Tell system tests
- if command == '!TELL':
- from os import path, access, R_OK
- exist = "tells/" + (body[0]) + ".txt"
- if path.isfile(exist) and access((exist), R_OK):
- self.say('\x02' + (body[0]) + '\x02 already has a message to read!', target)
- else:
- from datetime import datetime
- t = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- length = len(body[0])
- flength = 6 + (length)
- tell = open((exist), "ab+")
- tell.write((ctx['msg'][(flength):]) + ' - From: \x02' + (name) + '\x02 - ' + (t))
- tell.close()
- self.say("I'll tell " + (body[0]) + ' that.', target)
- if command == '!COUNT':
- count = 0
- textfile = open('BeamNG.txt', 'r')
- file = textfile
- for line in file:
- if (body[0]) in line:
- count += 1
- file.close()
- count = str((count))
- self.say((body[0]) + ' said ' + (count) + ' times', target)
- if (command == '?REG' or command == '?ACTIVE' or command == '?ACTIVATED'):
- values = { 'username' : message[1] }
- html = self.encodeurl("http://www.beamng.com/member.php", values)
- reg = self.htmlfind(html, '<span class="rank">', '</span>')
- rank = self.htmlfind(html, '<span class="usertitle">', '</span>')
- if reg.find('supporter') != -1 or rank.find('Developer') != -1 or rank.find('Vehicle Artist') != -1:
- self.say('\x0309,01\x02' + (message[1]) + "'s\x02\x0f account \x0309,01\x02IS\x02\x0f activated.", target)
- else:
- self.say('\x0304,01\x02' + (message[1]) + "'s\x02\x0f account \x0304,01\x02NOT\x02\x0f activated.", target)
- # if command == '!D':
- # word = self.delimit(message[1], "+")
- # link = "http://www.thefreedictionary.com/" + (word)
- # response = urllib2.urlopen(link)
- # html = response.read()
- # begin = html.find('<div class="ds-single">')
- # end = html.find('</div>',begin)
- # defi = html[begin+len('<div class="ds-single">'):end].strip()
- # if len(defi) > 100 or defi.find('<') != -1:
- # self.say((word) + ' not found.', target)
- # else:
- # self.say((defi), target)
- if command == '!D':
- if fun == 1:
- try:
- html = self.webrequest("http://www.oxforddictionaries.com/definition/english/" + urllib.quote(message[1]))
- defi = self.htmlfind(html, 'definition">', '</span>')
- # defi.replace('[','')
- # defi.replace(']','')
- # defi.replace(''',"'")
- # defi.replace('"','"')
- # defi = defi.split('<')[0]
- # defi = defi[:-1]
- if len(defi) > 199:
- defi = defi[:200]
- defi = (defi) + ' (.....)'
- print((defi))
- if len(defi) > 400 or defi.find('BLIC') != -1:
- self.say('\x02"' + (message[1]) + '"\x02' + ' not found in the dictionary.', target)
- else:
- self.say('\x02' + (message[1]) + ':\x02 ' +(defi), target)
- except urllib2.HTTPError, error:
- print error
- except:
- print "Error:", sys.exc_info()
- self.say('\x02"' + (message[1]) + '"\x02' + ' not found in the dictionary.', target)
- if command == '?WHOIS':
- if fun == 1:
- values = { 'username' : message[1] }
- html = self.encodeurl('http://www.beamng.com/member.php', values)
- join = self.htmlfind(html, '<dd>', '</dd>')
- title = self.htmlfind(html, '<title>', '</title>')
- friends = self.htmlfind(html, '<span class="friends_total">', '</span>')
- rank = self.htmlfind(html, '<span class="usertitle">', '</span>')
- if friends == "-1":
- if rank == "-1" :
- self.say("Account doesn't exist", target)
- #self.say((title), target)
- else:
- self.say('\x02' + (message[1]) + '\x02 joined the forums on \x02' + (join) + '\x02 and is a \x02' + (rank) + '\x02.', target)
- else:
- if rank == "-1" :
- self.say("Account doesn't exist", target)
- #self.say((title), target)
- else:
- self.say('\x02' + (message[1]) + '\x02 has \x02' + (friends) + ' \x02friends. \x02' + (message[1]) + '\x02 joined the forums on \x02' + (join) + '\x02 and is a \x02' + (rank) + '\x02.', target)
- # Now i'm just duplicating bots from #offtopic
- if command == '!FACT':
- try:
- response = urllib2.urlopen('http://numbersapi.com/' + message[1]) # fetches the websites data
- html = response.read() # saves the data into a string
- self.say((html), target) # print the fact to irc
- except:
- print 'nope'
- if command == '!REMEMBER':
- from os import path, access, R_OK
- remember = "remember/" + (body[0]) + ".txt"
- if path.isfile(remember) and access((remember), R_OK):
- self.say('\x02' + (body[0]) + '\x02 already has a definition, remembering yours instead.', target)
- import os
- os.remove((remember))
- length = len(body[0])
- flength = 10 + (length)
- remember = open((remember), "ab+")
- remember.write((ctx['msg'][(flength):]))
- remember.close()
- else:
- length = len(body[0])
- flength = 10 + (length)
- remember = open((remember), "ab+")
- remember.write((ctx['msg'][(flength):]))
- remember.close()
- self.say("I'll remember that.", target)
- def tosay(tosay):
- self.say((tosay), target)
- # if command == '!CLEVER':
- # from chatterbotapi import ChatterBotFactory, ChatterBotType
- # import time
- # factory = ChatterBotFactory()
- # bot1 = factory.create(ChatterBotType.CLEVERBOT)
- # bot1session = bot1.create_session()
- # bot2 = factory.create(ChatterBotType.PANDORABOTS, 'b0dafd24ee35a477')
- # bot2session = bot2.create_session()
- # s = self.delimit(message[1], " ")
- # s = bot2session.think(s);
- # time.sleep(2)
- # two = (s)
- # self.say((two), target)
- # s = bot1session.think(s);
- if command == '!GERMAN':
- values = { 'src' : 'fr',
- 'dest' : 'de',
- 'text' : message[1],
- 'email' : 'danj.scripter@gmail.com',
- 'password' : 'five12' }
- html = self.encodeurl('http://syslang.com/', values)
- trans = self.htmlfind(html, '<translation>', '</translation>')
- self.say((trans), target)
- if command == '!GERMAN2ENGLISH':
- values = { 'src' : 'de',
- 'dest' : 'en',
- 'text' : message[1],
- 'email' : 'danj.scripter@gmail.com',
- 'password' : 'five12' }
- html = self.encodeurl('http://syslang.com/', values)
- trans = self.htmlfind(html, '<translation>', '</translation>')
- self.say((trans), target)
- if command == '!CONVO':
- try:
- if fun == 1:
- print "doing"
- values = { 'say' : message[1],
- 'bot_id' : '10',
- 'convo_id' : '661413365323256456' }
- html = self.encodeurl('http://api.program-o.com/v2.3.1/chatbot/', values)
- say = self.htmlfind(html, 'botsay":"', '"}')
- say = urllib.unquote(say)
- print (say)
- self.say((say), target)
- except urllib2.HTTPError, error:
- print error
- except:
- print "error:", sys.exc_info()
- if command == '!RUSSIAN':
- values = { 'src' : 'fr',
- 'dest' : 'ru',
- 'text' : message[1],
- 'email' : 'danj.scripter@gmail.com',
- 'password' : 'five12' }
- html = self.encodeurl('http://syslang.com/', values)
- trans = self.htmlfind(html, '<translation>', '</translation>')
- self.say((trans), target)
- if command == '!GIS':
- html = self.webrequest("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + self.delimit(message[1], "%20"))
- image = self.htmlfind(html, '"unescapedUrl":"', '","')
- self.say((image), target)
- if command == '!GOOGLE':
- if fun == 1:
- from pygoogle import pygoogle
- g = pygoogle((self.delimit(message[1], " ")))
- g.pages = 1
- say = g.get_urls()
- say = str(say).split(',')[0]
- say = say.replace("[u'", "")
- say = say.replace("'", "")
- self.say((say), target)
- if say.find('www.youtube.com/watch?v=') != -1 :
- if data.find('results?search') != -1 or data.find('/user') != -1 :
- print "nope"
- else:
- fresh = (say)
- try:
- html = self.webrequest(fresh)
- title = self.htmlfind(html, '<title>', '</title>')
- title = title.replace(" - YouTube", "")
- user = self.htmlfind(html, '<link itemprop="url" href="http://www.youtube.com/user/', '">')
- user = self.ytconstruct(user, ' \x02By:\x02 ')
- views = self.htmlfind(html, 'span class="watch-view-count " >', '</span>')
- views = views.replace("Aufrufe", "")
- #my system isn't German, strip "views" from output as well
- views = views.replace("views", "")
- views = self.ytconstruct(views, ' \x02Views:\x02 ')
- likes = self.htmlfind(html, 'span class="likes-count">', '</span>')
- likes2 = float(likes.replace(".", ""))
- # likes2 = float(likes.replace(",", ""))
- likes = self.ytconstruct(likes, ' \x02Likes:\x02 ')
- dislikes = self.htmlfind(html, 'span class="dislikes-count">', '</span>')
- dislikes2 = float(dislikes.replace(".", ""))
- # dislikes2 = float(dislikes.replace(",", ""))
- dislikes = self.ytconstruct(dislikes, ' \x02Dislikes:\x02 ')
- date = self.htmlfind(html, 'class="watch-video-date" >', '</span>')
- date = self.ytconstruct(date, ' \x02Uploaded:\x02 ')
- total = likes2+dislikes2
- if total > 0:
- final = round(((likes2/total)*100), 2)
- final = self.ytconstruct(str(final), ' \x02Recommended:\x02 ')
- final = final + '%'
- else:
- final = ""
- print title
- print user
- views = views.replace('.', ',')
- likes = likes.replace('.', ',')
- dislikes = dislikes.replace('.', ',')
- self.say('\x02\x0301,00You\x0300,04Tube' + '\x0f - \x02Title: \x02' + self.symboldecode(title, 14) + (user) + (date) + (views) + (likes) + (dislikes) + (final), target)
- final, likes2, dislikes2 = -1, -1, -1
- except urllib2.HTTPError, error:
- print error
- except:
- print "Error:", sys.exc_info()
- self.say("\x02Whoops, page error 404, that's bad isn't it? \x02", target)
- if command == '!RUSSIAN2ENGLISH':
- values = { 'src' : 'ru',
- 'dest' : 'en',
- 'text' : urllib.quote(message[1]),
- 'email' : 'danj.scripter@gmail.com',
- 'password' : 'five12' }
- html = self.encodeurl('http://syslang.com/', values)
- trans = self.htmlfind(html, '<translation>', '</translation>')
- self.say((trans), target)
- if command == '!NORWAY':
- values = { 'src' : 'fr',
- 'dest' : 'no',
- 'text' : urllib.quote(message[1]),
- 'email' : 'danj.scripter@gmail.com',
- 'password' : 'five12' }
- html = self.encodeurl('http://syslang.com/', values)
- trans = self.htmlfind(html, '<translation>', '</translation>')
- self.say((trans), target)
- if command == '!NORWAY2ENGLISH':
- values = { 'src' : 'no',
- 'dest' : 'en',
- 'text' : message[1],
- 'email' : 'danj.scripter@gmail.com',
- 'password' : 'five12' }
- html = self.encodeurl('http://syslang.com/', values)
- trans = self.htmlfind(html, '<translation>', '</translation>')
- self.say((trans), target)
- if command == '!WIKI':
- try:
- import re
- values = { 'search' : message[1],
- 'go' : 'Go' }
- html = self.encodeurl("http://en.wikipedia.org/wiki/Special:Search", values)
- n = self.htmlfind(html, '<p>', '.')
- n = self.symboldecode(n, 3)
- q = re.compile(r'<.*?>', re.IGNORECASE)
- a = re.sub(q, '', n)
- a = a + '.'
- if a.find('may refer to') != -1:
- whut()
- self.say((a), target)
- except urllib2.HTTPError, error:
- print error
- except:
- print "Error:", sys.exc_info()
- self.say((message[1]) + ' not found.', target)
- if command == '!RANDOM':
- seed = self.delimit(message[1], " ")
- get_data(seed)
- if command == '!W':
- if fun == 1:
- try:
- values = { 'query' : message[1] }
- html = self.encodeurl("http://www.wund.com/cgi-bin/findweather/getForecast", values)
- con = self.htmlfind(html, '<h4>', '</h4>')
- temp = self.htmlfind(html, "<h3>\n <span>", '</span>')
- real = self.htmlfind(html, '<h1>', '</h1>')
- if con == "-1":
- self.say((message[1]) + ': not found', target)
- else:
- temp = temp.split('.')[0]
- f = ((float((temp)) * 9) / 5 + 32)
- f = str((f))[:5]
- self.say('\x02' + (real) +':\x02 currently: ' + (con) + ', ' + str((temp)) + '°C/' + str((f)) + '°F', target)
- except urllib2.HTTPError, error:
- self.say((message[1]) + ': not found', target)
- print error
- except:
- self.say((message[1]) + ': not found', target)
- print "Error:", sys.exc_info()
- if command == '!WHOIS':
- if fun == 1:
- remember = "remember/" + (body[0]) + ".txt"
- from os import path, access, R_OK
- if path.isfile(remember) and access((remember), R_OK):
- from os import path, access, R_OK
- if path.isfile(remember) and access((remember), R_OK):
- with open ((remember), "r") as yourwho:
- with open ((remember), "r") as yourtell:
- yourwho2=yourwho.read().replace('\n', ' ')
- self.say('\x02' + (body[0]) + '\x02' + (yourwho2), target)
- else:
- self.say('\x02' + (body[0]) + '\x02 has no definition!', target)
- if command == '!T':
- try:
- values = { 'query' : message[1] }
- html = self.encodeurl("http://www.wunderground.com/cgi-bin/findweather/getForecast", values)
- time = self.htmlfind(html, 'id="infoTime"><span>', '</span>')
- real = self.htmlfind(html, '<title>', 'Fore')
- if real == "-1":
- self.say((message[1]) + ': not found', target)
- print((time))
- else:
- if time == "-1":
- time = 'HAMMER TIME!!'
- self.say('\x02' + (real) +':\x02 currently: ' + (time), target)
- except urllib2.HTTPError, error:
- print error
- except:
- print "Error:", sys.exc_info()
- #Major issues in this block
- #****************************************************************************************
- if data.find('PRIVMSG') != -1:
- #try:
- # import urllib2
- # import json
- # single = ctx['msg'].split(' ')[0]
- # req = urllib2.Request("http://ws.detectlanguage.com/0.2/detect?q=" + (single) + "&key=0708589d1ac3e7304aa3ecb96ed20f68")
- # opener = urllib2.build_opener()
- # f = opener.open(req)
- # json = json.loads(f.read())
- # json = str((json))
- # json = json.split("language': u'")[1]
- # json = json.replace(']','')
- # json = json.replace('}','')
- # json = json.replace("'",'')
- # print json
- # if json.find('en') != -1:
- # print 'english'
- # else:
- # import urllib2
- # link = "http://syslang.com/?src=" + (json) + "&dest=en&text=" + (newsay) + "&email=danj.scripter@gmail.com&password=five12"
- # req = urllib2.Request((link))
- # req.add_header('User-agent', 'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/0.9.7e')
- # res = urllib2.urlopen(req)
- # html = res.read()
- # begin = html.find('<translation>')
- # end = html.find('</translation>',begin)
- # trans = html[begin+len('<translation>'):end].strip()
- # #self.say((trans), target)
- # except:
- # print "unknown language"
- print "has tell?"
- from os import path, access, R_OK
- exist = "tells/" + (nick) + ".txt"
- if path.isfile(exist) and access((exist), R_OK):
- print "has tell!"
- exist = "tells/" + (nick) + ".txt"
- with open ((exist), "r") as yourtell:
- print (exist)
- with open ((exist), "r") as yourtell:
- yourtell2=yourtell.read().replace('\n', ' ')
- self.send("NOTICE " + (nick) + " " + (yourtell2))
- already = "tells/annoy/" + (nick) + ".txt"
- import os
- os.remove((exist))
- # if data.find('PRIVMSG') != -1:
- # if data.find('.com') != -1 or data.find('.org') != -1 or data.find('.net') != -1:
- # try:
- # urllink = data.split('www.')[1]
- # if urllink.find(' ') != -1:
- # urllink = urllink.split(' ')[0]
- # urllink = 'www.' + urllink
- # file = open('urls.txt', 'r+')
- # for line in file:
- # try:
- # if urllink == line.split('-')[0].replace(' ', ''):
- # self.say((line).split('- ')[1], target)
- # break
- # error()
- # except:
- # pass
- # file = open('urls.txt', 'ab+')
- # file.write('\n' + (urllink) + ' - ^ This was linked by ' + (ctx['sender']).split('!')[0] + ' already.')
- # file.close()
- # except:
- # pass
- if data.find('www.youtube.com/watch?v=') != -1 :
- if data.find('results?search') != -1 or data.find('/user') != -1 :
- print "nope"
- else:
- list = (data).split()
- for word in list:
- if 'www.youtube.com' in word :
- word1 = word.split()
- print word1
- for fresh in word1:
- if 'www.youtube.com' in fresh :
- print fresh
- if fresh.startswith(':'):
- fresh = fresh[1:]
- try:
- html = self.webrequest(fresh)
- title = self.htmlfind(html, '<title>', '</title>')
- title = title.replace(" - YouTube", "")
- user = self.htmlfind(html, 'data-name="watch">', '</a>')
- user = self.ytconstruct(user, ' \x02By:\x02 ')
- views = self.htmlfind(html, 'span class="watch-view-count">', '</span>')
- views = views.replace("Aufrufe", "")
- #my system isn't German, strip "views" from output as well
- views = views.replace("views", "")
- views = self.ytconstruct(views, ' \x02Views:\x02 ')
- likes = self.htmlfind(html, 'span class="likes-count">', '</span>')
- # likes2 = float(likes.replace(".", ""))
- likes2 = float(likes.replace(",", ""))
- likes = self.ytconstruct(likes, ' \x02Likes:\x02 ')
- dislikes = self.htmlfind(html, 'span class="dislikes-count">', '</span>')
- # dislikes2 = float(dislikes.replace(".", ""))
- dislikes2 = float(dislikes.replace(",", ""))
- dislikes = self.ytconstruct(dislikes, ' \x02Dislikes:\x02 ')
- date = self.htmlfind(html, '<strong>Uploaded on ', '</strong>')
- if date == "-1":
- date = self.htmlfind(html, '<strong>Published on ', '</strong>')
- date = self.ytconstruct(date, ' \x02Uploaded:\x02 ')
- total = likes2+dislikes2
- if total > 0:
- final = round(((likes2/total)*100), 2)
- final = self.ytconstruct(str(final), ' \x02Recommended:\x02 ')
- final = final + '%'
- else:
- final = ""
- print title
- print user
- views = views.replace('.', ',')
- likes = likes.replace('.', ',')
- dislikes = dislikes.replace('.', ',')
- self.say('\x02\x0301,00You\x0300,04Tube' + '\x0f - \x02Title: \x02' + self.symboldecode(title, 14) + (user) + (views) + (likes) + (dislikes) + (final), target)
- final, likes2, dislikes2 = -1, -1, -1
- except urllib2.HTTPError, error:
- print error
- except:
- print "Error:", sys.exc_info()
- if links == 1:
- if data.find('http://') != -1 :
- list = (data).split(" ")
- for word in list:
- if 'http://' in word :
- word1 = word.split(" ")
- print word1
- for fresh in word1:
- if 'http://' in fresh :
- print fresh
- if fresh.startswith(':'):
- fresh = fresh[1:]
- try:
- html = self.webrequest(fresh)
- title = self.htmlfind(html, '<title>', '</title>')
- title = self.symboldecode(title, 14)
- if title == "-1":
- print "nope"
- else :
- if fresh.find('youtube') != -1 or fresh.find('.jpeg') != -1:
- print "youtube link, or something idk screw you"
- else:
- self.say('Title: \x02' + (title) + '\x02', target)
- except urllib2.HTTPError, error:
- print error
- except:
- print "Error:", sys.exc_info()
- html = None
- #****************************************************************************************
- def send(self, msg):
- print "I>",msg
- self.socket.send(msg+"\r\n")
- def say(self, msg, to):
- self.send("PRIVMSG %s :%s" % (to, msg))
- def delimit(self, string, delimiter):
- delimited = string.replace(' ', delimiter).lower()
- return delimited
- def format(self, string):
- if len(string) > 0:
- nickname = "\x02" + string + ":\x02 "
- else:
- nickname = ""
- return nickname
- def encodeurl(self, link, values):
- headers = { 'User-Agent' : 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Win64; x64; Trident/5.0)',
- 'Accept-Language' : 'en-US' }
- values = urllib.urlencode(values)
- req = urllib2.Request(link, values, headers)
- html = self.webrequest(req)
- return html
- def webrequest(self, link):
- response = urllib2.urlopen(link) #link in this case could refer to the encoded URL data from function above
- html = response.read()
- return html
- def htmlfind(self, html, begin, end):
- string = html[html.find((begin))+len(begin):html.find((end), html.find(begin))]
- if html.find((begin)) == -1:
- string = "Lost data"
- if type(string) == str:
- string = string.strip()
- return string
- def ytreplace(self, string, period):
- chars = { "<" : "", ">" : "", " " : "", "/" : "", "\n" : "" }
- for key,value in chars.item():
- string = string.replace(key, value)
- if period == 1:
- string = string.replace(".", ",")
- return string
- def ytconstruct(self, string, prefix):
- if string != "-1":
- string = prefix + string
- else:
- string = ""
- return string
- def symboldecode(self, string, option):
- htmlcodes = { '"' : '"', '&' : '&', '<' : '<', '>' : '>', ' ' : ' ', '¡' : '¡', '¢' : '¢', '£' : '£', '¤' : '¤', '¥' : '¥', '¦' : '¦', '§' : '§', '¨' : '¨', '©' : '©', 'ª' : 'ª', '«' : '«', '¬' : '¬', '®' : '®', '¯' : '¯', '°' : '°', '±' : '±', '²' : '²', '³' : '³', '´' : '´', 'µ' : 'µ', '¶' : '¶', '·' : '·', '¸' : '¸', '¹' : '¹', 'º' : 'º', '»' : '»', '¼' : '¼', '½' : '½', '¾' : '¾', '¿' : '¿' }
- removechars = { "<" : "", ">" : "", " " : "", "/" : "", "\n" : "" }
- formatcodes = { '<b>' : '\x02', '</b>' : '\x02', '<i>' : '\\x09', '</i>' : '\\x09', '<u>' : '\x15', '</u>' : '\x15' }
- htmlnum = { ' ' : ' ', '!' : '!','"' : '\"', '#' : '#', '$' : '$', '%' : '%', '&' : '&', ''' : "\'", '(' : '(', ')' : ')', '*' : '*', '+' : '+', ',' : ',', '-' : '-', '.' : '.', '/' : '/', ':' : ':', ';' : ';', '<' : '<','=' : '=','>' : '>', '?' : '?', '&64;' : '@', '[' : '[', '\' : '\\', ']' : ']', '^' : '^', '_' : '_', '`' : '`', '{' : '{', '|' : '|', '}' : '}', '~' : '~', ' ' : ' ', '¡' : '¡', '¢' : '¢', '£' : '£', '¤' : '¤', '¥' : '¥', '¦' : '¦', '§' : '§', '¨' : '¨', '©' : '©', 'ª' : 'ª', '«' : '«', '¬' : '¬', '­' : '', '®' : '®','¯' : '¯', '°' : '°', '±' : '±', '²' : '²', '³' : '³', '´' : '´', 'µ' : 'µ', '¶' : '¶', '·' : '·', '¸' : '¸', '¹' : '¹', 'º' : 'º', '»' : '»', '¼' : '¼', '½' : '½', '¾' : '¾', '¿' : '¿' }
- combined = ( None, htmlcodes, removechars, formatcodes, htmlnum)
- print option
- if len(str(abs(option))) == 1:
- print combined[option]
- repldict = combined[option]
- elif len(str(abs(option))) > 1 and len(str(abs(option))) < 10:
- firstopt = option / 10
- secondopt = option % 10
- repldict = combined[firstopt]
- repldict.update(combined[secondopt])
- elif len(str(abs(option))) > 10 and len(str(abs(option))) < 1000:
- thirdopt = option % 10
- firstopt = option / 100
- secondopt = (option/10) % 10
- repldict = combined[firstopt]
- repldict.update(combined[secondopt])
- repldict.update(combined[thirdopt])
- else:
- print "invalid option"
- for key,value in repldict.items():
- string = string.replace(key, value)
- return string
- def perform(self):
- #self.send("PRIVMSG R : Register <>")
- self.send("PRIVMSG R : Login <>")
- self.send("MODE %s +x" % self.nickname)
- for c in self.channels:
- self.send("JOIN %s" % c)
- IRCClient()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement