FooSoft / anki-connect

Anki plugin to expose a remote API for creating flash cards.
https://foosoft.net/projects/anki-connect/
Other
1.94k stars 219 forks source link

addNote results in error: Exception 'modelName' #345

Open TanukiTom opened 2 years ago

TanukiTom commented 2 years ago

I cannot add notes through the addNote action in Python 3.10 and Anki 2.1.54.

My code:

import json
import urllib.request

# Basic AnkiConnect Functions
def request(action, **params):
    return {'action': action, 'params': params, 'version': 6}

def invoke(action, **params):
    requestJson = json.dumps(request(action, **params)).encode('utf-8')
    response = json.load(urllib.request.urlopen(urllib.request.Request('http://localhost:8765', requestJson)))
    if len(response) != 2:
        raise Exception('response has an unexpected number of fields')
    if 'error' not in response:
        raise Exception('response is missing required error field')
    if 'result' not in response:
        raise Exception('response is missing required result field')
    if response['error'] is not None:
        raise Exception(response['error']) # *Line 18*
    return response['result']

# Successfully makes deck
invoke('createDeck', deck='Test Deck')

my_note = {
    "action": "addNote",
    "version": 6,
    "params": {
        "note": {
            "deckName": "Test Deck",
            "modelName": "Basic",
            "fields": {
                "Front": "front content",
                "Back": "back content",
            },
            "options": {
                "allowDuplicate": False
            },
            "tags": ['tester']
        }
    }
}

invoke('addNote', note=my_note) # *Line 43*

Results in this error:

Traceback (most recent call list):
File "/home/me/py/test.py", line 43, in <module>
    invoke('addNote', note=my_note)
File "/home/me/py/test.py", line 18 in invoke
    raise Exception(response['error'])
Exception: 'modelName'

The "Basic" model in my Anki database. AnkiContect also returns that model name with invoke('modelNames').

snoyes commented 2 years ago

Not a bug. You've included too much in my_note. It should be:

my_note = {
            "deckName": "Test Deck",
            "modelName": "Basic",
            "fields": {
                "Front": "front content",
                "Back": "back content",
            },
            "options": {
                "allowDuplicate": False
            },
            "tags": ['tester']
        }