Skip to content

Instantly share code, notes, and snippets.

@enkore
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enkore/ddc79f8d13572dffd02e to your computer and use it in GitHub Desktop.
Save enkore/ddc79f8d13572dffd02e to your computer and use it in GitHub Desktop.
ratsbot
#!/usr/bin/env python
import urllib.request
import xml.etree.ElementTree as ET
import irc.bot
import irc.strings
# PyPI: mde_bbcode
import bbcode
SERVER = "<>"
USERNAME = "<>"
PASSWORD = "<>"
CHANNEL = "#mde.linux"
NICKNAME = "ratsbot"
FORMAT = "<{time}> Neuer Post von {user} »{msg}« {link}"
TID = 212187
def truncate(content, length=100, suffix='...'):
if len(content) <= length:
return content
else:
return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix
def reduce_msg(msg):
DROP = ["Code", "Spoiler", "Quote", "Image", "Table", "List"]
root = ET.fromstring(msg)
for elem in filter(lambda x: x.tag in DROP, root.iter()):
root.remove(elem)
return ET.tostring(root, encoding="unicode", method="text")
class APIWrapper:
def __init__(self, tid):
self.tid = tid
self.last_count = 0
def retrieve(self, page):
url = "http://forum.mods.de/bb/xml/thread.php?page={page}&TID={tid}".format(tid=self.tid, page=page)
response = urllib.request.urlopen(url)
return ET.fromstring(response.read())
def update(self):
root = self.retrieve(1000)
count = int(root.find("number-of-replies").get("value"))
if count > self.last_count:
self.last_count = count
root = self.retrieve((count // 30) + 1)
latest = root.find("./posts/post[last()]")
msg = "<msg>%s</msg>" % bbcode.BbCodeParser().parse(latest.find("./message/content").text)
msg = reduce_msg(msg)
latest = {
"time": latest.find("./date").text.split(" ")[1],
"user": latest.find("./user").text,
"msg": truncate(msg.split("\n")[0].strip()),
"link": "http://forum.mods.de/bb/thread.php?TID={tid}&PID={pid}#reply_{pid}".format(tid=self.tid, pid=latest.get("id")),
}
return latest
else:
if int(root.find("./flags/is-closed").get("value")):
return False
return None
class RatsBot(irc.bot.SingleServerIRCBot):
def __init__(self, channel, nickname, server, api, port=6667, password=None, username=None):
irc.bot.SingleServerIRCBot.__init__(self, [(server, port, password)], nickname, nickname, username=username)
self.channel = channel
self.api = api
def on_nicknameinuse(self, c, e):
c.nick(c.get_nickname() + "_")
def on_welcome(self, c, e):
c.join(self.channel)
c.execute_every(5, self.update, (c,))
def update(self, c):
latest = self.api.update()
if latest:
c.notice(self.channel, FORMAT.format(**latest))
elif latest == False:
self.die()
def main():
bot = RatsBot(CHANNEL, NICKNAME, SERVER, password=PASSWORD, username=USERNAME, api=APIWrapper(TID))
print("Starting bot...")
bot.start()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment