Pastebin

lintukoto oraakkeli

lintukoto oraakkeli from Pastebin

Lintukoto oraakkeli Pastebin
    
        #!/usr/bin/env python
# coding=utf-8
"""
Ylilaudan "psykoosibotti" :--D Sori en oo siivonnu koodia yhtään ja lisäksi tää on mun ensimmäinen pythoni-scripti. Hämmentävä kieli javascriptin jälkeen. 
Seuraava bottiscriptini on vähän viisaammin tehty, julkaisen senkin kuhan jaksan. 
Tämä aiheuttaa jäätävää peppukipua kanssanyymeissä hölmöillä viesteillään.
"""
#koiramies kiittää ja kuittaa :)

import dryscrape, re
from bs4 import BeautifulSoup
import getpass
import random
from random import randint
import time
import sys
import urllib
import os
from PIL import Image
import PIL.ImageOps 
from PIL import ImageFilter

reload(sys)
sys.setdefaultencoding('utf-8')
url="https://ylilauta.org/satunnainen/"
from requests import get
times = raw_input("Monta kertaa postaillaan: ")
username = raw_input("Käyttäjätunnus:")
passw = getpass.getpass('Salasana:' )
#kirjaudutaan sisään
session = dryscrape.Session()
session.set_error_tolerant(True)

oldImage = ""
pngOrJpg = ".jpg"

messagesdone = 0

answered =[]

try:
	session.visit(url)

	name = session.at_xpath('//*[@name="username"]')
	name.set(username)
	password = session.at_xpath('//*[@name="password"]')
	password.set(passw)
	# Push the button
	name.form().submit()
	response = session.body()
	soup = BeautifulSoup(response)
	print soup.findAll(text=re.compile('Kirjautuneena'))
except:
	print 'Error in page load when loggin in'
	
def psykoosibotti(teksti):
	#split words
	print "splitting words.."
	teksti.split(' ')
	
	
	
def smart_truncate(content, length=95):
    if len(content) <= length:
        return content
    else:
        return ' '.join(content[:length+1].split(' ')[0:-1])
        
        
def remove_transparency(im, bg_colour=(255, 255, 255)):

    if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
        alpha = im.convert('RGBA').split()[-1]
        bg = Image.new("RGBA", im.size, bg_colour + (255,))
        bg.paste(im, mask=alpha)
        return bg

    else:
        return im
        
#-------------------------------------------------------
for x in range(0, int(times)):
	try:
		try:
			os.remove(os.path.dirname(os.path.realpath(__file__))+"/img/"+oldImage+"_inverted"+pngOrJpg)
			os.remove(os.path.dirname(os.path.realpath(__file__))+"/img/"+oldImage+pngOrJpg)
		except:
			print "didnt find old image"
			
		#50/50 to go to frontpage or some other
		if randint(0,10) > 5:
			session.visit("https://ylilauta.org/satunnainen-"+str(randint(2,3)))
		else:
			session.visit(url)
		response = session.body()
		soup = BeautifulSoup(response)
		
		# check for all threads
		threads = soup.findAll("div", {"class": "thread"})
		
		#get random post
		randomid = randint(0, len(threads)-1)
		thread = threads[randomid]
		post = thread.find("div", {"class":"op_post"})
		
		#katotaan onko botin ite tekemä threadi tms
		postedMyself =  post.find("a", {"class":"icon-trash2"})
		if postedMyself:
			raise ValueError('oma viesti.. ei vastata')
			 
		
		author =  post.find("a", {"class":"postnumber"}).get_text()
		authorModified =  re.sub("\D", "", author)
		
		if authorModified in answered:
			raise ValueError("viestiin on jo vastattu kerran")
		
		#get posts content/message
		message = post.find("blockquote")
		messageText = post.find("div", {"class":"postcontent"}).get_text()
		
		#shorten it
		print "message length: "+ str(len(messageText))
		if len(messageText) > 95:
			messageText = smart_truncate(messageText, 95)
			#print messageText
		print "new length: "+ str(len(messageText))
		if len(messageText) == 0:
			messageText = "moro olen kissa koira random botti moro moro"
			
		#lapot pois
		if "=)" in messageText:
			raise ValueError('pedarisuoja aktivoitu')
		
		if "Testing" in messageText:
			raise ValueError('pedarisuoja aktivoitu')
		
		#get the post image and modify it
		try:
			image =  post.find("img", {"class":"imagefile"})
			imgcleaned1 = str(image)[str(image).find('src'):]
			imgcleaned2 = imgcleaned1[14:]
			imgcleaned3 = "i"+imgcleaned2[:-6]
			try:
				urllib.urlretrieve("https://"+imgcleaned3+"jpg", "img/"+authorModified+".jpg")
				#print imgcleaned3+"jpg"
				pngOrJpg = ".jpg"
				image = Image.open("img/"+authorModified+pngOrJpg)
				print "image type jpg"
			except:
				urllib.urlretrieve("https://"+imgcleaned3+"png", "img/"+authorModified+".png")
				#print imgcleaned3+"png"
				pngOrJpg = ".png"
				image = Image.open("img/"+authorModified+pngOrJpg)
				print "image type png"
			try:
				image = remove_transparency(image)
				image = image.convert('RGB')
				"""
				inverted_image = PIL.ImageOps.invert(image)
				if randint(0,10) > 5:
					inverted_image = PIL.ImageOps.flip(inverted_image)
				if randint(0,10) > 5:
					inverted_image = PIL.ImageOps.mirror(inverted_image)
				inverted_image = PIL.ImageOps.posterize(inverted_image,int(randint(3, 6)))
				inverted_image = PIL.ImageOps.autocontrast(inverted_image, int(randint(0, 40)))			
				inverted_image = PIL.ImageOps.solarize(inverted_image,int(randint(0, 45)))
				if randint(0,10) > 8:
					inverted_image = inverted_image.filter(ImageFilter.BLUR)
					
				if randint(0,10) > 8:
					inverted_image = inverted_image.filter(ImageFilter.EDGE_ENHANCE_MORE)
				"""
				inverted_image = PIL.ImageOps.invert(image)
				#inverted_image = PIL.ImageOps.flip(inverted_image)
				inverted_image = PIL.ImageOps.mirror(inverted_image)
				inverted_image = PIL.ImageOps.posterize(inverted_image,5)
				inverted_image = PIL.ImageOps.autocontrast(inverted_image, 40)			
				inverted_image = PIL.ImageOps.solarize(inverted_image,80)
				inverted_image = inverted_image.filter(ImageFilter.BLUR)
				inverted_image = inverted_image.filter(ImageFilter.EDGE_ENHANCE_MORE)
	
				inverted_image = PIL.ImageOps.fit(inverted_image, (666,666))
				meter = -1
				for i in range( inverted_image.size[0] ):
					for j in range( inverted_image.size[1] ):
						if i < int(inverted_image.size[0]):
							if meter < int(inverted_image.size[0])/2:
								meter+=1
							if randint(0,100) > 60:
								inverted_image.putpixel(( int(i), int(j)), inverted_image.getpixel((meter,j)) )
							if randint(0,100) > 90:
								inverted_image.putpixel(( randint(0,i), int(j)), inverted_image.getpixel((i,j)) )

				#newsize = inverted_image.size
				#width = 1+randint(0,4000)/1000
				#height = 1+randint(0,4000)/1000
				#newsize = (int(newsize[0]*width),int(newsize[1]*height));
				#inverted_image = inverted_image.resize(newsize)

				inverted_image.save("img/"+authorModified+"_inverted"+pngOrJpg)
			except Exception, e:
				print "error : "+str(e)
			print "image manipulation done.. answering.."
			#OPEN THE POST
			#convert the link to right format
			linkToPost = post.find("a", {"class":"postsubject"})			
			linkToPost = str(linkToPost)[str(linkToPost).find('href'):]
			splitattu = linkToPost.split()
			linkToPost = splitattu[0][6:]
			
			if "span" in linkToPost: 
				linkToPost = linkToPost[:-7]
			else:
				linkToPost = linkToPost[:-2]

			#visit the post
			session.visit("https://ylilauta.org"+linkToPost)
			response = session.body()
			soup = BeautifulSoup(response)
			
			#ANSWERING THE POST
			fil = session.at_xpath('//*[@name="file"]')
			fil.set(os.path.dirname(os.path.realpath(__file__))+"/img/"+authorModified+"_inverted"+pngOrJpg)
			print str(messageText).rstrip().replace('\n', '')+"?"
			
			oraakkeli = get("http://www.lintukoto.net/viihde/oraakkeli/index.php?kysymys="+str(messageText).rstrip().replace('\n', '')+"?&html")	
			print oraakkeli.text
			vastaus = oraakkeli.text
			if "Parseri" in vastaus:
				raise ValueError('tais olla joku ongelma oraakkelin päässä')
			if len(vastaus) > 500: 
				raise ValueError('tais olla joku ongelma oraakkelin päässä')
					
			teksti = session.at_xpath('//*[@name="msg"]')	
			#teksti.set(">>"+authorModified+"\n"+response.text)
			teksti.set(">>"+authorModified+"\n"+vastaus)
			token = session.at_xpath('//*[@name="submit"]')
			token.click()
			messagesdone=messagesdone+1
			print "messages sended: "+str(messagesdone)
			oldImage = authorModified
			#waitTime = randint(15, 900)
			waitTime = randint(120, 900)
			print "waiting "+str(waitTime)+"s"
			answered.append(authorModified)
			time.sleep(waitTime)
			
			
		except Exception, e:
			print "error : "+str(e)
			print "didn't find image in the thread(?)"
		print "--------------------------------"
			
	except Exception, e:
		print "error : "+str(e)
		time.sleep(15)
		session.visit(url)
		response = session.body()
		soup = BeautifulSoup(response)
		
compose = session.at_xpath('//*[contains(text(), "Kirjaudu ulos")]')
compose.click()