Passed
Push — master ( 4db5b8...de8749 )
by Mikael
03:11
created

marvin_actions.formatNames()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
#! /usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
"""
5
Make actions for Marvin, one function for each action.
6
"""
7 1
from urllib.parse import quote_plus
8 1
from urllib.request import urlopen
9 1
import calendar
10 1
import datetime
11 1
import json
12 1
import logging
13 1
import random
14 1
import requests
15
16 1
from bs4 import BeautifulSoup
17
18 1
LOG = logging.getLogger("action")
19
20 1
def getAllActions():
21
    """
22
    Return all actions in an array.
23
    """
24
    return [
25
        marvinExplainShell,
26
        marvinGoogle,
27
        marvinLunch,
28
        marvinVideoOfToday,
29
        marvinWhoIs,
30
        marvinHelp,
31
        marvinSource,
32
        marvinBudord,
33
        marvinQuote,
34
        marvinWeather,
35
        marvinSun,
36
        marvinSayHi,
37
        marvinSmile,
38
        marvinStrip,
39
        marvinTimeToBBQ,
40
        marvinBirthday,
41
        marvinNameday,
42
        marvinUptime,
43
        marvinStream,
44
        marvinPrinciple,
45
        marvinJoke,
46
        marvinCommit
47
    ]
48
49
50
# Load all strings from file
51 1
with open("marvin_strings.json", encoding="utf-8") as f:
52 1
    STRINGS = json.load(f)
53
54
55 1
def getString(key, key1=None):
56
    """
57
    Get a string from the string database.
58
    """
59 1
    data = STRINGS[key]
60 1
    if isinstance(data, list):
61 1
        res = data[random.randint(0, len(data) - 1)]
62 1
    elif isinstance(data, dict):
63 1
        if key1 is None:
64 1
            res = data
65
        else:
66 1
            res = data[key1]
67 1
            if isinstance(res, list):
68 1
                res = res[random.randint(0, len(res) - 1)]
69 1
    elif isinstance(data, str):
70 1
        res = data
71
72 1
    return res
0 ignored issues
show
introduced by
The variable res does not seem to be defined for all execution paths.
Loading history...
73
74
75 1
def marvinSmile(row):
76
    """
77
    Make Marvin smile.
78
    """
79 1
    msg = None
80 1
    if any(r in row for r in ["smile", "le", "skratta", "smilies"]):
81 1
        msg = getString("smile")
82 1
    return msg
83
84
85 1
def wordsAfterKeyWords(words, keyWords):
86
    """
87
    Return all items in the words list after the first occurence
88
    of an item in the keyWords list.
89
    """
90 1
    kwIndex = []
91 1
    for kw in keyWords:
92 1
        if kw in words:
93 1
            kwIndex.append(words.index(kw))
94
95 1
    if not kwIndex:
96 1
        return None
97
98 1
    return words[min(kwIndex)+1:]
99
100
101 1
def marvinGoogle(row):
102
    """
103
    Let Marvin present an url to google.
104
    """
105 1
    query = wordsAfterKeyWords(row, ["google", "googla"])
106 1
    if not query:
107 1
        return None
108
109 1
    searchStr = " ".join(query)
110 1
    url = "https://www.google.se/search?q="
111 1
    url += quote_plus(searchStr)
112 1
    msg = getString("google")
113 1
    return msg.format(url)
114
115
116 1
def marvinExplainShell(row):
117
    """
118
    Let Marvin present an url to the service explain shell to
119
    explain a shell command.
120
    """
121 1
    query = wordsAfterKeyWords(row, ["explain", "förklara"])
122 1
    if not query:
123 1
        return None
124 1
    cmd = " ".join(query)
125 1
    url = "https://explainshell.com/explain?cmd="
126 1
    url += quote_plus(cmd, "/:")
127 1
    msg = getString("explainShell")
128 1
    return msg.format(url)
129
130
131 1
def marvinSource(row):
132
    """
133
    State message about sourcecode.
134
    """
135 1
    msg = None
136 1
    if any(r in row for r in ["källkod", "source"]):
137 1
        msg = getString("source")
138
139 1
    return msg
140
141
142 1
def marvinBudord(row):
143
    """
144
    What are the budord for Marvin?
145
    """
146 1
    msg = None
147 1
    if any(r in row for r in ["budord", "stentavla"]):
148 1
        if any(r in row for r in ["#1", "1"]):
149 1
            msg = getString("budord", "#1")
150 1
        elif any(r in row for r in ["#2", "2"]):
151 1
            msg = getString("budord", "#2")
152 1
        elif any(r in row for r in ["#3", "3"]):
153 1
            msg = getString("budord", "#3")
154 1
        elif any(r in row for r in ["#4", "4"]):
155 1
            msg = getString("budord", "#4")
156 1
        elif any(r in row for r in ["#5", "5"]):
157 1
            msg = getString("budord", "#5")
158
159 1
    return msg
160
161
162 1
def marvinQuote(row):
163
    """
164
    Make a quote.
165
    """
166 1
    msg = None
167 1
    if any(r in row for r in ["quote", "citat", "filosofi", "filosofera"]):
168 1
        msg = getString("hitchhiker")
169
170 1
    return msg
171
172
173 1
def videoOfToday():
174
    """
175
    Check what day it is and provide a url to a suitable video together with a greeting.
176
    """
177 1
    weekday = datetime.date.today().strftime("%A")
178 1
    day = getString("video-of-today", weekday)
179 1
    msg = day.get("message")
180
181 1
    if day:
182 1
        msg += " En passande video är " + day.get("url")
183
    else:
184
        msg += " Jag har ännu ingen passande video för denna dagen."
185
186 1
    return msg
187
188
189 1
def marvinVideoOfToday(row):
190
    """
191
    Show the video of today.
192
    """
193 1
    msg = None
194 1
    if any(r in row for r in ["idag", "dagens"]):
195 1
        if any(r in row for r in ["video", "youtube", "tube"]):
196 1
            msg = videoOfToday()
197
198 1
    return msg
199
200
201 1
def marvinWhoIs(row):
202
    """
203
    Who is Marvin.
204
    """
205 1
    msg = None
206 1
    if all(r in row for r in ["vem", "är"]):
207 1
        msg = getString("whois")
208
209 1
    return msg
210
211
212 1
def marvinHelp(row):
213
    """
214
    Provide a menu.
215
    """
216 1
    msg = None
217 1
    if any(r in row for r in ["hjälp", "help", "menu", "meny"]):
218 1
        msg = getString("menu")
219
220 1
    return msg
221
222
223 1
def marvinSayHi(row):
224
    """
225
    Say hi with a nice message.
226
    """
227 1
    msg = None
228 1
    if any(r in row for r in [
229
            "snälla", "hej", "tjena", "morsning", "morrn", "mår", "hallå",
230
            "halloj", "läget", "snäll", "duktig", "träna", "träning",
231
            "utbildning", "tack", "tacka", "tackar", "tacksam"
232
    ]):
233 1
        smile = getString("smile")
234 1
        hello = getString("hello")
235 1
        friendly = getString("friendly")
236 1
        msg = f"{smile} {hello} {friendly}"
237
238 1
    return msg
239
240
241 1
def marvinLunch(row):
242
    """
243
    Help decide where to eat.
244
    """
245 1
    lunchOptions = {
246
        'stan centrum karlskrona kna': 'karlskrona',
247
        'ängelholm angelholm engelholm': 'angelholm',
248
        'hässleholm hassleholm': 'hassleholm',
249
        'malmö malmo malmoe': 'malmo',
250
        'göteborg goteborg gbg': 'goteborg'
251
    }
252
253 1
    data = getString("lunch")
254
255 1
    if any(r in row for r in ["lunch", "mat", "äta", "luncha"]):
256 1
        places = data.get("location").get("bth")
257 1
        for keys, value in lunchOptions.items():
258 1
            if any(r in row for r in keys.split(" ")):
259 1
                places = data.get("location").get(value)
260
261 1
        lunchStr = getString("lunch", "message")
262 1
        return lunchStr.format(places[random.randint(0, len(places) - 1)])
263
264 1
    return None
265
266
267 1
def marvinSun(row):
268
    """
269
    Check when the sun goes up and down.
270
    """
271 1
    msg = None
272 1
    if any(r in row for r in ["sol", "solen", "solnedgång", "soluppgång", "sun"]):
273 1
        try:
274 1
            url = getString("sun", "url")
275 1
            r = requests.get(url, timeout=5)
276 1
            sundata = r.json()
277
            # Formats the time from the response to HH:mm instead of hh:mm:ss
278 1
            sunrise = sundata["results"]["sunrise"].split()[0][:-3]
279 1
            sunset = sundata["results"]["sunset"].split()[0][:-3]
280
            # The api uses AM/PM notation, this converts the sunset to 12 hour time
281 1
            sunsetHour = int(sunset.split(":")[0]) + 12
282 1
            sunset = str(sunsetHour) + sunset[-3:]
283 1
            msg = getString("sun", "msg").format(sunrise, sunset)
284 1
            return msg
285
286 1
        except Exception as e:
287 1
            LOG.error("Failed to get sun times: %s", e)
288 1
            return getString("sun", "error")
289
290
    return msg
291
292
293 1
def marvinWeather(row):
294
    """
295
    Check what the weather prognosis looks like.
296
    """
297 1
    msg = ""
298 1
    if any(r in row for r in ["väder", "vädret", "prognos", "prognosen", "smhi"]):
299 1
        forecast = ""
300 1
        observation = ""
301
302 1
        try:
303 1
            station_req = requests.get(getString("smhi", "station_url"), timeout=5)
304 1
            weather_code:int = int(station_req.json().get("value")[0].get("value"))
305
306 1
            weather_codes_req = requests.get(getString("smhi", "weather_codes_url"), timeout=5)
307 1
            weather_codes_arr: list = weather_codes_req.json().get("entry")
308
309 1
            current_weather_req = requests.get(getString("smhi", "current_weather_url"), timeout=5)
310 1
            current_w_data: list = current_weather_req.json().get("timeSeries")[0].get("parameters")
311
312 1
            for curr_w in current_w_data:
313 1
                if curr_w.get("name") == "t":
314 1
                    forecast = curr_w.get("values")[0]
315
316 1
            for code in weather_codes_arr:
317 1
                if code.get("key") == weather_code:
318 1
                    observation = code.get("value")
319
320 1
            msg = f"Karlskrona just nu: {forecast} °C. {observation}."
321
322
        except Exception as e:
323
            LOG.error("Failed to get weather: %s", e)
324
            msg: str = getString("smhi", "failed")
325
326 1
    return msg
327
328
329 1
def marvinStrip(row):
330
    """
331
    Get a comic strip.
332
    """
333 1
    msg = None
334 1
    if any(r in row for r in ["strip", "comic", "nöje", "paus"]):
335 1
        msg = commitStrip(randomize=any(r in row for r in ["rand", "random", "slump", "lucky"]))
336 1
    return msg
337
338
339 1
def commitStrip(randomize=False):
340
    """
341
    Latest or random comic strip from CommitStrip.
342
    """
343 1
    msg = getString("commitstrip", "message")
344
345 1
    if randomize:
346 1
        first = getString("commitstrip", "first")
347 1
        last = getString("commitstrip", "last")
348 1
        rand = random.randint(first, last)
349 1
        url = getString("commitstrip", "urlPage") + str(rand)
350
    else:
351 1
        url = getString("commitstrip", "url")
352
353 1
    return msg.format(url=url)
354
355
356 1
def marvinTimeToBBQ(row):
357
    """
358
    Calcuate the time to next barbecue and print a appropriate msg
359
    """
360 1
    msg = None
361 1
    if any(r in row for r in ["grilla", "grill", "grillcon", "bbq"]):
362 1
        url = getString("barbecue", "url")
363 1
        nextDate = nextBBQ()
364 1
        today = datetime.date.today()
365 1
        daysRemaining = (nextDate - today).days
366
367 1
        if daysRemaining == 0:
368 1
            msg = getString("barbecue", "today")
369 1
        elif daysRemaining == 1:
370 1
            msg = getString("barbecue", "tomorrow")
371 1
        elif 1 < daysRemaining < 14:
372 1
            msg = getString("barbecue", "week") % nextDate
373 1
        elif 14 < daysRemaining < 200:
374 1
            msg = getString("barbecue", "base") % nextDate
375
        else:
376 1
            msg = getString("barbecue", "eternity") % nextDate
377
378 1
        msg = url + ". " + msg
379 1
    return msg
380
381 1
def nextBBQ():
382
    """
383
    Calculate the next grillcon date after today
384
    """
385
386 1
    MAY = 5
387 1
    SEPTEMBER = 9
388
389 1
    after = datetime.date.today()
390 1
    spring = thirdFridayIn(after.year, MAY)
391 1
    if after <= spring:
392 1
        return spring
393
394 1
    autumn = thirdFridayIn(after.year, SEPTEMBER)
395 1
    if after <= autumn:
396 1
        return autumn
397
398 1
    return thirdFridayIn(after.year + 1, MAY)
399
400
401 1
def thirdFridayIn(y, m):
402
    """
403
    Get the third Friday in a given month and year
404
    """
405 1
    THIRD = 2
406 1
    FRIDAY = -1
407
408
    # Start the weeks on saturday to prevent fridays from previous month
409 1
    cal = calendar.Calendar(firstweekday=calendar.SATURDAY)
410
411
    # Return the friday in the third week
412 1
    return cal.monthdatescalendar(y, m)[THIRD][FRIDAY]
413
414
415 1
def marvinBirthday(row):
416
    """
417
    Check birthday info
418
    """
419
    msg = None
420
    if any(r in row for r in ["birthday", "födelsedag"]):
421
        try:
422
            url = getString("birthday", "url")
423
            soup = BeautifulSoup(urlopen(url), "html.parser")
424
            my_list = list()
425
426
            for ana in soup.findAll('a'):
427
                if ana.parent.name == 'strong':
428
                    my_list.append(ana.getText())
429
430
            my_list.pop()
431
            my_strings = ', '.join(my_list)
432
            if not my_strings:
433
                msg = getString("birthday", "nobody")
434
            else:
435
                msg = getString("birthday", "somebody").format(my_strings)
436
437
        except Exception as e:
438
            LOG.error("Failed to get birthday: %s", e)
439
            msg = getString("birthday", "error")
440
441
    return msg
442
443 1
def marvinNameday(row):
444
    """
445
    Check current nameday
446
    """
447 1
    msg = None
448 1
    if any(r in row for r in ["nameday", "namnsdag"]):
449 1
        try:
450 1
            now = datetime.datetime.now()
451 1
            raw_url = "https://api.dryg.net/dagar/v2.1/{year}/{month}/{day}"
452 1
            url = raw_url.format(year=now.year, month=now.month, day=now.day)
453 1
            r = requests.get(url, timeout=5)
454 1
            nameday_data = r.json()
455 1
            names = nameday_data["dagar"][0]["namnsdag"]
456 1
            parsed_names = formatNames(names)
457 1
            if names:
458 1
                msg = getString("nameday", "somebody").format(parsed_names)
459
            else:
460 1
                msg = getString("nameday", "nobody")
461 1
        except Exception as e:
462 1
            LOG.error("Failed to get nameday: %s", e)
463 1
            msg = getString("nameday", "error")
464 1
    return msg
465
466 1
def formatNames(names):
467
    """
468
    Parses namedata from nameday API
469
    """
470 1
    if len(names) > 1:
471 1
        return " och ".join([", ".join(names[:-1])] + names[-1:])
472 1
    return "".join(names)
473
474 1
def marvinUptime(row):
475
    """
476
    Display info about uptime tournament
477
    """
478 1
    msg = None
479 1
    if "uptime" in row:
480 1
        msg = getString("uptime", "info")
481 1
    return msg
482
483 1
def marvinStream(row):
484
    """
485
    Display info about stream
486
    """
487 1
    msg = None
488 1
    if any(r in row for r in ["stream", "streama", "ström", "strömma"]):
489 1
        msg = getString("stream", "info")
490 1
    return msg
491
492 1
def marvinPrinciple(row):
493
    """
494
    Display one selected software principle, or provide one as random
495
    """
496 1
    msg = None
497 1
    if any(r in row for r in ["principle", "princip", "principer"]):
498 1
        principles = getString("principle")
499 1
        principleKeys = list(principles.keys())
500 1
        matchedKeys = [k for k in row if k in principleKeys]
501 1
        if matchedKeys:
502 1
            msg = principles[matchedKeys.pop()]
503
        else:
504 1
            msg = principles[random.choice(principleKeys)]
505 1
    return msg
506
507 1
def getJoke():
508
    """
509
    Retrieves joke from api.chucknorris.io/jokes/random?category=dev
510
    """
511 1
    try:
512 1
        url = getString("joke", "url")
513 1
        r = requests.get(url, timeout=5)
514 1
        joke_data = r.json()
515 1
        return joke_data["value"]
516 1
    except Exception as e:
517 1
        LOG.error("Failed to get joke: %s", e)
518 1
        return getString("joke", "error")
519
520 1
def marvinJoke(row):
521
    """
522
    Display a random Chuck Norris joke
523
    """
524 1
    msg = None
525 1
    if any(r in row for r in ["joke", "skämt", "chuck norris", "chuck", "norris"]):
526 1
        msg = getJoke()
527 1
    return msg
528
529 1
def getCommit():
530
    """
531
    Retrieves random commit message from whatthecommit.com/index.html
532
    """
533 1
    try:
534 1
        url = getString("commit", "url")
535 1
        r = requests.get(url, timeout=5)
536 1
        res = r.text.strip()
537 1
        msg = f"Använd detta meddelandet: '{res}'"
538 1
        return msg
539 1
    except Exception as e:
540 1
        LOG.error("Failed to get commit message: %s", e)
541 1
        return getString("commit", "error")
542
543 1
def marvinCommit(row):
544
    """
545
    Display a random commit message
546
    """
547 1
    msg = None
548 1
    if any(r in row for r in ["commit", "-m"]):
549 1
        msg = getCommit()
550
    return msg
551