diff --git a/discord_bot.py b/discord_bot.py index 49d1b74..25574d9 100644 --- a/discord_bot.py +++ b/discord_bot.py @@ -7,8 +7,6 @@ Connecting, sending and receiving messages and doing custom actions. """ -import logging - import discord from bot import Bot diff --git a/irc_bot.py b/irc_bot.py index 1e54ba8..645cfcb 100755 --- a/irc_bot.py +++ b/irc_bot.py @@ -56,26 +56,26 @@ def connectToServer(self): # Send the nick to server nick = self.CONFIG["nick"] if nick: - msg = 'NICK {NICK}\r\n'.format(NICK=nick) + msg = f'NICK {nick}\r\n' self.sendMsg(msg) else: LOG.info("Ignore sending nick, missing nick in configuration.") # Present yourself realname = self.CONFIG["realname"] - self.sendMsg('USER {NICK} 0 * :{REALNAME}\r\n'.format(NICK=nick, REALNAME=realname)) + self.sendMsg(f'USER {nick} 0 * :{realname}\r\n') # This is my nick, i promise! ident = self.CONFIG["ident"] if ident: - self.sendMsg('PRIVMSG nick IDENTIFY {IDENT}\r\n'.format(IDENT=ident)) + self.sendMsg(f'PRIVMSG nick IDENTIFY {ident}\r\n') else: LOG.info("Ignore identifying with password, ident is not set.") # Join a channel channel = self.CONFIG["channel"] if channel: - self.sendMsg('JOIN {CHANNEL}\r\n'.format(CHANNEL=channel)) + self.sendMsg(f'JOIN {channel}\r\n') else: LOG.info("Ignore joining channel, missing channel name in configuration.") @@ -84,7 +84,7 @@ def sendPrivMsg(self, message, channel): if channel == self.CONFIG["channel"]: self.MSG_LOG.debug("%s <%s> %s", channel, self.CONFIG["nick"], message) - msg = "PRIVMSG {CHANNEL} :{MSG}\r\n".format(CHANNEL=channel, MSG=message) + msg = f"PRIVMSG {channel} :{message}\r\n" self.sendMsg(msg) def sendMsg(self, msg): @@ -103,6 +103,7 @@ def decode_irc(self, raw, preferred_encs=None): changed = False enc = None + res = None for enc in preferred_encs: try: res = raw.decode(enc) @@ -122,6 +123,7 @@ def decode_irc(self, raw, preferred_encs=None): def receive(self): """Read incoming message and guess encoding""" + lines = None try: buf = self.SOCKET.recv(2048) lines = self.decode_irc(buf) @@ -182,10 +184,10 @@ def checkIrcActions(self, words): IRC protocol. """ if words[0] == "PING": - self.sendMsg("PONG {ARG}\r\n".format(ARG=words[1])) + self.sendMsg(f"PONG {words[1]}\r\n") if words[1] == 'INVITE': - self.sendMsg('JOIN {CHANNEL}\r\n'.format(CHANNEL=words[3])) + self.sendMsg(f'JOIN {words[3]}\r\n') def checkMarvinActions(self, words): """Check if Marvin should perform any actions""" diff --git a/main.py b/main.py index f164113..32021f1 100755 --- a/main.py +++ b/main.py @@ -59,7 +59,7 @@ AUTHOR = "Mikael Roos" EMAIL = "mikael.t.h.roos@gmail.com" VERSION = "0.3.0" -MSG_VERSION = "{program} version {version}.".format(program=PROGRAM, version=VERSION) +MSG_VERSION = f"{PROGRAM} version {VERSION}." LOG = logging.getLogger("main") diff --git a/marvin_actions.py b/marvin_actions.py index ee4f7d4..460f74a 100644 --- a/marvin_actions.py +++ b/marvin_actions.py @@ -5,7 +5,6 @@ Make actions for Marvin, one function for each action. """ from urllib.parse import quote_plus -from urllib.request import urlopen import calendar import datetime import json @@ -13,7 +12,6 @@ import random import requests -from bs4 import BeautifulSoup LOG = logging.getLogger("action") @@ -37,7 +35,6 @@ def getAllActions(): marvinSmile, marvinStrip, marvinTimeToBBQ, - marvinBirthday, marvinNameday, marvinUptime, marvinStream, @@ -68,6 +65,8 @@ def getString(key, key1=None): res = res[random.randint(0, len(res) - 1)] elif isinstance(data, str): res = data + else: + raise ValueError("Unsupported datatype in strings.json") return res @@ -412,34 +411,6 @@ def thirdFridayIn(y, m): return cal.monthdatescalendar(y, m)[THIRD][FRIDAY] -def marvinBirthday(row): - """ - Check birthday info - """ - msg = None - if any(r in row for r in ["birthday", "födelsedag"]): - try: - url = getString("birthday", "url") - soup = BeautifulSoup(urlopen(url), "html.parser") - my_list = list() - - for ana in soup.findAll('a'): - if ana.parent.name == 'strong': - my_list.append(ana.getText()) - - my_list.pop() - my_strings = ', '.join(my_list) - if not my_strings: - msg = getString("birthday", "nobody") - else: - msg = getString("birthday", "somebody").format(my_strings) - - except Exception as e: - LOG.error("Failed to get birthday: %s", e) - msg = getString("birthday", "error") - - return msg - def marvinNameday(row): """ Check current nameday diff --git a/marvin_strings.json b/marvin_strings.json index c85ccc7..aadd6ca 100644 --- a/marvin_strings.json +++ b/marvin_strings.json @@ -3,7 +3,7 @@ "whois": "Jag är en tjänstvillig själ som gillar webbprogrammering. Jag bor på GitHub https://github.com/mosbth/irc2phpbb och du kan diskutera mig i forumet https://dbwebb.se/t/20", - "menu": "[ vem är | le | lunch [var] | citat | budord 1 - 5 | source | väder | solen | dagens video | nöje/paus/strip/comic [slump] | grill | birthday/födelsedag | nameday/namnsdag | google/googla | explain/förklara | uptime | stream | princip | skämt/joke | hjälp ]", + "menu": "[ vem är | le | lunch [var] | citat | budord 1 - 5 | source | väder | solen | dagens video | nöje/paus/strip/comic [slump] | grill | nameday/namnsdag | google/googla | explain/förklara | uptime | stream | princip | skämt/joke | hjälp ]", "google": [ "Googla {}", @@ -226,12 +226,6 @@ "eternity": "Det är en evighet (%s) till nästa grill." }, - "birthday": { - "url": "https://dbwebb.se/forum/", - "somebody": "Idag gratulerar vi {}", - "nobody": "Ingen som fyller år idag.", - "error": "Något gick snett, jag har inte en susning om någon fyller år eller inte." - }, "nameday": { "somebody": "Idag har {} namnsdag", "nobody": "Ingen har namnsdag idag", diff --git a/test_marvin_actions.py b/test_marvin_actions.py index 388cfa8..6a62b02 100644 --- a/test_marvin_actions.py +++ b/test_marvin_actions.py @@ -71,32 +71,37 @@ def assertBBQResponse(self, todaysDate, bbqDate, expectedMessageKey): self.assertActionOutput(marvin_actions.marvinTimeToBBQ, "dags att grilla", expected) - def assertNameDayOutput(self, exampleFile, expectedOutput): - """Assert that the proper nameday message is returned, given an inputfile""" - with open(os.path.join("namedayFiles", f"{exampleFile}.json"), "r", encoding="UTF-8") as f: + def createResponseFrom(self, directory, filename): + """Create a response object with contect as contained in the specified file""" + with open(os.path.join(directory, f"{filename}.json"), "r", encoding="UTF-8") as f: response = requests.models.Response() response._content = str.encode(json.dumps(json.load(f))) - with mock.patch("marvin_actions.requests") as r: - r.get.return_value = response - self.assertActionOutput(marvin_actions.marvinNameday, "nameday", expectedOutput) + return response + + + def assertNameDayOutput(self, exampleFile, expectedOutput): + """Assert that the proper nameday message is returned, given an inputfile""" + response = self.createResponseFrom("namedayFiles", exampleFile) + with mock.patch("marvin_actions.requests") as r: + r.get.return_value = response + self.assertActionOutput(marvin_actions.marvinNameday, "nameday", expectedOutput) + def assertJokeOutput(self, exampleFile, expectedOutput): """Assert that a joke is returned, given an input file""" - with open(os.path.join("jokeFiles", f"{exampleFile}.json"), "r", encoding="UTF-8") as f: - response = requests.models.Response() - response._content = str.encode(json.dumps(json.load(f))) - with mock.patch("marvin_actions.requests") as r: - r.get.return_value = response - self.assertActionOutput(marvin_actions.marvinJoke, "joke", expectedOutput) + response = self.createResponseFrom("jokeFiles", exampleFile) + with mock.patch("marvin_actions.requests") as r: + r.get.return_value = response + self.assertActionOutput(marvin_actions.marvinJoke, "joke", expectedOutput) + def assertSunOutput(self, expectedOutput): """Test that marvin knows when the sun comes up, given an input file""" - with open(os.path.join("sunFiles", "sun.json"), "r", encoding="UTF-8") as f: - response = requests.models.Response() - response._content = str.encode(json.dumps(json.load(f))) - with mock.patch("marvin_actions.requests") as r: - r.get.return_value = response - self.assertActionOutput(marvin_actions.marvinSun, "sol", expectedOutput) + response = self.createResponseFrom("sunFiles", "sun") + with mock.patch("marvin_actions.requests") as r: + r.get.return_value = response + self.assertActionOutput(marvin_actions.marvinSun, "sol", expectedOutput) + def testSmile(self): """Test that marvin can smile"""