Compare commits

..

No commits in common. "master" and "bdc110598ca47ebd2013533ee25df1086140d6ec" have entirely different histories.

3 changed files with 93 additions and 123 deletions

4
.gitignore vendored
View File

@ -1,5 +1,3 @@
__pycache__ __pycache__
local local
env/ venv/
.gitignore
.vscode

210
plugin.py
View File

@ -2,7 +2,7 @@
# Copyright (c) 2020, mogad0n # Copyright (c) 2020, mogad0n
# All rights reserved. # All rights reserved.
# #
# Redistribution and use in source and binary forms, with or wthout # Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met: # modification, are permitted provided that the following conditions are met:
# #
# * Redistributions of source code must retain the above copyright notice, # * Redistributions of source code must retain the above copyright notice,
@ -28,13 +28,19 @@
### ###
from humanize import ordinal
from supybot import utils, plugins, ircutils, callbacks, world, conf, log from supybot import utils, plugins, ircutils, callbacks, world, conf, log
from supybot.commands import * from supybot.commands import *
from num2words import num2words from num2words import num2words
import dateutil.parser
import json
import requests
import pickle import pickle
import sys
import datetime import datetime
import time
import pytz import pytz
try: try:
@ -47,6 +53,10 @@ except ImportError:
filename = conf.supybot.directories.data.dirize("Tripsit.db") filename = conf.supybot.directories.data.dirize("Tripsit.db")
url_drug = "http://tripbot.tripsit.me/api/tripsit/getDrug"
url_combo = "http://tripbot.tripsit.me/api/tripsit/getInteraction"
insufflated = ["Insufflation", "Insufflation-IR", "Insufflation-XR"] insufflated = ["Insufflation", "Insufflation-IR", "Insufflation-XR"]
METHODS = { METHODS = {
@ -63,7 +73,6 @@ METHODS = {
"smoked": ["Smoked"] "smoked": ["Smoked"]
} }
class Tripsit(callbacks.Plugin): class Tripsit(callbacks.Plugin):
"""Harm-Reduction tools from tripsit's tripbot and the tripsitwiki""" """Harm-Reduction tools from tripsit's tripbot and the tripsitwiki"""
threaded = True threaded = True
@ -98,6 +107,54 @@ class Tripsit(callbacks.Plugin):
world.flushers.remove(self._flushDb) world.flushers.remove(self._flushDb)
self.__parent.die() self.__parent.die()
@wrap(['something', optional('something')])
def drug(self, irc, msg, args, name, category):
"""<drug> [<category>]
fetches data on drug from tripsit wiki
"""
category_list = []
r = requests.get(url_drug, params={"name": name}).json()
if not r['err']:
drug = r["data"][0]["pretty_name"]
properties = r["data"][0]["properties"]
for key in properties:
category_list.append(key)
if category is None:
re = drug + " Available categories are: " + ", ".join(category_list)
irc.reply(re)
else:
if category in properties.keys():
re = drug + " " + properties[category]
irc.reply(re)
else:
irc.error(f"Unknown category {drug} Available categories are: " + ", ".join(category_list))
else:
irc.error("unknown drug")
def combo(self, irc, msg, args, drugA, drugB):
"""<drugA> <drugB>
fetches known interactions between the substances provided.
"""
r = requests.get(url_combo, params={f"drugA": drugA, f"drugB": drugB}).json()
if not r["err"] and r["data"][0]:
interaction = r["data"][0]
drug_a = interaction["interactionCategoryA"]
drug_b = interaction["interactionCategoryB"]
interaction_status = interaction["status"]
re = f"{drug_a} and {drug_b}: {interaction_status}"
if 'note' in interaction:
note = interaction["note"]
re += f'. Note: {note}'
irc.reply(re)
else:
irc.reply(re)
else:
irc.reply("Unknown combo (that doesn't mean it's safe). Known combos: lsd, mushrooms, dmt, mescaline, dox, nbomes, 2c-x, 2c-t-x, amt, 5-meo-xxt, cannabis, ketamine, mxe, dxm, pcp, nitrous, amphetamines, mdma, cocaine, caffeine, alcohol, ghb/gbl, opioids, tramadol, benzodiazepines, maois, ssris.")
combo = wrap(combo, [("something"), ("something")])
def set(self, irc, msg, args, timezone): def set(self, irc, msg, args, timezone):
"""<timezone> """<timezone>
@ -125,16 +182,35 @@ class Tripsit(callbacks.Plugin):
[--ago] and [ROA] fields are optional [--ago] and [ROA] fields are optional
""" """
opts = dict(opts) opts = dict(opts)
r = requests.get(url_drug, params={"name": name}).json()
found_method = False found_method = False
onset = None onset = None
methods = [] if not r['err']:
if method: drug = r['data'][0]
methods = [method.lower()] drug_name = drug['pretty_name']
methods = METHODS.get(methods[0], methods) method_keys = ['value']
methods = []
if method:
methods = [method.lower()]
methods = METHODS.get(methods[0], methods)
method_keys += methods
if 'formatted_onset' in drug:
match = list(set(method_keys)&
set(drug["formatted_onset"].keys()))
if match:
onset = drug["formatted_onset"][match[0]]
found_method = True
if match[0] in methods:
method = (match or [method])[0]
if onset and "_unit" in drug["formatted_onset"]:
onset = "%s %s" % (
onset, drug["formatted_onset"]["_unit"])
drug_and_method = name drug_and_method = name
if method: if method:
if not found_method: if not found_method:
method = method method = method.title()
drug_and_method = "%s via %s" % (drug_and_method, method) drug_and_method = "%s via %s" % (drug_and_method, method)
else: else:
method = 'Undefined' method = 'Undefined'
@ -172,17 +248,16 @@ class Tripsit(callbacks.Plugin):
self.db[nick] = {'timezone': timezone, 'doses': doses} self.db[nick] = {'timezone': timezone, 'doses': doses}
if dose_td == 0: if dose_td == 0:
re = utils.str.format("You dosed %s of %s at %s, %s", dose, drug_and_method, time.strftime("%c"), timezone) re = utils.str.format("You dosed %s of %s at %s, %s", dose, drug_and_method, str(time), timezone)
if onset is not None: if onset is not None:
re += utils.str.format(". You should start feeling effects %s from now", onset) re += utils.str.format(". You should start feeling effects %s from now", onset)
else: else:
re = utils.str.format("You dosed %s of %s at %s, %s ; %T ago", dose, drug_and_method, time.strftime("%c"), timezone, dose_td.total_seconds()) re = utils.str.format("You dosed %s of %s at %s, %s ; %T ago", dose, drug_and_method, str(time), timezone, dose_td.total_seconds())
if onset is not None: if onset is not None:
re += utils.str.format(". You should have/will start feeling effects %s from/after dosing", onset) re += utils.str.format(". You should have/will start feeling effects %s from/after dosing", onset)
irc.reply(re) irc.reply(re)
@wrap([optional('postiveInt')])
@wrap([optional('positiveInt')])
def undose(self, irc, msg, args, entry): def undose(self, irc, msg, args, entry):
"""<n> """<n>
@ -206,7 +281,8 @@ class Tripsit(callbacks.Plugin):
else: else:
irc.error(f'No doses saved for {nick}') irc.error(f'No doses saved for {nick}')
def doseslogged(self, irc, msg, args): @wrap()
def doseslogged(self, irc, msg, args, history):
""" """
This command takes no arguments. This command takes no arguments.
@ -216,15 +292,12 @@ class Tripsit(callbacks.Plugin):
if nick in self.db: if nick in self.db:
try: try:
nick_dose_log_count = len(self.db[nick]['doses']) nick_dose_log_count = len(self.db[nick]['doses'])
nick_dose_log_since = self.db[nick]['doses'][0]["time"] irc.reply(f"{nick} has logged {nick_dose_log_count} doses")
nick_dose_log_since_string = nick_dose_log_since.strftime("%c")
irc.reply(f"{nick} has logged {nick_dose_log_count} doses since {nick_dose_log_since_string}")
except IndexError: except IndexError:
irc.error("Can't seem to do math, check logs") irc.error(f"Can't seem to do math, check logs")
else: else:
irc.error(f"No doses saved for {nick}") irc.error(f"No doses saved for {nick}")
doseslogged = wrap(doseslogged)
@wrap([optional('positiveInt')]) @wrap([optional('positiveInt')])
def lastdose(self, irc, msg, args, history): def lastdose(self, irc, msg, args, history):
@ -253,112 +326,13 @@ class Tripsit(callbacks.Plugin):
since_dose_seconds = since_dose.total_seconds() since_dose_seconds = since_dose.total_seconds()
if history: if history:
history = num2words(history, to='ordinal') history = num2words(history, to='ordinal')
re = utils.str.format("Your %i last dose was %s of %s via %s at %s %s, %T ago", history, dose, drug, method, dose_time.strftime("%c"), timezone, since_dose_seconds) re = utils.str.format("Your %i last dose was %s of %s via %s at %s %s, %T ago", history, dose, drug, method, str(dose_time), timezone, since_dose_seconds)
else: else:
re = utils.str.format("You last dosed %s of %s via %s at %s %s, %T ago", dose, drug, method, dose_time.strftime("%c"), timezone, since_dose_seconds) re = utils.str.format("You last dosed %s of %s via %s at %s %s, %T ago", dose, drug, method, str(dose_time), timezone, since_dose_seconds)
irc.reply(re) irc.reply(re)
else: else:
irc.error(f'No doses saved for {nick}') irc.error(f'No doses saved for {nick}')
@wrap([getopts({'drug': 'something'}), 'positiveInt'])
def listdose(self, irc, msg, args, opts, history):
"""[--drug <drug>] <n>
Retrieves your <n> last logged doses, optionally filtered by drug.
"""
if history > 20:
irc.error("You can't retrieve more than 20 doses.")
return
opts = dict(opts)
drug_filter = opts.get('drug')
nick = msg.nick
if nick in self.db:
doses = self.db[nick]['doses']
if drug_filter:
doses = [dose for dose in doses if dose['drug'].lower() == drug_filter.lower()]
if len(doses) == 0:
irc.error(f"No doses found for drug '{drug_filter}'.")
return
if drug_filter:
irc.reply(f"Here are your last {history} dose(s) for drug '{drug_filter}':", private=True)
else:
irc.reply(f"Here are your last {history} dose(s):", private=True)
try:
for number in range(0, history):
lastdose = doses[-(number + 1)]
dose = lastdose['dose']
drug = lastdose['drug']
method = lastdose['method']
dose_time = lastdose['time']
timezone = self.db[nick]['timezone']
tz = pytz.timezone(str(timezone))
time = datetime.datetime.now(tz=tz)
since_dose = time - dose_time
since_dose_seconds = since_dose.total_seconds()
hours, remainder = divmod(since_dose_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
timedelta_str = f"{int(hours)} hours, {int(minutes)} minutes" if hours > 0 else f"{int(minutes)} minutes, {int(seconds)} seconds"
number_str = "The" if number == 0 else num2words(number + 1, to='ordinal')
re = utils.str.format(
"%s last dose: \x02Amount:\x0F %s of \x02%s\x0F \x02via\x0F %s | \x02Datetime:\x0F %s %s | \x02Time Since Last Dose:\x0F %s",
number_str, dose, drug, method, dose_time.strftime("%Y-%m-%d %H:%M:%S"), timezone, timedelta_str
)
irc.reply(re, private=True)
except IndexError:
irc.error("You haven't logged that many doses.")
return
else:
irc.error(f"No doses saved for {nick}.")
@wrap(["something"])
def grepdose(self, irc, msg, args, drug):
"""<drug>
pulls most recent dose for drug
"""
nick = msg.nick
if nick in self.db:
doselogs = self.db[nick]['doses']
found = False
for doselog in reversed(doselogs):
if doselog['drug'] == drug:
timezone = self.db[nick]['timezone']
tz = pytz.timezone(str(timezone))
now = datetime.datetime.now(tz=tz)
since_dose = now - doselog['time']
re = utils.str.format("You last dosed %s of %s via %s at %s %s, %T ago", doselog["dose"], doselog["drug"], doselog["method"], doselog["time"].strftime("%c"), timezone, since_dose.total_seconds())
irc.reply(re)
found = True
break
if not found:
irc.error(f"No doses saved for {drug}")
else:
irc.error(f"No doses saved for {nick}")
@wrap(["something"])
def amountdosed(self, irc, msg, args, drug):
"""<drug>
shows Aggregate amount in "mg" for <drug> ever logged
"""
num = 0
unit = ""
nick = msg.nick
if nick in self.db:
doselogs = self.db[nick]['doses']
for doselog in doselogs:
if doselog["drug"] == drug:
for i,c in enumerate(doselog["dose"]):
if not c.isdigit():
break
num += int(doselog["dose"][:i])
unit = doselog["dose"][i:].lstrip()
irc.reply(f"You have dosed a total of {num}{unit} amount of {drug}")
else:
irc.error(f"No doses saved for {nick}")
Class = Tripsit Class = Tripsit

View File

@ -1,5 +1,3 @@
docopt==0.6.2 docopt==0.6.2
humanize==3.11.0
logger==1.4
num2words==0.5.10 num2words==0.5.10
pytz==2020.5 pytz==2020.5