A place for all our bot adventures.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

211 lines
7.4 KiB

import os
import re
import shutil
import urllib.request
from urllib.parse import urlparse
import jinja2
from xbotlib import Bot
class Logbot(Bot):
help = """Oh dear, logbot is here!
(You can speak to the bot using @logbot or logbot:)
<image>: Your image is added to the log.
logbot @help: Print this message
logbot @add <message>: Add a message to the log.
logbot @delete <num>: Delete posts from the log. For example: @logbot @delete 5
logbot @title <string>: Set the title of your log.
logbot @style <element> <css-rule>: Edit the css of your log. For example: logbot @style body background-color: pink; [future-feature]
logbot @uptime: To check how long @logbot has been around
@bots: To see who is around :)
""" # noqa
IMAGE_TYPES = (".jpg", "jpeg", "png", ".gif", ".bmp", ".svg", "eps")
AUDIO_TYPES = (".mp3", ".ogg", ".oga", ".mogg", ".wav", ".m4a", ".webm")
FILE_TYPES = ".pdf"
def _download(self, message):
# define media_type
if message.url.lower().endswith(self.IMAGE_TYPES):
media_type = "images"
elif message.url.lower().endswith(self.FILE_TYPES):
media_type = "pdf"
elif message.url.lower().endswith(self.AUDIO_TYPES):
media_type = "audio"
elif message.url.lower().endswith(self.VIDEO_TYPES):
media_type = "video"
media_type = None
self.log.info(f"Unable to determine media type of {message.url.lower()}")
# download file
data = urllib.request.urlopen(message.url).read()
if data:
self.log.info("downloading: ", message.url)
parsed_url = urlparse(message.url)
filename = (
os.path.basename(parsed_url.path).replace(" ", "_").replace("%20", "_")
) # safe url's
self.log.info("as the file: ", filename)
roomname = re.sub(r"@.*", "", message.room)
path = os.path.join(self.output, roomname, media_type)
if not os.path.isdir(path):
file_path = os.path.join(path, filename)
with open(file_path, "wb") as media_file:
# define media_post
media_path = os.path.join(media_type, filename)
if message.url.lower().endswith(self.IMAGE_TYPES):
media_post = f'<img src="{ media_path }">'
elif message.url.lower().endswith(self.FILE_TYPES):
media_post = (
f'<iframe src="{ media_path }" width="800" height="1000"></iframe>'
elif message.url.lower().endswith(self.AUDIO_TYPES):
media_post = f'<audio controls src="{ media_path }"></audio>'
elif message.url.lower().endswith(self.VIDEO_TYPES):
media_post = f'<video controls src="{ media_path }"></video>'
media_post = None
return media_post, media_type
def _write_log(self, message):
"""Write new log to the file system."""
template = jinja2.Template(open("template.html").read())
room_name = self._parse_room_name(message.room)
log_path = os.path.join(self.output, room_name, "index.html")
with open(log_path, "w") as out:
html = template.render(
self.log.info("writing to: ", log_path)
def _add_to_db(self, message, media_post=None):
"""Save new entry to database."""
keys = [x for x in self.db[message.room]["messages"].keys()]
if not keys:
new_key = "0"
new_key = str(int(keys[-1]) + 1)
if media_post:
self.db[message.room]["messages"][new_key] = media_post
replaced = message.content.replace("@add", "")
self.db[message.room]["messages"][new_key] = replaced
def _parse_room_name(self, room):
"""Parse room name from entire address string."""
return str(re.match(r".*@", room).group()).replace("@", "")
def _setup_room(self, room):
"""Create directories and database entries for a new room."""
room_name = self._parse_room_name(room)
room_path = os.path.join(self.output, room_name)
self.log.info(f"Processing setup logic for: {room_path}")
if room not in self.db.keys():
self.db[room] = {}
self.db[room]["messages"] = {}
self.db[room]["title"] = room
self.log.info(f"Added to the database: { room }")
if not os.path.exists(room_path):
shutil.copy("stylesheet.css", room_path)
self.log.info(f"Created a folder for: { room }")
self.log.info(f"Copied stylesheet.css to: { room }")
def setup(self):
self.log.info(f"Output folder is set to: { self.output }")
for room in self.rooms:
def group_invite(self, message):
"""Extend xbotlib invite response logic and do required room setup."""
def group(self, message):
# to debug in the terminal
self.log.info("message: ", message.text)
self.log.info("room: ", message.room)
self.log.info("sender: ", message.sender)
# image / PDF / audio / video
if message.url:
media_post, media_type = self._download(message, self.log)
if media_post:
self._add_to_db(message, media_post=media_post)
media_type = media_type.replace("images", "image") # linguistic hack!
reply = f"Thanks for that { media_type }!"
reply = "Sorry, can't process that :( (unknown media type?)"
elif "@add" in message.text:
reply = "Added, thanks!"
elif "@delete" in message.text:
match = re.findall(r"@delete \d*", message.content)[0]
key = str(match.replace("@delete ", ""))
if key in self.db[message.room]["messages"]:
self.log.info("To be deleted:", self.db[message.room]["messages"][key])
reply = f"This message is deleted: { self.db[message.room]['messages'][key] }"
del self.db[message.room]["messages"][key]
reply = "This message is already gone!"
elif "@title" in message.text:
match = re.findall("@title .*", message.content)[0]
title = match.replace("@title", "")
self.db[message.room]["title"] = title
reply = f"The title of the log is changed to: { title }"
elif "@style" in message.text:
reply = "This is a future-feature ..."
reply = "Hmm ... not sure what you want to do?"
self._write_log(message, self.log)
self.reply(reply, room=message.room)