Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from selenium import webdriver
- from selenium.webdriver.common.keys import Keys
- import time
- import json
- from datetime import datetime
- import random
- import os.path
- if not os.path.isfile("data.json"):
- with open("data.json", "w") as f:
- f.write("{}")
- leaderboard = []
- with open('data.json') as f:
- leaderboard = json.load(f)
- if not os.path.isfile("steam.json"):
- with open("steam.json", "w") as f:
- f.write("{}")
- steamIDs = []
- with open('steam.json') as f:
- steamIDs = json.load(f)
- messageIDs = []
- permWaitTime = 5
- sleepTime = 5
- timeToServe = 60
- debug = False
- debugMessage = False
- semprexity = False
- lastSeenTime = time.time()
- first = True
- restrictTime = 6
- lastMessage = 0
- username = ""
- password = ""
- profile = webdriver.FirefoxProfile("C:\\firefoxSelenium")
- driver = webdriver.Firefox(profile)
- driver.implicitly_wait(10)
- servingTrivia = False
- triviaStarted = 0
- currentQuestion = ""
- currentDifficulty = 0
- currentAnswer = []
- SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}
- def ordinal(num):
- if 10 <= num % 100 <= 20:
- suffix = 'th'
- else:
- suffix = SUFFIXES.get(num % 10, 'th')
- return str(num) + suffix
- def login():
- driver.get("https://clwo.eu/index.php")
- if "Log out" in driver.find_element_by_class_name("dropdown").get_attribute('innerHTML'):
- return "Remembered"
- driver.find_element_by_class_name("Login").click()
- ufield = driver.find_element_by_id("quick_login_username")
- pfield = driver.find_element_by_id("quick_login_password")
- ufield.send_keys(username)
- pfield.send_keys(password)
- pfield.send_keys(Keys.ENTER)
- return "New Login"
- def scrapeShoutbox():
- global first
- if first:
- first = False
- entries = driver.find_element_by_class_name("data")
- allEntries = entries.get_attribute('innerHTML')
- individualEntries = allEntries.split('<div style="display: block;" class="entry" data-id="')
- individualEntries.pop(0)
- if semprexity:
- listOfEntries = [{'text': '!trivia', 'date': 14603112000, 'name': 'Semprexity'}]
- else:
- listOfEntries = []
- for entry in individualEntries:
- details = {}
- # print(entry)
- details["id"] = entry[:4]
- # print(details["id"])
- entry = entry[21:]
- entry = entry.split('" data-own="">\n')
- try:
- blarg = entry[1]
- except:
- entry = entry[0].split('">\n')
- details["name"] = entry[0]
- # print("Name: " + name)
- # print(details["name"])
- # print(entry)
- entry = entry[1].split('<div class="text">')
- entry = entry[1].split('</div>\n <div class="info"><span class="date">')
- details["text"] = entry[0]
- # print("Text: " + text)
- entry = entry[1].split('</span><a href="" class="mo')
- # 10 Apr 17:04
- tempDate = datetime.strptime(entry[0] + " 2016", "%d %b %H:%M %Y")
- details["date"] = int(time.mktime(time.strptime(str(tempDate), '%Y-%m-%d %H:%M:%S'))) - time.timezone
- # print("Date: " + date)
- # print(details)
- listOfEntries.append(details)
- # print("We scraped " + str(len(listOfEntries)) + " entries")
- return listOfEntries
- def sendMessage(message, test=False, bot="(TriviaBot) "):
- time.sleep(permWaitTime)
- global lastMessage, restrictTime
- # print(time.time() - lastMessage)
- if time.time() - lastMessage > restrictTime:
- lastMessage = time.time()
- if debugMessage or test:
- message = "/pvt 897 " + bot + message
- else:
- message = bot + message
- if not debug:
- print(message)
- messageField = driver.find_element_by_xpath("//input[@placeholder='ENTER your message...']")
- messageField.send_keys(message)
- messageField.send_keys(Keys.ENTER)
- else:
- print(message)
- else:
- waitTime = restrictTime - (time.time() - lastMessage)
- print("Messaging Too Quickly, Holding " + str(int(waitTime)) + " Seconds")
- time.sleep(waitTime)
- sendMessage(message)
- def handleMessages(messages):
- global timeToServe, lastSeenTime
- for message in reversed(messages):
- # print(message)
- # print("LastSeen: " + str(lastSeenTime) + " MessageDate: " + str(message['date']))
- if lastSeenTime > message['date']:
- pass
- else:
- if message['id'] not in messageIDs:
- messageIDs.append(message['id'])
- print("Tested " + message['text'])
- if "(TriviaBot)" not in message['text']:
- if "!trivia" in message['text']:
- # Someone asked for a trivia question
- print("Serving Trivia: " + str(servingTrivia))
- if not servingTrivia:
- print(message['name'] + " wanted a trivia question")
- startTrivia()
- else:
- timeLeft = int(timeToServe - (time.time() - triviaStarted))
- sendMessage(message['name'] + ", you asked for a trivia but there is already one up! Please wait " + str(timeLeft) + " seconds until that trivia ends.")
- if "!answer" in message['text']:
- if servingTrivia:
- checkAnswer(message['text'], message['name'])
- else:
- sendMessage(message['name'] + ", there isn't a trivia up at the moment to answer!")
- if "!position" in message['text']:
- sendMessage(message['name'] + ", you are currently " + ordinal(checkPosition(message['name'])) + " in the leaderboard of " + str(len(leaderboard)) + " people!")
- if "!help" in message['text']:
- sendMessage("Currently supported commands: !trivia, !answer <answer>, !position, !help")
- lastSeenTime = messages[0]['date'] - 5
- def startTrivia(difficulty=-1):
- global servingTrivia, triviaStarted, currentDifficulty, currentQuestion, currentAnswer
- servingTrivia = True
- triviaStarted = time.time()
- while 1:
- data = random.choice(open("questions.psv").readlines()).split("|")
- if int(data[0]) == difficulty or difficulty == -1:
- break
- currentDifficulty = int(data[0])
- currentQuestion = data[1]
- data.pop(0)
- data.pop(0)
- currentAnswer = data
- currentAnswer[-1] = currentAnswer[-1].strip()
- sendMessage(currentQuestion)
- print(currentDifficulty)
- print(currentAnswer)
- def checkAnswer(answer, player):
- global currentAnswer, servingTrivia, triviaStarted, currentQuestion, currentDifficulty
- answer = answer.replace("!answer ", "")
- answer = answer.replace('<span class="private-message"><b>Private shout from <span class="private-username">Popey456963</span></b>: </span> ', "")
- print(player + " submitted the answer: " + answer)
- if answer.lower in currentAnswer:
- if player in leaderboard:
- leaderboard[player] += 1
- else:
- leaderboard[player] = 1
- storeLeaderboard()
- sendMessage("Congratulations " + player + " on getting the answer right! That is the " + ordinal(leaderboard[player]) + " question you've got right!")
- servingTrivia = False
- triviaStarted = 0
- currentQuestion = ""
- currentDifficulty = 0
- currentAnswer = []
- def questionTimeout():
- global timeToServer, triviaStarted, currentAnswer, servingTrivia, currentQuestion, currentDifficulty
- timeLeft = int(timeToServe - (time.time() - triviaStarted))
- if timeLeft < 0 and servingTrivia:
- print(currentAnswer)
- try:
- sendMessage("Noone answered the question in time! The answer was: " + currentAnswer[0])
- except:
- print("We reacon there was a list range index here because the answer was already solved. We can safely ignore")
- servingTrivia = False
- triviaStarted = 0
- currentQuestion = ""
- currentDifficulty = 0
- currentAnswer = []
- def storeLeaderboard():
- with open("data.json", "w") as f:
- json.dump(leaderboard, f)
- def storeSteam():
- with open("steam.json", "w") as f:
- json.dump(steamIDs)
- def checkPosition(player):
- positions = sorted(leaderboard, key=leaderboard.get, reverse=True)
- return positions.index(player) + 1
- report = login()
- sendMessage("Hello. I'm a bot. Beep Boop. (Initialization Complete)", test=True)
- driver.execute_script('document.getElementsByClassName("text")[0].setAttribute("maxlength", "90000");')
- while 1:
- time.sleep(sleepTime)
- questionTimeout()
- messages = scrapeShoutbox()
- handleMessages(messages)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement