Compare commits

...

15 Commits

Author SHA1 Message Date
bf26c3c63c Merge pull request 'Improve listdose output format' (#16) from enhance/listdose_format into master
Reviewed-on: #16
2024-12-15 13:12:18 +01:00
d28f2032cd
Improve listdose output format
Sort output with most recent first. And improve reply string

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2024-12-10 23:35:08 +05:30
f53ddf450c Merge pull request 'Drug filtering added to listdose' (#14) from feat/listdose_drug into master
Reviewed-on: #14
Reviewed-by: Georg Pfuetzenreuter <mail@georg-pfuetzenreuter.net>
2024-11-29 23:22:27 +01:00
bcb385d3e8
Drug lookup added to listdose
listdose now supports filtering with drug

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2024-11-30 03:48:10 +05:30
816ce22eca Merge pull request 'Clean up' (#12) from clean_up into master
Reviewed-on: #12
Reviewed-by: Georg Pfuetzenreuter <mail@georg-pfuetzenreuter.net>
2024-11-01 20:46:43 +01:00
41f4e7d749
Remove Unneeded Deps
Contained imports which weren't being used.
 They have been removed.

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2024-11-02 01:00:54 +05:30
4c7f27393e
Remove Lookup Logic
Remove TripSit API lookup logic. Clear out commented blocks wrt same.

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2024-11-02 00:58:58 +05:30
fe1554b925 Merge pull request 'Implement dose lookup' (#10) from grepdose into master
Reviewed-on: #10
2024-10-30 00:02:06 +01:00
658302de4b
Implement dose lookup
Adds ability to lookup the last logged dose for a drug.

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2024-10-30 03:30:55 +05:30
844491972e Merge pull request 'Commit manual changes' (#9) from production into master
Reviewed-on: #9
2024-10-29 22:33:05 +01:00
192bd0e59e
Commit manual changes
Commit manual changes on production machine.

Signed-off-by: Pratyush Desai <pratyush.desai@liberta.casa>
2024-10-30 02:19:06 +05:30
c9c21839fe
requirements.txt 2021-09-23 16:32:40 +05:30
3d9bfef057
update gitignore 2021-09-23 16:26:59 +05:30
36d0f4b2f7 fix gpg key violation 2021-07-14 13:50:20 +05:30
bf8d055424
fix time formatting 2021-07-14 05:48:16 +05:30
3 changed files with 123 additions and 93 deletions

4
.gitignore vendored
View File

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

210
plugin.py
View File

@ -2,7 +2,7 @@
# Copyright (c) 2020, mogad0n
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# Redistribution and use in source and binary forms, with or wthout
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
@ -28,19 +28,13 @@
###
from humanize import ordinal
from supybot import utils, plugins, ircutils, callbacks, world, conf, log
from supybot.commands import *
from num2words import num2words
import dateutil.parser
import json
import requests
import pickle
import sys
import datetime
import time
import pytz
try:
@ -53,10 +47,6 @@ except ImportError:
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"]
METHODS = {
@ -73,6 +63,7 @@ METHODS = {
"smoked": ["Smoked"]
}
class Tripsit(callbacks.Plugin):
"""Harm-Reduction tools from tripsit's tripbot and the tripsitwiki"""
threaded = True
@ -107,54 +98,6 @@ class Tripsit(callbacks.Plugin):
world.flushers.remove(self._flushDb)
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):
"""<timezone>
@ -182,35 +125,16 @@ class Tripsit(callbacks.Plugin):
[--ago] and [ROA] fields are optional
"""
opts = dict(opts)
r = requests.get(url_drug, params={"name": name}).json()
found_method = False
onset = None
if not r['err']:
drug = r['data'][0]
drug_name = drug['pretty_name']
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"])
methods = []
if method:
methods = [method.lower()]
methods = METHODS.get(methods[0], methods)
drug_and_method = name
if method:
if not found_method:
method = method.title()
method = method
drug_and_method = "%s via %s" % (drug_and_method, method)
else:
method = 'Undefined'
@ -248,16 +172,17 @@ class Tripsit(callbacks.Plugin):
self.db[nick] = {'timezone': timezone, 'doses': doses}
if dose_td == 0:
re = utils.str.format("You dosed %s of %s at %s, %s", dose, drug_and_method, str(time), timezone)
re = utils.str.format("You dosed %s of %s at %s, %s", dose, drug_and_method, time.strftime("%c"), timezone)
if onset is not None:
re += utils.str.format(". You should start feeling effects %s from now", onset)
else:
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())
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())
if onset is not None:
re += utils.str.format(". You should have/will start feeling effects %s from/after dosing", onset)
irc.reply(re)
@wrap([optional('postiveInt')])
@wrap([optional('positiveInt')])
def undose(self, irc, msg, args, entry):
"""<n>
@ -281,8 +206,7 @@ class Tripsit(callbacks.Plugin):
else:
irc.error(f'No doses saved for {nick}')
@wrap()
def doseslogged(self, irc, msg, args, history):
def doseslogged(self, irc, msg, args):
"""
This command takes no arguments.
@ -292,12 +216,15 @@ class Tripsit(callbacks.Plugin):
if nick in self.db:
try:
nick_dose_log_count = len(self.db[nick]['doses'])
irc.reply(f"{nick} has logged {nick_dose_log_count} doses")
nick_dose_log_since = self.db[nick]['doses'][0]["time"]
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:
irc.error(f"Can't seem to do math, check logs")
irc.error("Can't seem to do math, check logs")
else:
irc.error(f"No doses saved for {nick}")
doseslogged = wrap(doseslogged)
@wrap([optional('positiveInt')])
def lastdose(self, irc, msg, args, history):
@ -326,13 +253,112 @@ class Tripsit(callbacks.Plugin):
since_dose_seconds = since_dose.total_seconds()
if history:
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, str(dose_time), 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, dose_time.strftime("%c"), timezone, since_dose_seconds)
else:
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)
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)
irc.reply(re)
else:
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

View File

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