forked from varia/bots
96 lines
2.4 KiB
Python
96 lines
2.4 KiB
Python
from xbotlib import Bot
|
|
import json
|
|
import jinja2
|
|
import re
|
|
|
|
db = 'storage.json'
|
|
|
|
def readdb():
|
|
storage = open(db, 'r').read()
|
|
messages = json.loads(storage)
|
|
lastid = sorted(list(messages.keys()))
|
|
nextid = str(int(lastid[-1])+1)
|
|
return messages
|
|
|
|
def writedb(message):
|
|
try:
|
|
with open(db, 'r') as storage:
|
|
messages = json.loads(storage.read())
|
|
if messages.keys():
|
|
keys = [int(x) for x in messages.keys()]
|
|
keys.sort()
|
|
lastid = keys[-1]
|
|
nextid = lastid + 1
|
|
else:
|
|
nextid = 0
|
|
messages[f'{ nextid }'] = message
|
|
storage = open(db, 'w')
|
|
storage.write(json.dumps(messages, indent=4))
|
|
except IOError:
|
|
with open(db, 'w') as storage:
|
|
storage.write(json.dumps('{}'))
|
|
writedb(message)
|
|
return messages
|
|
|
|
def deletefromdb(id):
|
|
with open(db, 'r') as storage:
|
|
messages = json.loads(storage.read())
|
|
del messages[id]
|
|
storage = open(db, 'w')
|
|
storage.write(json.dumps(messages, indent=4))
|
|
return messages
|
|
|
|
def writelog(messages):
|
|
template = jinja2.Template(open('index.html.j2').read())
|
|
with open('log.html','w') as out:
|
|
html = template.render(messages=messages)
|
|
out.write(html)
|
|
|
|
class logbot(Bot):
|
|
|
|
help = '''Oh dear, logbot is here!
|
|
|
|
@delete <num>
|
|
Delete posts from the log.
|
|
For example: @logbot @delete 5
|
|
|
|
@bots
|
|
To see who is around :)
|
|
|
|
@uptime
|
|
To check how long @logbot has been around
|
|
|
|
@help
|
|
Print this message
|
|
'''
|
|
|
|
def group(self, message):
|
|
print(message.content)
|
|
messages = readdb()
|
|
|
|
if message.url:
|
|
messages = writedb(f'<img src="{ message.url }">')
|
|
reply = 'Thanks for that image!'
|
|
|
|
elif '@delete' in message.text:
|
|
match = re.findall("@delete \d*", message.content)[0]
|
|
id = match.replace('@delete ','')
|
|
if id in messages:
|
|
print('To be deleted:', messages[str(id)])
|
|
reply = f'This message is deleted: { messages[str(id)] }'
|
|
messages = deletefromdb(id)
|
|
else:
|
|
reply = 'This message is already gone!'
|
|
|
|
elif '@help' in message.text:
|
|
print('HELP')
|
|
|
|
else:
|
|
messages = writedb(message.text)
|
|
reply = 'Added, thanks!'
|
|
|
|
writelog(messages)
|
|
return self.reply(reply, room=message.room)
|
|
|
|
logbot()
|