Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Points not showing up in Habitica #67

Open
johnfred4 opened this issue Apr 17, 2019 · 30 comments
Open

Points not showing up in Habitica #67

johnfred4 opened this issue Apr 17, 2019 · 30 comments
Labels
reference Solved issue sticking around for others with similar issues

Comments

@johnfred4
Copy link

When I reach the end of my "box" in Anki, the points don't show on Habitica. I've tried syncing, "Score Habitica Backlog", signing out and back in of both Anki and Habitica...now I get this message:

An error occurred in an add-on.
Please post on the add-on forum:
https://anki.tenderapp.com/discussions/add-ons

Traceback (most recent call last):
File "aqt/progress.pyc", line 69, in handler
File "aqt/main.pyc", line 110, in setupProfile
File "aqt/main.pyc", line 244, in loadProfile
File "anki/hooks.pyc", line 26, in runHook
File "/Users/benedictjfrederickiv/Library/Application Support/Anki2/addons/ankihabitica.py", line 718, in grab_profile
if ah.settings.check_db_on_profile_load and ah.settings.configured and ah.habitica.grab_scorecounter('Anki Points') and compare_score_to_db():
File "/Users/benedictjfrederickiv/Library/Application Support/Anki2/addons/AnkiHabitica/habitica_class.py", line 336, in grab_scorecounter
if self.missing[habit]:
KeyError: 'Anki Points'

When I try to "Score Habitica Backlog":

Screen Shot 2019-04-17 at 1 48 57 PM

@eshapard
Copy link
Owner

eshapard commented Apr 18, 2019 via email

@johnfred4
Copy link
Author

johnfred4 commented Apr 19, 2019 via email

@eshapard
Copy link
Owner

eshapard commented Apr 19, 2019 via email

@MedAnki
Copy link

MedAnki commented May 30, 2019

I downloaded the add-on today for the first time and have experienced the same problem.
I am using a Mac with macOS Mojave 10.14.1
and Anki version Version 2.1.11

Initially had no habit named Anki Points on Habitica, had to create one after reading this post.
No process after creating the habit.

@MedAnki
Copy link

MedAnki commented May 30, 2019

Error
An error occurred. Please start Anki while holding down the shift key, which will temporarily disable the add-ons you have installed.
If the issue only occurs when add-ons are enabled, please use the Tools>Add-ons menu item to disable some add-ons and restart Anki, repeating until you discover the add-on that is causing the problem.
When you've discovered the add-on that is causing the problem, please report the issue on the add-ons section of our support site.
Debug info:
Anki 2.1.11 (3cf770c7) Python 3.6.7 Qt 5.12.1 PyQt 5.11.3
Platform: Mac 10.14.1
Flags: frz=True ao=True sv=1
Add-ons possibly involved: Anki Habitica formerly Anki HRPG

Caught exception:
File "aqt/progress.py", line 72, in handler
File "aqt/main.py", line 122, in setupProfile
File "aqt/main.py", line 263, in loadProfile
File "anki/hooks.py", line 29, in runHook
File "/Users/anupamsinghchauhan/Library/Application Support/Anki2/addons21/954979168/init.py", line 737, in grab_profile
if ah.settings.check_db_on_profile_load and ah.settings.configured and ah.habitica.grab_scorecounter('Anki Points') and compare_score_to_db():
File "/Users/anupamsinghchauhan/Library/Application Support/Anki2/addons21/954979168/habitica_class.py", line 388, in grab_scorecounter
if self.missing[habit]:
<class 'KeyError'>: 'Anki Points'

@MedAnki
Copy link

MedAnki commented May 30, 2019

#71 I used the Python method too but nothing happened.

@MedAnki
Copy link

MedAnki commented May 30, 2019

Okay, so I did something. It kind of worked?
So I followed #71 exactly.
Whatever it had to do - it did, the add-on did not work but it reduced the number of errors.
I have no knowledge in regards to coding and all but since I can read English I tried to follow the errors - the files and location - as showed on the Anki's screen.
So there was this error pointed at line 388. I realised that all the other codes didn't have an extra line and only this one did. So I deleted that extra line and restarted Anki. The add-on worked. It even made the Habit in Habitica. Scoring also started. The only weird thing was that the in the "notes" past of the Habit, this was written :
"{"scoresincedate": 1559212199, "scorecount": 1, "sched": 12}".

It looked weird so I just deleted it - hoping it won't change anything since its written in the "notes" which is as far as I know plain text.

And now it seems to be working. Will let you know if I get a bug.

@MedAnki
Copy link

MedAnki commented May 30, 2019

So the only bug that I have been seeing since 7 hours is not in Anki but in Habitica.
The text I deleted from "notes"

The only weird thing was that the in the "notes" past of the Habit, this was written :
"{"scoresincedate": 1559212199, "scorecount": 1, "sched": 12}".

It came back again and this is how it is seen in both the webpage and iOS app:
image

And fixing this is beyond my level!

@MedAnki
Copy link

MedAnki commented May 30, 2019

P.S.: I changed "sched" from 12 to 30 in order to increase difficulty.

@eshapard
Copy link
Owner

The string in the notes is not a bug. You must keep that there. That's how the addon keeps track of things across multiple devices and multiple sessions.

Also, in which file did you delete line 388? And if you didn't delete the entire line, what change did you make?

@eshapard
Copy link
Owner

FYI: Habitica used to not show the notes, so this string that the addon sets wasn't noticeable unless you clicked on the habit... some time ago, they changed that and now notes are shown below each habit. It's a minor annoyance :-(

@MedAnki
Copy link

MedAnki commented May 31, 2019

So all I did was delete an empty line above this line. In my Mac's TextEdit app, it showed an empty line(blank line). All I did was delete the line above and aligned the text of line 388 with the line above. Restarted Anki and it started working. Pretty weird.
I did all this after following #71 procedure which did reduce the number of error shown on Anki. I don't know whether #71 is a required step or not.

While seeing the code in GitHub there was no empty line, I don't know why there was in my Mac's, but there was.

@eshapard
Copy link
Owner

eshapard commented May 31, 2019 via email

@MedAnki
Copy link

MedAnki commented May 31, 2019

Oh yeah like you told me

What I am saying is that in the code that was in my files, there was a blank line and deleting that line fixed it

It can be a fluke or just the work of the #71 but it was the process that I went through

@eshapard
Copy link
Owner

eshapard commented May 31, 2019 via email

@MedAnki
Copy link

MedAnki commented May 31, 2019

#67 (comment)

Refer to this

@eshapard
Copy link
Owner

Sorry, I sent some of those comments through email, and for some reason it took a long time for them to show up in the thread so I just posted comments directly on the site.... that's why i seem to be repeating myself.

@eshapard eshapard added the reference Solved issue sticking around for others with similar issues label Jun 3, 2019
@johnfred4
Copy link
Author

Still not working. Tried deleting my "Anki Points" Habit, letting the plugin try to add it automatically; it didn't. Still getting the message saying it can't connect.

An error occurred in an add-on.
Please post on the add-on forum:
https://anki.tenderapp.com/discussions/add-ons

Traceback (most recent call last):
File "aqt/progress.pyc", line 69, in handler
File "aqt/main.pyc", line 110, in setupProfile
File "aqt/main.pyc", line 244, in loadProfile
File "anki/hooks.pyc", line 26, in runHook
File "/Users/benedictjfrederickiv/Library/Application Support/Anki2/addons/ankihabitica.py", line 718, in grab_profile
if ah.settings.check_db_on_profile_load and ah.settings.configured and ah.habitica.grab_scorecounter('Anki Points') and compare_score_to_db():
File "/Users/benedictjfrederickiv/Library/Application Support/Anki2/addons/AnkiHabitica/habitica_class.py", line 336, in grab_scorecounter
if self.missing[habit]:
KeyError: 'Anki Points'

@MedAnki
Copy link

MedAnki commented Jun 11, 2019

Try using my method..?

@johnfred4
Copy link
Author

I also tried searching for any extra lines in between lines of code (mine seems to be pointing towards line 336) and deleting them. Still no luck/same error message saying it can't connect.

@MedAnki

This comment has been minimized.

@MedAnki
Copy link

MedAnki commented Jun 11, 2019

First follow #71 method,
then paste the above comment
restart anki

@johnfred4
Copy link
Author

Would the fact that I'm using Anki 2.0 affect whether or not to follow #71 ? Also am I copy/pasting that entire post or just what is in the "white" (or both the white and grey boxes?)

@johnfred4
Copy link
Author

image

@MedAnki
Copy link

MedAnki commented Jun 11, 2019

Oh I have Anki 2.1
so that might change something

You were supposed to copy paste the whole thing. things other than the box too.

I am just trying to create a similar situation for you so that it might work for you.

I am a medical student and I have little to no idea about coding! :)

@MedAnki
Copy link

MedAnki commented Jun 11, 2019

#!/usr/bin/python
from .habitica_api import HabiticaAPI
import os
import sys
import json
import datetime
import time
import _thread
from aqt import *
from aqt.main import AnkiQt
from anki.hooks import runHook
from . import db_helper
from anki.utils import intTime
from aqt.utils import tooltip
from .ah_common import AnkiHabiticaCommon as ah


# TODO: make sure script can survive internet outages.
class Habitica(object):
    allow_threads = True  # startup config processes checking habits, etc.
    allow_post_scorecounter_thread = True  # Maybe a source of database warnings?
    # find icon file
    iconfile = os.path.join(os.path.dirname(
        os.path.realpath(__file__)), "habitica_icon.png")
    offline_sincedate = intTime()  # Score Since date for when we are offline
    offline_scorecount = 0  # Starting score for offline
    offline_recover_attempt = 0  # attempt to recover from offline state every third time

    def __init__(self):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        self.api = HabiticaAPI(ah.settings.user, ah.settings.token)
        self.name = 'Anki User'
        self.lvl = 0
        self.xp = 0
        self.xt = 0
        self.gp = 0
        self.hp = 0
        self.ht = 50
        self.mp = 0
        self.mt = 0
        self.stats = {}
        self.hnote = {}
        self.habit_grabbed = {}  # marked true when we get scorecounter.
        # holder for habit IDs
        self.habit_id = ah.config[ah.settings.profile]['habit_id']
        self.missing = {}  # holds missing habits
        self.init_update()  # check habits, grab user object, get avatar
        if ah.settings.keep_log:
            ah.log.debug("End function")

    def init_update(self):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        for habit in ah.settings.habitlist:
            self.habit_grabbed[habit] = False
            # create a thread to check the habit as to not slow down
            # the startup process
            if Habitica.allow_threads:
                _thread.start_new_thread(self.check_anki_habit, (habit,))
            else:
                self.check_anki_habit(habit)
        # Grab user object in the background
        if Habitica.allow_threads:
            _thread.start_new_thread(self.init_grab_stats, ())
        else:
            self.init_grab_stats()
        # Grab avatar from habitica
        if Habitica.allow_threads:
            _thread.start_new_thread(self.save_avatar, ())
        else:
            self.save_avatar()
        if ah.settings.keep_log:
            ah.log.debug("End function")

    # Try updating stats silently on init
    def init_grab_stats(self):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        try:
            self.update_stats(True)
        except:
            if ah.settings.keep_log:
                ah.log.error("End function")
            return

    # Save avatar from habitica as png
    def save_avatar(self):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        # Check to see if we are downloading the avatar image
        if not ah.settings.download_avatar:
            if ah.settings.keep_log:
                ah.log.debug("Function Return - not downloading avatar")
            return
        # See if there's an image for this profile
        profile_pic = ah.settings.user + ".png"  # use user id instead of profile name
        self.avatarfile = os.path.join(os.path.dirname(
            os.path.realpath(__file__)), profile_pic)
        try:
            pngfile = self.api.export_avatar_as_png()  # Grab avatar png from Habitica
            if not pngfile:
                if ah.settings.keep_log:
                    ah.log.error("End function returning: %s" % False)  # Exit if we failed
                return False  # Exit if we failed
            with open(self.avatarfile, 'wb') as outfile:
                outfile.write(pngfile)
            del pngfile
        except:
            pass
        if os.path.exists(self.avatarfile):
            # use {profile}.png as icon if it exists
            self.iconfile = self.avatarfile
        else:
            self.iconfile = Habitica.iconfile
        if ah.settings.keep_log:
            ah.log.debug("End function")

    def hrpg_showInfo(self, text):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        if ah.settings.keep_log:
            ah.log.info("Msg: %s" % text.replace('\n', ' '))
        # display a small message window with an OK Button
        parent = aqt.mw.app.activeWindow() or aqt.mw
        icon = QMessageBox.Information
        mb = QMessageBox(parent)
        mb.setText(text)
        if os.path.isfile(self.iconfile):
            mb.setIconPixmap(QPixmap(self.iconfile))
        else:
            mb.setIcon(icon)
        mb.setWindowModality(Qt.WindowModal)
        mb.setWindowTitle("Anki Habitica")
        b = mb.addButton(QMessageBox.Ok)
        b.setDefault(True)
        out = mb.exec_()
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % out)
        return out

    def get_user_object(self):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        out = self.api.user()
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % out)
        return out

    def update_stats(self, silent=False):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        try:
            user = self.get_user_object()
        except:
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            if ah.settings.debug:
                raise
            if not silent:
                self.hrpg_showInfo(
                    "Unable to log in to Habitica.\n\nCheck that you have the correct user-id and api-token in\n%s.\n\nThese should not be your username and password.\n\nPost at github.com/eshapard/AnkiHRPG if this issue persists." % (ah.conffile))
            return False
        self.name = user['profile']['name']
        self.stats = user['stats']
        self.lvl = self.stats['lvl']
        self.xp = self.stats['exp']
        self.gp = self.stats['gp']
        self.hp = self.stats['hp']
        self.mp = self.stats['mp']
        self.xt = self.stats['toNextLevel']
        self.ht = self.stats['maxHealth']
        self.mt = self.stats['maxMP']
        if ah.settings.keep_log:
            ah.log.debug(self.name)
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % True)
        return True

    def score_anki_points(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        try:
            habitID = self.habit_id[habit]
            out = self.api.perform_task(habitID, "up")
            if ah.settings.keep_log:
                ah.log.debug("End function returning: %s" % out)
            return out
        except:
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            if ah.settings.debug:
                raise
            return False

    def update_anki_habit(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        try:
            habitID = self.habit_id[habit]
            data = {'up': True, 'down': False, 'attribute': 'int'}
            out = self.api.update_task(habitID, data)
            if ah.settings.keep_log:
                ah.log.debug("End function returning: %s" % out)
            return out
        except:
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            if ah.settings.debug:
                raise
            return False

    # Check Anki Habit, make new one if it does not exist, and try to
    #    grab the note string.
    def check_anki_habit(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        found = False
        if ah.settings.keep_log:
            ah.log.debug("checking %s" % habit)
        if habit not in self.habit_id:
            try:
                self.habit_id[habit] = self.api.find_habit_id(habit)
                habitID = self.habit_id[habit]
            except:
                if ah.settings.keep_log:
                    ah.log.error("End function returning: %s" % False)
                if ah.settings.debug:
                    raise
                return False
        else:
            habitID = self.habit_id[habit]
            # We have an ID, but we may want to check that the habit still exists
        if ah.settings.keep_log:
            ah.log.debug("HabitID: %s" % habitID)
        if not habitID:  # find_habit_id returned False; habit not found!
            if ah.settings.keep_log:
                ah.log.warning("Habit ID Missing")
            del self.habit_id[habit]
            self.missing[habit] = True
            if ah.settings.keep_log:
                ah.log.warning("Task not found")
            self.create_missing_habit(habit)
            if ah.settings.keep_log:
                ah.log.warning("End function returning: %s" % False)
            return False
        # Check to see if habit Still exists
        if ah.settings.keep_log:
            ah.log.debug("Checking %s habit" % habit)
        if not found:
            try:
                tasks = self.api.tasks()
                if ah.settings.keep_log:
                    ah.log.debug(json.dumps(tasks))
                for t in tasks:
                    if str(t['id']) == str(habitID):
                        found = True
                if found:
                    self.missing[habit] = False
                    del tasks
                    if ah.settings.keep_log:
                        ah.log.debug("Task found")
                else:
                    self.missing[habit] = True
                    if ah.settings.keep_log:
                        ah.log.warning("Task not found")
                    self.create_missing_habit(habit)
                    del tasks
                    if ah.settings.keep_log:
                        ah.log.warning("End function returning: %s" % False)
                    return False
            except:
                pass
        # Check to see that habitica habit is set up properly
        if ah.settings.keep_log:
            ah.log.debug("Checking habit setup")
        try:
            response = self.api.task(habitID)
        except:
            if ah.settings.keep_log:
                ah.log.error("Could not retrieve task")
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            if ah.settings.debug:
                raise
            return False
        if response['down'] or response['attribute'] != "int":
            try:
                if ah.settings.keep_log:
                    ah.log.debug("Updating Habit")
                self.update_anki_habit(habitID)
                if ah.settings.keep_log:
                    ah.log.debug("End function returning: %s" % True)
                return True
            except:
                if ah.settings.keep_log:
                    ah.log.error("End function returning: %s" % False)
                if ah.settings.debug:
                    raise
                hrpg_showInfo("Your %s habit is not configured correctly yet.\nPlease set it to Up only and Mental attribute." % habit)
                return False
        if ah.settings.keep_log:
            ah.log.debug("Habit looks good")
        # Grab scorecounter from habit
        out = self.grab_scorecounter(habit)
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % out)
        return out

    # Create a missing habits
    def create_missing_habit(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        try:
            # create habit
            if ah.settings.keep_log:
                ah.log.debug("Trying to create %s habit" % habit)
            # create task on habitica
            curtime = intTime()
            self.hnote[habit] = {'scoresincedate': curtime,
                                 'scorecount': 0, 'sched': ah.settings.sched_dict[habit]}
            note = json.dumps(self.hnote[habit])
            msg = self.api.create_task(
                'habit', habit, False, note, 'int', 1, True)
            self.habit_id[habit] = str(msg['_id'])  # capture new task ID
            if ah.settings.keep_log:
                ah.log.debug("New habit created: %s" % self.habit_id[habit])
            if ah.settings.keep_log:
                ah.log.debug(json.dumps(msg))
            self.missing[habit] = False
            self.habit_grabbed[habit] = True
        except:
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            if ah.settings.debug:
                raise
            return False

    def reset_scorecounter(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        if ah.settings.keep_log:
            ah.log.debug("Resetting Scorecounter")
        last_review_time = db_helper.latest_review_time()
        if ah.settings.keep_log:
            ah.log.debug(str(last_review_time))
        self.hnote[habit] = {'scoresincedate': last_review_time,
                             'scorecount': 0, 'sched': ah.settings.sched_dict[habit]}
        self.habit_grabbed[habit] = True
        if ah.settings.keep_log:
            ah.log.debug("reset: %s" % json.dumps(self.hnote[habit]))
        try:
            self.post_scorecounter(habit)
            if ah.settings.keep_log:
                ah.log.debug("End function returning: %s" % True)
            return True
        except:
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            if ah.settings.debug:
                raise
            return False

    def grab_scorecounter(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        if self.habit_grabbed[habit]:
            if ah.settings.keep_log:
                ah.log.debug("End function returning: %s" % True)
            return True
        try:
            habitID = str(self.habit_id[habit])
            if ah.settings.keep_log:
                ah.log.debug("grabbing scorecounter: %s" % habitID)
            response = self.api.task(habitID)
            if not habitID:
                if ah.settings.keep_log:
                    ah.log.error("End function returning: %s" % False)
                return False
            if ah.settings.keep_log:
                ah.log.debug(response['notes'])
        except:
            # Check if habit exists
            if habit not in self.missing:
                if ah.settings.keep_log:
                    ah.log.debug("Habit not missing")
            # Reset scorecount if habit is missing
            if self.missing[habit]:
                if ah.settings.keep_log:
                    ah.log.debug("Habit was missing")
                self.reset_scorecounter(habit)
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            if ah.settings.debug:
                raise
            return False
        # Try to grab the scorecount and score since date
        if ah.settings.keep_log:
            ah.log.debug("trying to load note string: %s" % response['notes'])
        try:
            self.hnote[habit] = json.loads(response['notes'])
        except:
            if ah.settings.keep_log:
                ah.log.warning("Reset 1")
            self.reset_scorecounter(habit)
            if ah.settings.keep_log:
                ah.log.warning("End function returning: %s" % True)
            return True
        if 'scoresincedate' not in self.hnote[habit] or 'scorecount' not in self.hnote[habit]:
            # reset habit score counter if both keys not found
            if ah.settings.keep_log:
                ah.log.debug("scorecounter missing keys")
            self.reset_scorecounter(habit)
            if ah.settings.keep_log:
                ah.log.warning("End function returning: %s" % False)
            return False
        # reset if sched is different from last sched or is missing
        # this should prevent problems caused by changing the reward schedule
        if 'sched' not in self.hnote[habit] or (int(self.hnote[habit]['sched']) != int(ah.settings.sched_dict[habit])):
            self.reset_scorecounter(habit)
            if ah.settings.keep_log:
                ah.log.warning("End function returning: %s" % False)
            return False
        if ah.settings.keep_log:
            ah.log.debug("Habit Grabbed")
        if ah.settings.keep_log:
            ah.log.debug("Habit note: %s" % self.hnote[habit])
        self.habit_grabbed[habit] = True
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % True)
        return True

    def post_scorecounter(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        try:
            habitID = self.habit_id[habit]
            if ah.settings.keep_log:
                ah.log.debug("posting scorecounter: %s" % self.hnote[habit])
            datastring = json.dumps(self.hnote[habit])
            data = {"notes": datastring}
            self.api.update_task(habitID, data)
            if ah.settings.keep_log:
                ah.log.debug("End function returning: %s" % True)
            return True
        except:
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            return False

    def test_internet(self):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        out = self.api.test_internet()
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % out)
        return out

    def make_score_message(self, new_lvl, new_xp, new_mp, new_gp, new_hp, streak_bonus=0, crit_multiplier=0, drop_dialog=None):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        hrpgresponse = "Huzzah! You've Earned Points!\nWell Done %s!\n" % (
            self.name)
        # Check for increases and add to message
        if new_lvl > self.lvl:
            diff = int(new_lvl) - int(self.lvl)
            hrpgresponse += "\nYOU LEVELED UP! NEW LEVEL: %s" % (new_lvl)
            self.save_avatar()  # save the new avatar!
        hrpgresponse += "\nHP: %s" % (int(self.hp))
        if new_hp > self.hp:
            diff = int(new_hp) - int(self.hp)
            hrpgresponse += "  +%s!" % (diff)
        hrpgresponse += "\nXP: %s" % (int(self.xp))
        if new_xp > self.xp:
            diff = int(new_xp) - int(self.xp)
            hrpgresponse += "  +%s!" % (diff)
        hrpgresponse += "\nGP: %s" % (round(self.gp, 2))
        if new_gp > self.gp:
            diff = int(new_gp) - int(self.gp)
            hrpgresponse += "  +%s!" % (diff)
        hrpgresponse += "\nMP: %s" % (int(self.mp))
        if new_mp > self.mp:
            diff = int(new_mp) - int(self.mp)
            hrpgresponse += "  +%s!" % (diff)
        # Check for drops, streaks, and critical hits
        if crit_multiplier:
            hrpgresponse += "\nCritical Hit! Bonus: +%s%%" % crit_multiplier
        if streak_bonus:
            hrpgresponse += "\nStreak Bonus! +%s" % (int(streak_bonus))
        if drop_dialog:
            hrpgresponse += "\n\n%s" % str(drop_dialog)
        # Show message box
        if ah.settings.show_popup:
            self.hrpg_showInfo(hrpgresponse)
        else:
            tooltip(_("Huzzah! You Scored Points!"), period=2500)

        # update levels
        if new_lvl > self.lvl and self.lvl > 0:
            self.update_stats(False)
        else:
            self.lvl = new_lvl
            self.xp = new_xp
            self.mp = new_mp
            self.gp = new_gp
            self.hp = new_hp
        runHook("HabiticaAfterScore")
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % True)
        return True

    def earn_points(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        # get user stats if we don't have them
        if 'lvl' not in self.stats:
            if ah.settings.keep_log:
                ah.log.warning("lvl not in stats")
            self.update_stats(False)
        # check habit if is is unchecked
        if not self.habit_grabbed[habit]:
            if ah.settings.keep_log:
                ah.log.debug("%s habit not checked" % habit)
            try:
                if ah.settings.keep_log:
                    ah.log.debug("Checking Habit Score Counter")
                self.check_anki_habit(habit)
            except:
                pass
        crit_multiplier = None
        streak_bonus = None
        drop_dialog = None
        # Loop through scoring attempts up to 3 times
        # -- to account for missed scoring opportunities (smartphones, etc.)
        i = 0  # loop counter
        success = False
        while i < 3 and ah.config[ah.settings.profile]['score'] >= ah.settings.sched and ah.settings.internet:
            try:
                msg = self.score_anki_points(habit)
                if msg['lvl']:  # Make sure we really got a response
                    success = True
                    self.hnote[habit]['scorecount'] += 1
                    ah.config[ah.settings.profile]['score'] -= ah.settings.sched
                # Collect message strings
                if msg['_tmp']:
                    if 'streakBonus' in msg['_tmp']:
                        # streak bonuses
                        if not streak_bonus:
                            streak_bonus = ""
                        else:
                            streak_bonus += "\n"
                        streak_bonus += str(round((100 * msg['_tmp']['streakBonus']), 0))
                    if 'crit' in msg['_tmp']:
                        # critical multiplier
                        if not crit_multiplier:
                            crit_multiplier = ""
                        else:
                            crit_multiplier += ", "
                        crit_multiplier += str(round((100 * msg['_tmp']['crit']), 0))
                    if 'drop' in msg['_tmp'] and 'dialog' in msg['_tmp']['drop']:
                        # drop happened
                        if not drop_dialog:
                            drop_dialog = ""
                        else:
                            drop_dialog += "\n"
                        drop_dialog += str(msg['_tmp']['drop']['dialog'])
            except:
                if ah.settings.debug:
                    raise
            i += 1

        if not success:  # exit if we failed all 3 times
            self.hrpg_showInfo(
                "Huzzah! You've earned points!\nWell done %s!\n\nSorry,\nI couldn't score your %s habit on Habitica.\nDon't worry, I'll remember your points and try again later." % (self.name, habit))
            ah.settings.internet = False  # internet failed
            if ah.settings.keep_log:
                ah.log.warning('Internet failed')
            if ah.settings.keep_log:
                ah.log.warning("End function returning: %s" % False)
            return False
        # Post scorecounter to Habit note field
        if Habitica.allow_post_scorecounter_thread:
            _thread.start_new_thread(self.post_scorecounter, (habit,))
        else:
            self.post_scorecounter(habit)

        # Gather new levels from last successful msg
        new_lvl = msg['lvl']
        new_xp = msg['exp']
        new_mp = msg['mp']
        new_gp = msg['gp']
        new_hp = msg['hp']

        out = self.make_score_message(
            new_lvl, new_xp, new_mp, new_gp, new_hp, streak_bonus, crit_multiplier, drop_dialog)
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % out)
        return out

    # Compact Habitica Stats for Progress Bar
    def compact_habitica_stats(self):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        if self.ht and self.xt and self.mt:
            health = int(100 * self.hp / self.ht)
            experience = int(100 * self.xp / self.xt)
            mana = int(100 * self.mp / self.mt)
            string = "<font color='firebrick'>%s</font> | <font color='darkorange'>%s</font> | <font color='darkblue'>%s</font>" % (
                health, experience, mana)
        else:
            string = False
        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % string)
        return string

    # Silent Version of Earn Points
    def silent_earn_points(self, habit):
        if ah.settings.keep_log:
            ah.log.debug("Begin function")
        # check habit if is is unchecked
        if not self.habit_grabbed[habit]:
            try:
                self.check_anki_habit(habit)
                self.grab_scorecounter(habit)
            except:
                pass
        try:
            self.score_anki_points(habit)
            self.hnote[habit]['scorecount'] += 1
        except:
            if ah.settings.keep_log:
                ah.log.error("End function returning: %s" % False)
            if ah.settings.debug:
                raise
            return False

        if ah.settings.keep_log:
            ah.log.debug("End function returning: %s" % True)
        return True

@johnfred4
Copy link
Author

Me too man, me too.

Tried copying and pasting that entire script and still an error message:

image

@johnfred4
Copy link
Author

Also, after copying that script, AnkiHabitica won't even show up in my "Tools" list, so I can't even manually tell it to score my backlog. The box at the bottom that tracks my progress until the next points are awarded also disappears.

image

@MedAnki
Copy link

MedAnki commented Jun 11, 2019

try updating it to 2.1?

@MedAnki
Copy link

MedAnki commented Jun 11, 2019

Delete the Habitica add on, start from fresh.
Update to Anki latest
follow #71
paste the code I gave you

Other than this even my hands are tide man

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
reference Solved issue sticking around for others with similar issues
Projects
None yet
Development

No branches or pull requests

3 participants