Browse Source

Auto-formatter has something to say here

master
Luke Murphy 4 years ago
parent
commit
b359d92021
No known key found for this signature in database GPG Key ID: 5E2EF5A63E3718CC
  1. 10
      LogBot/README.md
  2. 327
      LogBot/logbot.py
  3. 26
      LogBot/stylesheet.css

10
LogBot/README.md

@ -4,7 +4,7 @@ A small XMPP bot written in Python that logs XMPP conversations into a HTML page
The bot is used in group chats, where it includes all images that are send to the group and all messages that include `@logbot` or `logbot` or `logbot:`. The bot is used in group chats, where it includes all images that are send to the group and all messages that include `@logbot` or `logbot` or `logbot:`.
*work-in-progress* _work-in-progress_
## How to use LogBot? ## How to use LogBot?
@ -24,10 +24,10 @@ logbot @uptime: To check how long @logbot has been around
## Situated tails ## Situated tails
* Archive bot, Relearn 2017, <https://gitlab.com/relearn/relearn2017/-/tree/master/xmpp-bots/archive-bot> - Archive bot, Relearn 2017, <https://gitlab.com/relearn/relearn2017/-/tree/master/xmpp-bots/archive-bot>
* Streambot, Varia website extension 2017-2018, <https://git.vvvvvvaria.org/varia/xmpp.streambot> - Streambot, Varia website extension 2017-2018, <https://git.vvvvvvaria.org/varia/xmpp.streambot>
* Logbot v1, Varia XMPP extension 2017-2020, <https://git.vvvvvvaria.org/varia/bots/src/branch/master/logbot> - Logbot v1, Varia XMPP extension 2017-2020, <https://git.vvvvvvaria.org/varia/bots/src/branch/master/logbot>
## Requirements ## Requirements
* [xbotlib](https://git.vvvvvvaria.org/decentral1se/xbotlib) - [xbotlib](https://git.vvvvvvaria.org/decentral1se/xbotlib)

327
LogBot/logbot.py

@ -1,81 +1,134 @@
from xbotlib import Bot import json
import jinja2 import os
import os, re, json, shutil import re
from os import environ import shutil
import urllib.request import urllib.request
from os import environ
from urllib.parse import urlparse from urllib.parse import urlparse
import jinja2
from xbotlib import Bot
def add_to_db(self, message, media_post=None): def add_to_db(self, message, media_post=None):
keys = [x for x in self.db[message.room]['messages'].keys()] keys = [x for x in self.db[message.room]["messages"].keys()]
keys.sort(key=int) keys.sort(key=int)
if not keys: if not keys:
new_key = "0" new_key = "0"
else: else:
new_key = str(int(keys[-1]) + 1) new_key = str(int(keys[-1]) + 1)
if media_post: if media_post:
self.db[message.room]['messages'][new_key] = media_post self.db[message.room]["messages"][new_key] = media_post
else: else:
self.db[message.room]['messages'][new_key] = message.content.replace('@add','') self.db[message.room]["messages"][new_key] = message.content.replace("@add", "")
def del_from_db(self, message, key): def del_from_db(self, message, key):
del self.db[message.room]['messages'][key] del self.db[message.room]["messages"][key]
def write_log(self, message): def write_log(self, message):
template = jinja2.Template(open('template.html').read()) template = jinja2.Template(open("template.html").read())
roomname = re.sub(r'@.*', '', message.room) roomname = re.sub(r"@.*", "", message.room)
log_path = os.path.join(self.output, roomname, 'index.html') log_path = os.path.join(self.output, roomname, "index.html")
with open(log_path,'w') as out: with open(log_path, "w") as out:
html = template.render(title=self.db[message.room]['title'], db=self.db[message.room]['messages']) html = template.render(
out.write(html) title=self.db[message.room]["title"], db=self.db[message.room]["messages"]
print('writing to: ', log_path) )
out.write(html)
print("writing to: ", log_path)
def download(self, message): def download(self, message):
# define media_type # define media_type
if message.url.lower().endswith(('.jpg','jpeg','png','.gif','.bmp','.svg','eps')): if message.url.lower().endswith(
media_type = 'images' (".jpg", "jpeg", "png", ".gif", ".bmp", ".svg", "eps")
elif message.url.lower().endswith('.pdf'): ):
media_type = 'pdf' media_type = "images"
elif message.url.lower().endswith(('.mp3','.ogg','.oga','.mogg','.wav','.m4a','.webm')): elif message.url.lower().endswith(".pdf"):
media_type = 'audio' media_type = "pdf"
elif message.url.lower().endswith(('.mp4','.webm','.flv','.vob','.avi','.mov','.qt','.mpg','.mpeg','.mp4','.m2v','.mpe','.3gp')): elif message.url.lower().endswith(
media_type = 'video' (".mp3", ".ogg", ".oga", ".mogg", ".wav", ".m4a", ".webm")
else: ):
media_type = None media_type = "audio"
elif message.url.lower().endswith(
# download file (
data = urllib.request.urlopen(message.url).read() ".mp4",
if data: ".webm",
print('downloading: ', message.url) ".flv",
parsed_url = urlparse(message.url) ".vob",
filename = os.path.basename(parsed_url.path).replace(' ','_').replace('%20','_') # safe url's ".avi",
print('as the file: ', filename) ".mov",
roomname = re.sub(r'@.*', '', message.room) ".qt",
path = os.path.join(self.output, roomname, media_type) ".mpg",
if not os.path.isdir(path): ".mpeg",
os.mkdir(path) ".mp4",
file_path = os.path.join(path, filename) ".m2v",
with open(file_path, 'wb') as media_file: ".mpe",
media_file.write(data) ".3gp",
media_file.close() )
):
# define media_post media_type = "video"
media_path = os.path.join(media_type, filename) else:
if message.url.lower().endswith(('.jpg','jpeg','png','.gif','.bmp','.svg','eps')): media_type = None
media_post = f'<img src="{ media_path }">'
elif message.url.lower().endswith('.pdf'): # download file
media_post = f'<iframe src="{ media_path }" width="800" height="1000"></iframe>' data = urllib.request.urlopen(message.url).read()
elif message.url.lower().endswith(('.mp3','.ogg','.oga','.mogg','.wav','.m4a','.webm')): if data:
media_post = f'<audio controls src="{ media_path }"></audio>' print("downloading: ", message.url)
elif message.url.lower().endswith(('.mp4','.webm','.flv','.vob','.avi','.mov','.qt','.mpg','.mpeg','.mp4','.m2v','.mpe','.3gp')): parsed_url = urlparse(message.url)
media_post = f'<video controls src="{ media_path }"></video>' filename = (
else: os.path.basename(parsed_url.path).replace(" ", "_").replace("%20", "_")
media_post = None ) # safe url's
print("as the file: ", filename)
return media_post, media_type roomname = re.sub(r"@.*", "", message.room)
path = os.path.join(self.output, roomname, media_type)
if not os.path.isdir(path):
os.mkdir(path)
file_path = os.path.join(path, filename)
with open(file_path, "wb") as media_file:
media_file.write(data)
media_file.close()
# define media_post
media_path = os.path.join(media_type, filename)
if message.url.lower().endswith(
(".jpg", "jpeg", "png", ".gif", ".bmp", ".svg", "eps")
):
media_post = f'<img src="{ media_path }">'
elif message.url.lower().endswith(".pdf"):
media_post = f'<iframe src="{ media_path }" width="800" height="1000"></iframe>'
elif message.url.lower().endswith(
(".mp3", ".ogg", ".oga", ".mogg", ".wav", ".m4a", ".webm")
):
media_post = f'<audio controls src="{ media_path }"></audio>'
elif message.url.lower().endswith(
(
".mp4",
".webm",
".flv",
".vob",
".avi",
".mov",
".qt",
".mpg",
".mpeg",
".mp4",
".m2v",
".mpe",
".3gp",
)
):
media_post = f'<video controls src="{ media_path }"></video>'
else:
media_post = None
return media_post, media_type
class logbot(Bot): class logbot(Bot):
help = '''Oh dear, logbot is here! help = """Oh dear, logbot is here!
(You can speak to the bot using @logbot or logbot:) (You can speak to the bot using @logbot or logbot:)
@ -94,76 +147,78 @@ logbot @style <element> <css-rule>: Edit the css of your log. For example: logbo
logbot @uptime: To check how long @logbot has been around logbot @uptime: To check how long @logbot has been around
@bots: To see who is around :) @bots: To see who is around :)
''' """
def setup(self):
print('INFO ', f'Output folder is set to: { self.output }') def setup(self):
print("INFO ", f"Output folder is set to: { self.output }")
for room in self.rooms:
for room in self.rooms:
roomname = str(re.match(r'.*@', room).group()).replace('@','')
self.room_path = os.path.join(self.output, roomname) roomname = str(re.match(r".*@", room).group()).replace("@", "")
print('INFO ', f'Room path is set to: { self.room_path }') self.room_path = os.path.join(self.output, roomname)
print("INFO ", f"Room path is set to: { self.room_path }")
# Check if the room is in the database already
if not room in self.db.keys(): # Check if the room is in the database already
self.db[room] = {} if not room in self.db.keys():
self.db[room]['messages'] = {} self.db[room] = {}
self.db[room]['title'] = room self.db[room]["messages"] = {}
print('INFO ', f'Added to the database: { room }') self.db[room]["title"] = room
print("INFO ", f"Added to the database: { room }")
# Check if the room has an output folder already
if not os.path.exists(self.room_path): # Check if the room has an output folder already
os.mkdir(self.room_path) if not os.path.exists(self.room_path):
shutil.copy('stylesheet.css', self.room_path) os.mkdir(self.room_path)
print('INFO ', f'Created a folder for: { room }') shutil.copy("stylesheet.css", self.room_path)
print('INFO ', f'Copied stylesheet.css to: { room }') print("INFO ", f"Created a folder for: { room }")
print("INFO ", f"Copied stylesheet.css to: { room }")
def group(self, message):
def group(self, message):
# to debug in the terminal
print('------------------') # to debug in the terminal
print('message: ', message.text) print("------------------")
print('room: ', message.room) print("message: ", message.text)
print('sender: ', message.sender) print("room: ", message.room)
print("sender: ", message.sender)
# image / PDF / audio / video
if message.url: # image / PDF / audio / video
media_post, media_type = download(self, message) if message.url:
if media_post: media_post, media_type = download(self, message)
add_to_db(self, message, media_post=media_post) if media_post:
media_type = media_type.replace('images', 'image') # linguistic hack! add_to_db(self, message, media_post=media_post)
reply = f'Thanks for that { media_type }!' media_type = media_type.replace("images", "image") # linguistic hack!
else: reply = f"Thanks for that { media_type }!"
reply = 'Sorry, can\'t process that :(' else:
reply = "Sorry, can't process that :("
elif '@add' in message.text:
add_to_db(self, message) elif "@add" in message.text:
reply = 'Added, thanks!' add_to_db(self, message)
reply = "Added, thanks!"
elif '@delete' in message.text:
match = re.findall("@delete \d*", message.content)[0] elif "@delete" in message.text:
key = str(match.replace('@delete ','')) match = re.findall("@delete \d*", message.content)[0]
key = str(match.replace("@delete ", ""))
if key in self.db[message.room]['messages']:
print('To be deleted:', self.db[message.room]['messages'][key]) if key in self.db[message.room]["messages"]:
reply = f"This message is deleted: { self.db[message.room]['messages'][key] }" print("To be deleted:", self.db[message.room]["messages"][key])
del_from_db(self, message, key) reply = f"This message is deleted: { self.db[message.room]['messages'][key] }"
else: del_from_db(self, message, key)
reply = 'This message is already gone!' else:
reply = "This message is already gone!"
elif '@title' in message.text:
match = re.findall("@title .*", message.content)[0] elif "@title" in message.text:
title = match.replace('@title','') match = re.findall("@title .*", message.content)[0]
self.db[message.room]['title'] = title title = match.replace("@title", "")
reply = f'The title of the log is changed to: { 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 ...' elif "@style" in message.text:
reply = "This is a future-feature ..."
else:
reply = 'Hmm ... not sure what you want to do?' else:
reply = "Hmm ... not sure what you want to do?"
write_log(self, message)
return self.reply(reply, room=message.room) write_log(self, message)
return self.reply(reply, room=message.room)
logbot() logbot()

26
LogBot/stylesheet.css

@ -1,21 +1,21 @@
body{ body {
margin: 1em; margin: 1em;
max-width: 800px; max-width: 800px;
} }
.post{ .post {
margin: 1em 0; margin: 1em 0;
clear: both; clear: both;
} }
.post p.key{ .post p.key {
float: left; float: left;
margin: 0 1em 1em; margin: 0 1em 1em;
} }
.post p.message{ .post p.message {
} }
img, img,
iframe, iframe,
audio, audio,
video{ video {
max-width: calc(100% - 100px); max-width: calc(100% - 100px);
height: auto; height: auto;
} }
Loading…
Cancel
Save