Skip to content

Commit

Permalink
Merge pull request #23 from guerda/screenshot-toot
Browse files Browse the repository at this point in the history
feat(screenshot): add screenshot of energy-charts traffic light in the post
  • Loading branch information
guerda authored Dec 9, 2024
2 parents d0058a8 + fc7d9b5 commit 97f28dd
Show file tree
Hide file tree
Showing 6 changed files with 189 additions and 18 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9", "3.10", "3.11"]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]

steps:
- uses: actions/checkout@v4
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.env
*.log
eue-mastobot-job.sh
stromampel.png
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ name = "pypi"
requests = "*"
"mastodon.py" = "*"
python-dotenv = "*"
playwright = "*"

[dev-packages]
ruff = "*"
Expand Down
126 changes: 118 additions & 8 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,22 @@ Das Script nutzt die API von Energy Charts (https://api.energy-charts.info/).

Der Bot läuft aktuell unter https://ruhr.social/@erneuerbarer_ueberschuss

Permissions
===========
Diese Permissions braucht die Mastodon-Applikation, um Beiträge mit Medien zu veröffentlichen:

* read
* write:statuses
* write:media

Installation
============

pipenv install oder pipenv install --dev sollte ausreichen

Danach muss für die Screenshots Folgendes ausgeführt werden:

pipenv shell
playwright install

Damit wird Chromium installiert, mit dem die Screenshots erzeugt werden.
58 changes: 49 additions & 9 deletions euemastobot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
import logging
import os
import requests
import asyncio
from playwright.async_api import async_playwright

threshold = 100
mastodon = None


def get_time_slots():
Expand Down Expand Up @@ -46,33 +49,65 @@ def get_time_slots():
return slots


def post_timeslots_to_mastodon(time_slots):
mastodon = Mastodon(
api_base_url="https://ruhr.social",
access_token=os.getenv("ACCESS_TOKEN"),
)
def get_mastodon_client():
global mastodon
if mastodon is None:
logger.info("Create new Mastodon client")
mastodon = Mastodon(
api_base_url="https://ruhr.social",
access_token=os.getenv("ACCESS_TOKEN"),
)
return mastodon


def post_timeslots_to_mastodon(time_slots, attach_screenshot=False, media_id=None):
mastodon = get_mastodon_client()
slot_text = ", ".join(["{} - {}".format(slot[0], slot[1]) for slot in time_slots])
status_text = """Der Anteil der erneuerbaren Energien in Deutschland liegt voraussichtlich heute zwischen {} über {}%.
Daten via https://energy-charts.info/charts/consumption_advice/chart.htm""".format(
slot_text, threshold
)
status = mastodon.status_post(status_text, language="de")
status = mastodon.status_post(status_text, language="de", media_ids=media_id)
logger.info("Posted status #{} ({})".format(status["id"], status["created_at"]))
return status["url"]


async def create_screenshot_of_traffic_light():
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page(locale="de-DE")
await page.set_viewport_size({"width": 765, "height": 500})
await page.goto(
"https://energy-charts.info/charts/consumption_advice/chart.htm?l=de&c=DE"
)
await page.locator("div#inhalt .chartCard:first-child").screenshot(
path="stromampel.png"
)
await browser.close()
logger.info("Created screenshot")
mastodon = get_mastodon_client()
result = mastodon.media_post(
"stromampel.png",
description="Screenshot of energy-charts.info"
"s traffic light for energy production",
file_name="Stromampel.png",
)
logger.info("Uploaded screenshot with ID {}".format(result["id"]))
return result["id"]


if __name__ == "__main__":
FORMAT = "%(asctime)s [%(levelname)s] %(name)s - %(message)s"
date_format = '%d.%m. %H:%M:%S'
date_format = "%d.%m. %H:%M:%S"
logging.basicConfig(level=logging.INFO, format=FORMAT, datefmt=date_format)
logger = logging.getLogger("euemastobot")

time_slots = None
try:
time_slots = get_time_slots()
except Exception as e:
logging.exception("Could not get forecast data", e)
logger.exception("Could not get forecast data", e)

if time_slots is not None:
if len(time_slots) == 0:
Expand All @@ -83,5 +118,10 @@ def post_timeslots_to_mastodon(time_slots):
)
else:
dotenv.load_dotenv()
post_url = post_timeslots_to_mastodon(time_slots)
media_id = None
try:
media_id = asyncio.run(create_screenshot_of_traffic_light())
except Exception as e:
logger.error("Could not create screenshot", e)
post_url = post_timeslots_to_mastodon(time_slots, media_id=media_id)
logger.info("Successfully posted: {}".format(post_url))

0 comments on commit 97f28dd

Please sign in to comment.