Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions discord_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
Connecting, sending and receiving messages and doing custom actions.
"""

import logging

import discord

from bot import Bot
Expand Down
16 changes: 9 additions & 7 deletions irc_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")

Expand All @@ -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):
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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"""
Expand Down
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
33 changes: 2 additions & 31 deletions marvin_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@
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
import logging
import random
import requests

from bs4 import BeautifulSoup

LOG = logging.getLogger("action")

Expand All @@ -37,7 +35,6 @@ def getAllActions():
marvinSmile,
marvinStrip,
marvinTimeToBBQ,
marvinBirthday,
marvinNameday,
marvinUptime,
marvinStream,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
8 changes: 1 addition & 7 deletions marvin_strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}",
Expand Down Expand Up @@ -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",
Expand Down
41 changes: 23 additions & 18 deletions test_marvin_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand Down
Loading