In preparation for the end of Code Review's 2015 election, I've built a simple bot to get the election votes, run OpenSTV on them, and post the result to a chatroom. I'm using this Python implementation of STV and ManishEarth's ChatExchange.
import getpass import logging import os import time import urllib import sys from subprocess import call import ChatExchange.chatexchange from ChatExchange.chatexchange.events import MessageEdited logging.captureWarnings(True) class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' logging.basicConfig(level=logging.CRITICAL) if 'ChatExchangeU' in os.environ: email = os.environ['ChatExchangeU'] else: email = raw_input("Email: ") if 'ChatExchangeP' in os.environ: password = os.environ['ChatExchangeP'] else: password = getpass.getpass("Password: ") client = ChatExchange.chatexchange.Client('stackexchange.com', email, password) raw_input(bcolors.BOLD + bcolors.OKGREEN + "Connection good." + bcolors.ENDC + bcolors.BOLD + " [Enter] to proceed getting results for " + sys.argv + " election #" + sys.argv + "..." + bcolors.ENDC) urllib.urlretrieve ("http://" + sys.argv + "/election/download-result/" + sys.argv, "votes.blt") result = os.popen("python runElection.py MeekSTV votes.blt").read() os.remove("votes.blt") result_indented = "" for string in result.splitlines(): result_indented = result_indented + " " + string + "\n" print result_indented winners_line = ">" + result_indented.splitlines()[-1] okay_to_post = raw_input("Okay to post? ") if okay_to_post.lower() == "y": sandbox = client.get_room(sys.argv) sandbox.send_message(winners_line) sandbox.send_message(result_indented, False) time.sleep(40)
I run it from the command line like so:
python StackElectChat.py <site> <election number> <chatroom id>
For example, running this:
python StackElectChat.py serverfault.com 2 17251
Would take the results from Server Fault's second election and post it to Chatroom #17251.
- I don't like how I'm doing colors for it (taken from this Stack Overflow answer), is there a built in way?
okay_to_post.lower()seems like a hack - is there a built in way to check for an affirmative answer to a request?
- I don't like how I iterate over every line to add code formatting (four spaces) to the chat message