romeotools/classes/attachment.py

39 lines
No EOL
1.3 KiB
Python

from urllib.request import urlopen
from .http import HTTPRequest
class Attachment:
def __init__(self, id, owner, token, message, content=None, retrieve=True):
self.id = id
self.owner = owner
self.token = token
self.content = content if content else self.get_content() if retrieve else None
self.message = message
def get_content(self, exceptions=False):
try:
return urlopen(HTTPRequest(IMAGE_URL % self.token)).read()
except:
if not exceptions:
return False
raise
def to_database(self, db=None, exceptions=False):
try:
db = db or Database()
db.execute("INSERT INTO attachment VALUES (?, ?, ?, ?, ?);",
(self.id, self.owner, self.token, self.message, self.content))
except:
if not exceptions:
return
raise
@classmethod
def from_dict(cls, attachment, message_id):
if attachment["type"] == "IMAGE":
try:
return cls(attachment["params"]["id"], attachment["params"]["owner_id"], attachment["params"]["url_token"], message_id)
except Exception as e:
print(f"Error getting attachment: {e}")
return False