Skip to content

Commit

Permalink
Added ranks, improved Redunda logging
Browse files Browse the repository at this point in the history
- Implemented rank detection and mention of the last status (#11)
- Improved the logging for Redunda so that the main thread and logging doesn't get blocked. Also, a bug which crashes the bot when Redunda isn't available was fixed (#13)
  • Loading branch information
Filnor committed Feb 19, 2018
1 parent 1f05f93 commit 0b544a8
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 21 deletions.
12 changes: 6 additions & 6 deletions chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

bot_parent = 'chade_'
bot_machine = 'HP Envy (dev machine)'
bot_version = 'v0.5'
bot_version = 'v0.6.0'
rooms = {
"Debug": 163468,
"SOBotics": 111347,
Expand Down Expand Up @@ -53,17 +53,17 @@ def main():

logging.info("Joined room '{}' on {}".format(room.name, host_id))

#Run Redunda reporting on a seperate thread

redunda_thread = threading.Thread(target=redunda.continousPing(bot_version))
redunda_thread.daemon = True
#Run Redunda reporting on a seperate thread/in the background
stop_redunda = threading.Event()
redunda_thread = redunda.RedundaThread(stop_redunda, bot_version, logging)
redunda_thread.start()

while True:
message = input("<< ")
room.send_message(message)

client.logout()
stop_redunda.set()

def on_message(message, client):
if not isinstance(message, MessagePosted) and not isinstance(message, MessageEdited):
Expand Down Expand Up @@ -107,4 +107,4 @@ def on_message(message, client):


if __name__ == '__main__':
main(*sys.argv[1:])
main()
23 changes: 18 additions & 5 deletions flagbot/check_flags.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import binascii

import gzip
import io
import json
import flagbot.ranks as ranks
import flagbot.html_parser as html_parser
from urllib.request import urlopen
from pyquery import PyQuery as pq
Expand All @@ -12,7 +13,8 @@ def checkOwnFlags(message, chat_helper):
html = page.read().decode("utf-8")
jQuery = pq(html)
flagCount = str(pq(jQuery(".g-col.g-row.fl-none").children()[6]).html()).replace('\n', ' ').replace('\r', '').strip().strip(" helpful flags")
chat_helper.replyWith(message, "You have {} helpful flags. Ranks are coming soon, you can suggest levels [here](https://github.com/SOBotics/FlaggersHall/issues/11)!".format(flagCount));
currentFlagRank = getCurrentFlagRank(int(flagCount.replace(",", "")))
chat_helper.replyWith(message, "You have {} helpful flags. Your last achieved rank was **{}** ({}) for {} helpful flags.".format(flagCount, currentFlagRank["title"], currentFlagRank["description"], currentFlagRank["count"]))
# message.message.reply("**This feature is not working yet!** You need [69] more helpful flags to get your next rank: **Burn the evil** (666 flags)") # original message, currently kept for historical reasons

def checkFlags(message, chat_helper):
Expand All @@ -34,7 +36,7 @@ def checkFlags(message, chat_helper):
if len(data["items"]) is 1:
validId = True
if data['quota_remaining'] is not None:
chat_helper.setQuota(data['quota_remaining']);
chat_helper.setQuota(data['quota_remaining'])
else:
chat_helper.postMessage("The specfied argument for the user id is not correct. Only digits are allowed.")
return
Expand All @@ -44,9 +46,20 @@ def checkFlags(message, chat_helper):
html = page.read().decode("utf-8")
jQuery = pq(html)
flagCount = str(pq(jQuery(".g-col.g-row.fl-none").children()[6]).html()).replace('\n', ' ').replace('\r', '').strip().strip(" helpful flags")
currentFlagRank = getCurrentFlagRank(int(flagCount.replace(",", "")))
userName = str(pq(jQuery(".name")[0]).html()).replace('\n', ' ').replace('\r', '').strip()
# Stripping mod markup from the name
userName = html_parser.strip_tags(userName)
chat_helper.postMessage("{} has {} helpful flags. Ranks are coming soon, you can suggest levels [here](https://github.com/SOBotics/FlaggersHall/issues/11)!".format(userName, flagCount))
chat_helper.postMessage("{} has {} helpful flags. Their last achieved rank was **{}** ({}) for {} helpful flags.".format(userName, flagCount, currentFlagRank["title"], currentFlagRank["description"], currentFlagRank["count"]))
else:
chat_helper.postMessage("The specfied user id does not belong to an existing user.")
chat_helper.postMessage("The specfied user id does not belong to an existing user.")

def getCurrentFlagRank(flagCount):
rankThresholds = []

for rank in ranks.ranks:
rankThresholds.append(int(rank))

for rank in rankThresholds:
if rank - flagCount >= 0:
return ranks.ranks[str(rankThresholds[rankThresholds.index(rank) - 1])]
62 changes: 62 additions & 0 deletions flagbot/ranks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
ranks = {
"365": {
"title": "A flag a day keeps bad posts away",
"description": "One year has 365 days",
"count": 365
},
"1111": {
"title": "No badge needed",
"description": "A number is prettier than a badge anyway!",
"count": 1111
},
"2008": {
"title": "Flag Overflow",
"description": "Stack Overflow was created in 2008",
"count": 2008
},
"10000": {
"title": "Elite Squad",
"description": "At one point of time, there were only 16 of us",
"count": 10000
},
"11111": {
"title": "Game of Flags",
"description": "All elevens because the TV show Game of Thrones started in 2011",
"count": 11111
},
"22656": {
"title": "Almost Jon Skeet",
"description": "22656 is his (John's) user ID",
"count": 22656
},
"33333": {
"title": "The Mad Flagger",
"description": "Got nothing better to do with your time? ;D",
"count": 33333
},
"42195": {
"title": "The Marathon",
"description": "Marathon's length in meters",
"count": 42195
},
"65536": {
"title": "The two to the sixteen",
"description": None,
"count": 65536
},
"101010": {
"title": "Definitely a robot",
"description": "42 in binary code. [Also 42 is the Answer to the Ultimate Question of Life, the Universe, and Everything](https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life,_the_Universe,_and_Everything_(42))",
"count": 101010
},
"2147483647": {
"title": "The Overflow",
"description": "[Maximum size of a 32-bit integer](https://stackoverflow.com/a/94608)",
"count": 2147483647
},
"4294967296": {
"title": "A `long` journey",
"description": None,
"count": 4294967296
}
}
32 changes: 22 additions & 10 deletions flagbot/redunda.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,30 @@
from threading import Thread
from urllib import parse, request
from time import localtime, strftime

import json
import time
from urllib.error import URLError


def pingRedunda(bot_version):
data = parse.urlencode({"key": "19b558436329ff6eb8247bc21fdd2aaa1135597b5bb858a10e8eef2688b8565e", "version": bot_version}).encode()
req = request.Request("https://redunda.sobotics.org/status.json", data)
class RedundaThread(Thread):
def __init__(self, event, bot_version, logging):
Thread.__init__(self)
self.stopped = event
self.bot_version = bot_version
self.logging = logging

response = request.urlopen(req)
def run(self):
while not self.stopped.wait(60):
self.pingRedunda()

jsonReturned = json.loads(response.read().decode("utf-8"))
def pingRedunda(self):
try:
data = parse.urlencode({"key": "19b558436329ff6eb8247bc21fdd2aaa1135597b5bb858a10e8eef2688b8565e", "version": self.bot_version}).encode()
req = request.Request("https://redunda.sobotics.org/status.json", data)

def continousPing(bot_version):
while True:
pingRedunda(bot_version)
time.sleep(60)
response = request.urlopen(req)

jsonReturned = json.loads(response.read().decode("utf-8"))
except (OSError, URLError) as e:
current_timestamp = strftime("%Y-%m-%d %H:%M:%S", localtime())
self.logging.warn("Pinging Redunda failed at {} CET", current_timestamp)

0 comments on commit 0b544a8

Please sign in to comment.