Browse Source

making a copy of the folding bot in this repo

master
mb 2 years ago
commit
8d8df1b780
  1. 8
      Makefile
  2. 105
      folding.py
  3. 2
      requirements.txt
  4. 16
      templates/folds.html
  5. 21
      websocket-server.py

8
Makefile

@ -0,0 +1,8 @@
all: run
run:
venv/bin/python3 folding.py
setup:
python3 -m venv venv
venv/bin/pip3 install -r requirements.txt

105
folding.py

@ -0,0 +1,105 @@
from urllib.request import urlopen
from urllib.parse import urlencode
import os, json
from time import sleep
import jinja2
def ep(fn, api_url, api_key, **data):
d = {}
d['apikey'] = api_key
for key in data:
d[key] = data[key]
return json.load(urlopen(f"{api_url}{fn}", data=urlencode(d).encode()))
with open("/srv/etherpad-lite/APIKEY.txt") as f:
api_key = f.read()
api_url = "https://hub.vvvvvvaria.org/rosa/pad/api/1.2.15/"
pad_url = "https://hub.vvvvvvaria.org/rosa/pad/p/"
nickname = "folding"
author = ep("createAuthor", api_url, api_key, name=nickname)
author_id = author["data"]["authorID"]
all_pads = ep("listAllPads", api_url, api_key)
all_pads = all_pads["data"]["padIDs"]
db_filename = "folding.json"
# Make database json file when it does not exist yet
if not os.path.exists(db_filename):
with open(db_filename, "w") as out:
db = { 'messages' : [] }
out.write(json.dumps(db, indent=4))
out.close()
# Read db
db_file = open(db_filename).read()
db = json.loads(db_file)
while True:
for pad in all_pads:
# Get the current chat_head of this pad
chat_head_data = ep("getChatHead", api_url, api_key, padID=pad)
chat_head = chat_head_data["data"]["chatHead"]
# If this pad is not in the database yet
if not pad in db:
# Then create an entry for this pad
db[pad] = chat_head
# Read latest chat_head from db
latest_chat_head = db[pad]
# If the last chat_head is lower then the current one
if int(latest_chat_head) < chat_head:
# Check how many messages have been sent
num_of_messages = chat_head - int(latest_chat_head)
print(num_of_messages)
# Get latest num message(s)
chat_history = ep("getChatHistory", api_url, api_key, padID=pad)
print(chat_history)
# Loop through the last num_of_messages
for num in range(num_of_messages):
print('------------')
num = num_of_messages - num
last_message = chat_history["data"]["messages"][-num]["text"]
last_author_id = chat_history["data"]["messages"][-num]["userId"]
last_author_name = chat_history["data"]["messages"][-num]["userName"]
last_timestamp = chat_history["data"]["messages"][-num]["time"]
print(num, last_message)
# If the bot is called, using @bot
if "<fold>" in last_message:
# Say that the message is folded
reply = f"{ last_author_name }, your message is folded onto the resonance board."
ep("appendChatMessage", api_url, api_key, padID=pad, text=reply, authorID=author_id)
# Store the message in the list folds
message = last_message.replace("<fold>", "")
message = f"<b>folding from <a href='{ pad_url }{ pad }'>{ pad }</a> by { last_author_name }</b>: { message }"
db['messages'].append(message)
# Update the db with the latest chat_head
db[pad] = str(chat_head)
sleep(5)
# Write the db back to file
with open(db_filename, "w") as db_out:
db_out.write(json.dumps(db, indent=4))
# Save the message to a .html file using a jinja template
template = jinja2.Template(open("/srv/folds/templates/folds.html").read())
html = template.render(folds=db["messages"])
with open("/var/www/html/folds.html", "w") as out:
out.write(html)
# Pause 60 seconds between each loop through all the pads
sleep(60)

2
requirements.txt

@ -0,0 +1,2 @@
Jinja2==2.11.3
MarkupSafe==2.0.1

16
templates/folds.html

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<base target="_blank">
<title>rosa folds</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="folds-wrapper">
{% for fold in folds|reverse %}
<p class="fold">{{ fold }}</p>
{% endfor %}
</div>
</body>
</html>

21
websocket-server.py

@ -0,0 +1,21 @@
# WS server that sends messages every second
import asyncio
import datetime
import random
import websockets
import ssl
async def time(websocket, path):
while True:
with open('/var/www/html/folds.html') as myinput:
folds = myinput.read()
print(folds)
await websocket.send(folds)
await asyncio.sleep(1)
start_server = websockets.serve(time, "0.0.0.0", 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Loading…
Cancel
Save