Skip to content

Commit e6789fe

Browse files
committed
Refactor horoscope.py db queries
1 parent 25c4cf9 commit e6789fe

1 file changed

Lines changed: 21 additions & 7 deletions

File tree

plugins/horoscope.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import requests
44
from bs4 import BeautifulSoup
5-
from sqlalchemy import Table, String, Column
5+
from sqlalchemy import Table, String, Column, select
66

77
from cloudbot import hook
88
from cloudbot.util import database
@@ -15,6 +15,22 @@
1515
)
1616

1717

18+
def get_sign(db, nick):
19+
row = db.execute(select([table.c.sign]).where(table.c.nick == nick.lower())).fetchone()
20+
if not row:
21+
return None
22+
23+
return row[0]
24+
25+
26+
def set_sign(db, nick, sign):
27+
res = db.execute(table.update().values(sign=sign.lower()).where(table.c.nick == nick.lower()))
28+
if res.rowcount == 0:
29+
db.execute(table.insert().values(nick=nick.lower(), sign=sign.lower()))
30+
31+
db.commit()
32+
33+
1834
@hook.command(autohelp=False)
1935
def horoscope(text, db, bot, nick, notice, notice_doc, reply, message):
2036
"""[sign] - get your horoscope"""
@@ -43,11 +59,11 @@ def horoscope(text, db, bot, nick, notice, notice_doc, reply, message):
4359
sign = text.strip().lower()
4460

4561
if not sign:
46-
sign = db.execute("SELECT sign FROM horoscope WHERE "
47-
"nick=lower(:nick)", {'nick': nick}).fetchone()
62+
sign = get_sign(db, nick)
4863
if not sign:
4964
notice_doc()
5065
return
66+
5167
sign = sign[0].strip().lower()
5268

5369
if sign not in signs:
@@ -70,11 +86,9 @@ def horoscope(text, db, bot, nick, notice, notice_doc, reply, message):
7086
soup = BeautifulSoup(request.text)
7187

7288
horoscope_text = soup.find("div", class_="horoscope-content").find("p").text
73-
result = "\x02{}\x02 {}".format(text, horoscope_text)
89+
result = "\x02{}\x02 {}".format(sign, horoscope_text)
7490

7591
if text and not dontsave:
76-
db.execute("insert or replace into horoscope(nick, sign) values (:nick, :sign)",
77-
{'nick': nick.lower(), 'sign': sign})
78-
db.commit()
92+
set_sign(db, nick, sign)
7993

8094
message(result)

0 commit comments

Comments
 (0)