blob: 21e7e8e1813d81e80d9d8bdf4431896928f804a1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
import json
import logging
import requests
from project.basecommunicator import BaseCommunicator
class ShoutboxCommunicator(BaseCommunicator):
"""Class for communication with the shoutbox API"""
url = "http://localhost:8000"
interval = 10
token = ""
@staticmethod
def get_url():
return "{}/api/last?seconds={}".format(ShoutboxCommunicator.url, ShoutboxCommunicator.interval)
@staticmethod
def post_url():
return ShoutboxCommunicator.url + "/api/post"
@staticmethod
def fetch():
"""Get and return a list of new messages from the API"""
try:
r = requests.get(ShoutboxCommunicator.get_url())
logging.info("Response from API OK.")
except:
logging.warning("Failed to get response from API! ({})".format(ShoutboxCommunicator.get_url()))
return
try:
content = json.loads(r.text)
except:
logging.warning("Could not parse JSON from request!")
return
if len(content) > 0:
logging.info("Messages from shoutbox:")
for msg in content:
logging.info("{}: {}".format(msg["user"], msg["text"]))
return content
@staticmethod
def send(data):
"""Send a message to the API"""
post_params = "?user={}&text={}&id={}&ip={}×tamp={}&api_token={}".format(
data["user"], data["text"], data["id"], data["ip"], data["timestamp"],
ShoutboxCommunicator.token
)
try:
requests.post(ShoutboxCommunicator.post_url() + post_params, "")
user = data["user"]
logging.info("Sent message from {} to shoutbox.".format(user))
except:
logging.warning("Failed to send message to shoutbox API!")
|