Move functions under the class to unify self usage

This commit is contained in:
Luke Murphy 2021-02-27 11:38:28 +01:00
parent d41e4b80bd
commit 623f2c8bb5
No known key found for this signature in database
GPG Key ID: 5E2EF5A63E3718CC

View File

@ -7,13 +7,36 @@ from urllib.parse import urlparse
import jinja2 import jinja2
from xbotlib import Bot from xbotlib import Bot
IMAGE_TYPES = (".jpg", "jpeg", "png", ".gif", ".bmp", ".svg", "eps")
AUDIO_TYPES = (".mp3", ".ogg", ".oga", ".mogg", ".wav", ".m4a", ".webm") class Logbot(Bot):
FILE_TYPES = ".pdf" help = """Oh dear, logbot is here!
(You can speak to the bot using @logbot or logbot:)
VIDEO_TYPES = ( <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"
VIDEO_TYPES = (
".mp4", ".mp4",
".webm", ".webm",
".flv", ".flv",
@ -27,56 +50,26 @@ VIDEO_TYPES = (
".m2v", ".m2v",
".mpe", ".mpe",
".3gp", ".3gp",
)
def add_to_db(self, message, media_post=None):
keys = [x for x in self.db[message.room]["messages"].keys()]
keys.sort(key=int)
if not keys:
new_key = "0"
else:
new_key = str(int(keys[-1]) + 1)
if media_post:
self.db[message.room]["messages"][new_key] = media_post
else:
self.db[message.room]["messages"][new_key] = message.content.replace("@add", "")
def del_from_db(self, message, key):
del self.db[message.room]["messages"][key]
def write_log(self, message, logger):
template = jinja2.Template(open("template.html").read())
roomname = re.sub(r"@.*", "", message.room)
log_path = os.path.join(self.output, roomname, "index.html")
with open(log_path, "w") as out:
html = template.render(
title=self.db[message.room]["title"], db=self.db[message.room]["messages"]
) )
out.write(html)
logger.info("writing to: ", log_path)
def _download(self, message):
def download(self, message, logger):
# define media_type # define media_type
if message.url.lower().endswith(IMAGE_TYPES): if message.url.lower().endswith(self.IMAGE_TYPES):
media_type = "images" media_type = "images"
elif message.url.lower().endswith(FILE_TYPES): elif message.url.lower().endswith(self.FILE_TYPES):
media_type = "pdf" media_type = "pdf"
elif message.url.lower().endswith(AUDIO_TYPES): elif message.url.lower().endswith(self.AUDIO_TYPES):
media_type = "audio" media_type = "audio"
elif message.url.lower().endswith(VIDEO_TYPES): elif message.url.lower().endswith(self.VIDEO_TYPES):
media_type = "video" media_type = "video"
else: else:
media_type = None media_type = None
logger.info(f"Unable to determine media type of {message.url.lower()}") self.log.info(f"Unable to determine media type of {message.url.lower()}")
# download file # download file
data = urllib.request.urlopen(message.url).read() data = urllib.request.urlopen(message.url).read()
if data: if data:
logger.info("downloading: ", message.url) self.log.info("downloading: ", message.url)
parsed_url = urlparse(message.url) parsed_url = urlparse(message.url)
filename = ( filename = (
os.path.basename(parsed_url.path).replace(" ", "_").replace("%20", "_") os.path.basename(parsed_url.path).replace(" ", "_").replace("%20", "_")
@ -92,42 +85,47 @@ def download(self, message, logger):
# define media_post # define media_post
media_path = os.path.join(media_type, filename) media_path = os.path.join(media_type, filename)
if message.url.lower().endswith(IMAGE_TYPES): if message.url.lower().endswith(self.IMAGE_TYPES):
media_post = f'<img src="{ media_path }">' media_post = f'<img src="{ media_path }">'
elif message.url.lower().endswith(FILE_TYPES): elif message.url.lower().endswith(self.FILE_TYPES):
media_post = f'<iframe src="{ media_path }" width="800" height="1000"></iframe>' media_post = (
elif message.url.lower().endswith(AUDIO_TYPES): 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>' media_post = f'<audio controls src="{ media_path }"></audio>'
elif message.url.lower().endswith(VIDEO_TYPES): elif message.url.lower().endswith(self.VIDEO_TYPES):
media_post = f'<video controls src="{ media_path }"></video>' media_post = f'<video controls src="{ media_path }"></video>'
else: else:
media_post = None media_post = None
return media_post, media_type 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(
title=self.db[message.room]["title"],
db=self.db[message.room]["messages"],
)
out.write(html)
self.log.info("writing to: ", log_path)
class Logbot(Bot): def _add_to_db(self, message, media_post=None):
"""Save new entry to database."""
help = """Oh dear, logbot is here! keys = [x for x in self.db[message.room]["messages"].keys()]
keys.sort(key=int)
(You can speak to the bot using @logbot or logbot:) if not keys:
new_key = "0"
<image>: Your image is added to the log. else:
new_key = str(int(keys[-1]) + 1)
logbot @help: Print this message if media_post:
self.db[message.room]["messages"][new_key] = media_post
logbot @add <message>: Add a message to the log. else:
replaced = message.content.replace("@add", "")
logbot @delete <num>: Delete posts from the log. For example: @logbot @delete 5 self.db[message.room]["messages"][new_key] = replaced
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 :)
"""
def _parse_room_name(self, room): def _parse_room_name(self, room):
"""Parse room name from entire address string.""" """Parse room name from entire address string."""
@ -171,16 +169,16 @@ logbot @uptime: To check how long @logbot has been around
# image / PDF / audio / video # image / PDF / audio / video
if message.url: if message.url:
media_post, media_type = download(self, message, self.log) media_post, media_type = self._download(message, self.log)
if media_post: if media_post:
add_to_db(self, message, media_post=media_post) self._add_to_db(message, media_post=media_post)
media_type = media_type.replace("images", "image") # linguistic hack! media_type = media_type.replace("images", "image") # linguistic hack!
reply = f"Thanks for that { media_type }!" reply = f"Thanks for that { media_type }!"
else: else:
reply = "Sorry, can't process that :( (unknown media type?)" reply = "Sorry, can't process that :( (unknown media type?)"
elif "@add" in message.text: elif "@add" in message.text:
add_to_db(self, message) self._add_to_db(message)
reply = "Added, thanks!" reply = "Added, thanks!"
elif "@delete" in message.text: elif "@delete" in message.text:
@ -190,7 +188,7 @@ logbot @uptime: To check how long @logbot has been around
if key in self.db[message.room]["messages"]: if key in self.db[message.room]["messages"]:
self.log.info("To be deleted:", self.db[message.room]["messages"][key]) self.log.info("To be deleted:", self.db[message.room]["messages"][key])
reply = f"This message is deleted: { self.db[message.room]['messages'][key] }" reply = f"This message is deleted: { self.db[message.room]['messages'][key] }"
del_from_db(self, message, key) del self.db[message.room]["messages"][key]
else: else:
reply = "This message is already gone!" reply = "This message is already gone!"
@ -206,7 +204,7 @@ logbot @uptime: To check how long @logbot has been around
else: else:
reply = "Hmm ... not sure what you want to do?" reply = "Hmm ... not sure what you want to do?"
write_log(self, message, self.log) self._write_log(message, self.log)
self.reply(reply, room=message.room) self.reply(reply, room=message.room)