Code Monkey home page Code Monkey logo

characterai's Introduction

logo

Downloads License Stars Discord

Welcome to the documentation for a synchronous/asynchronous unofficial library for CharacterAI using curl_cff

๐Ÿ’ป Installation

pip install git+https://github.com/kramcat/CharacterAI.git

โš ๏ธ Warning

This version of the library is in alpha version, there may be bugs and errors. The library was developed without the participation of Character AI developers or their knowledge. To work with the library you need to know how to work with asyncio

๐Ÿ”ฅ Features

  • Supports logging in via email or as a guest
  • Does not use web browsers like: Pypeeter, Playwright, etc.
  • Supports uploading/downloading pictures
  • Has detailed documentation
  • Uses Pydantic
  • Asynchronous

๐Ÿ“™ Simple Example

You need an account to use the library. To find out your token, you must log in through the library

from characterai import aiocai
import asyncio

async def main():
    char = input('CHAR ID: ')

    client = aiocai.Client('TOKEN')

    me = await client.get_me()

    async with await client.connect() as chat:
        new, answer = await chat.new_chat(
            char, me.id
        )

        print(f'{answer.name}: {answer.text}')
        
        while True:
            text = input('YOU: ')

            message = await chat.send_message(
                char, new.chat_id, text
            )

            print(f'{message.name}: {message.text}')

asyncio.run(main())

๐Ÿ“š Documentation

The documentation contains all the detailed information about functions and types. If you have any questions, first of all read whether there is an answer in the documentation

docs.kram.cat

๐Ÿ‘ฅ Community

If you have any questions about our library or would like to discuss CharacterAI, LLM, or Neural Networks topics, please visit our Discord channel

discord.gg/ZHJe3tXQkf

๐Ÿ“ TODO List

  • Character voice work
  • Community tab support
  • Add logging
  • Group chat support
  • Improved work with uploading pictures

๐Ÿ’ต Support

TON - EQCSMftGsV4iU2b9H7tuEURIwpcWpF_maw4yknMkVxDPKs6v
BTC - bc1qghtyl43jd6xr66wwtrxkpe04sglqlwgcp04yl9
ETH - 0x1489B0DDCE07C029040331e4c66F5aA94D7B4d4e
USDT (TRC20) - TJpvALv9YiL2khFBb7xfWrUDpvL5nYFs8u

You can contact me via Telegram or Discord if you need help with parsing services or want to write a library. I can also create bots and userbots for Telegram

characterai's People

Contributors

kramcat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

characterai's Issues

500 Internal Server Error

Bot gives an "500 Internal Server Error" after several success attempts to reply. Earlier versions of the library did not have this error. Can i fix this?

Unable to delete messages

For some reason the messages in the chat aren't deleting when I use client.chat.delete_message(history_id, uuids_to_delete).
Here is my following code:

from characterai import PyCAI

client = PyCAI('CLIENT')
character_key = 'CHAR'
history_id = 'HISTORY ID'

history = client.chat.get_history(character_key)

uuids_to_delete = []
for message in history['messages']:
    uuids_to_delete.append(message['uuid'])

print(uuids_to_delete)

for uuid in uuids_to_delete:
    client.chat.delete_message(history_id, uuids_to_delete)

The goal of this code is to automatically reset the chat. When I check the website, the messages are still there. Did I do something wrong?

I am so confused by everything

What do all of these keys mean?
image
only few of them are actually specified, and the documentation doesn't do anything to help.

unable to use versions 0.2.6 and 0.2.7

if i try to install those versions i get this.

ร— python setup.py egg_info did not run successfully.
โ”‚ exit code: 1
โ•ฐโ”€> [8 lines of output]
Traceback (most recent call last):
File "", line 2, in
File "", line 34, in
File "C:\Users\Hex\AppData\Local\Temp\pip-install-9j_3ogkx\characterai_03569ba5445d41f7926cb60078390a46\setup.py", line 4, in
long_description = readme.read()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 155: character maps to
[end of output]

An error occurs when installing dependencies

$ pip install characterai==0.6.0

ERROR: Could not find a version that satisfies the requirement playwright>=1.32.1 (from characterai) (from versions: none)
ERROR: No matching distribution found for playwright>=1.32.1

There is smth wrong with execution

Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\pythonProject5\Chatty.py", line 10, in
client.start(headless=True)
File "C:\Users\User\PycharmProjects\pythonProject5\venv\Lib\site-packages\characterai\characterai.py", line 103, in start
self.browser = self.playwright.firefox.launch(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\pythonProject5\venv\Lib\site-packages\playwright\sync_api_generated.py", line 14778, in launch
self._sync(
File "C:\Users\User\PycharmProjects\pythonProject5\venv\Lib\site-packages\playwright_impl_sync_base.py", line 109, in _sync
return task.result()
^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\pythonProject5\venv\Lib\site-packages\playwright_impl_browser_type.py", line 96, in launch
Browser, from_channel(await self._channel.send("launch", params))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\pythonProject5\venv\Lib\site-packages\playwright_impl_connection.py", line 61, in send
return await self._connection.wrap_api_call(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\PycharmProjects\pythonProject5\venv\Lib\site-packages\playwright_impl_connection.py", line 482, in wrap_api_call
return await cb()
^^^^^^^^^^
File "C:\Users\User\PycharmProjects\pythonProject5\venv\Lib\site-packages\playwright_impl_connection.py", line 97, in inner_send
result = next(iter(done)).result()
^^^^^^^^^^^^^^^^^^^^^^^^^
playwright._impl._api_types.Error: Executable doesn't exist at C:\Users\User\AppData\Local\ms-playwright\firefox-1424\firefox\firefox.exe
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘ Looks like Playwright was just installed or updated. โ•‘
โ•‘ Please run the following command to download new browsers: โ•‘
โ•‘ โ•‘
โ•‘ playwright install โ•‘
โ•‘ โ•‘
โ•‘ <3 Playwright Team โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Despite me making in headless=False , it still requires browser . How can i make this work only in terminal. Any help is appriceated, thanks in advance.

I can't find key value

I can't find key value after searching"/dj-rest-auth/auth0/".
Is "access_token"the"key value"๏ผŸ

Very amazing idea but couldn't get it to work at all

Its beautiful but I couldn't get it to work at all. I think you need to include a example script that actually works instead of just posting pieces of code on the gitbook. I give up. I am just going to build my own quick and dirty scraper with selenium and I'll check back later.

TypeError: string indices must be integers Pls Help!

Hey, I keep getting this error every time I try to get a response from character. Pls help
Traceback (most recent call last): File "d:\Work\LiveWhisper-main\char.py", line 12, in <module> print(f"{data['src_char']['participant']['name']}: {data['replies'][0]['text']}") TypeError: string indices must be integers

module object is not callable???

Traceback (most recent call last):
  File "c:\Users\_____\OneDrive\Documents\discordbots\aigeneratedtogrps\caitest.py", line 38, in <module>
    asyncio.run(main())
  File "C:\Users\_____\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\_____\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\_____\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "c:\Users\_____\OneDrive\Documents\discordbots\aigeneratedtogrps\caitest.py", line 7, in main
    caiclient = pyasynccai("7b9773bac6c2a3139dd41e393fce72f76d9e9342")
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'module' object is not callable

image
i copied the exact code from the gitbook (other than renaming the client and making it a global variable but it shouldn't be the issue, right?)

Stuck waiting for Character response

Hi,
I started using this library cause I had problems when developing my own library.
I am using the synchronous standard example provided in github.
It sometimes works, but mostly does not.
When using the headless = false option it is always stuck at the point shown in the picture.
image

Any ideas what is happenig?
There is no error messagen, its just waiting for the response:
image

Getting chat fails if account has chats with multiple characters

https://beta.character.ai/chat2?char=gIor6bOT0GtU7tTNvAvc1NxAW5O7AyqdBx-cApcH9wk

if account has multiple characters chats(?) i think
the link will have chat2 instead of chat. And this will not allow API to get character`s history.

        async def get_chat(
            self, char: str = None, *,
            wait: bool = False, token: str = None,
            **kwargs
        ):
            return await _PostResponse(
                post_link='chat/history/continue/',
                data={
                    'character_external_id': char,
                    **kwargs
                },
                wait=wait, token=token
            )

There's a problem with token and the character

Traceback (most recent call last):
  File "C:\Users\hp\Documents\Projects\python\chatbot\c.ai.py", line 20, in <module>
    data = client.chat.send_message('YntB_ZeqRq2l_aVf2gWDCZl4oBttQzDvhj9cXafWcF8', message, wait=True)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\characterai\characterai.py", line 383, in send_message
    info = PostResponse(
  File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\characterai\characterai.py", line 82, in PostResponse
    raise errors.ServerError(response.status_text)
characterai.errors.ServerError: Unauthorized

Why am I getting this and I couldn't find the token from the network tab so I used local storage and copied the access token in the key that starts with @@auth0spajs

Are some characters are blocked or something else because I can write in character.ai easily with no problem

@kramcat @kramcat @kramcat

What does "KeyError: 'src_char'" mean?

So, I wanted to see if this would be a means to bypass the filter on character.ai,
But, when I did do that, occasionally, I would get name = data['src_char']['participant']['name'] KeyError: 'src_char'

What does this mean?

Didnt work


client = PyCAI("XXXXXXXXXXXXXXXXXXXXXXX")
client.start()

char = 'XXXXXXXXXXXXXXXXXXXXX'

chat = client.chat.get_chat(char)

participants = chat['participants']

if not participants[0]['is_human']:
    tgt = participants[0]['user']['username']
else:
    tgt = participants[1]['user']['username']

while True:
    message = input('You:')

    data = client.chat.send_message(
        chat['external_id'], tgt, message
    )

    name = data['src_char']['participant']['name']
    text = data['replies'][0]['text']

    print(f"{name}: {text}")```


```Traceback (most recent call last):
  File "<module1>", line 37, in <module>
  File "C:\Users\luvut\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\luvut\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "<module1>", line 13, in main
  File "C:\Users\luvut\AppData\Local\Programs\Python\Python310\lib\site-packages\characterai\pyasynccai.py", line 567, in get_chat
    return await _PostResponse(
  File "C:\Users\luvut\AppData\Local\Programs\Python\Python310\lib\site-packages\characterai\pyasynccai.py", line 79, in _PostResponse
    raise errors.ServerError(response.status_text)
characterai.errors.ServerError: Not Found```

It looks like you are using Playwright Sync API inside the asyncio loop

i sometimes get error "It looks like you are using Playwright Sync API inside the asyncio loop." on client = PyCAI(auth_token). i do not use async so i guess it is related to how this package works.

i noticed it happens only when CharacterAI(website) is overloaded(e.g. when waiting queue appears) but more frequently i get TimeoutError(which is logical). setting "wait" to true does not help either

ImportError

I am getting this error:
ImportError: cannot import name 'pyCAI' from partially initialized module 'characterai' (most likely due to a circular import)

All i did is just copy the example code and give it a test and this error showed up.

characterai.errors.ServerError: Unauthorized

Code:

from characterai import PyCAI

client = PyCAI('TOKEN')

while True:
message = input('You: ')

data = client.chat.send_message('CHAR', message)

if data['replies']:
    reply = data['replies'][0]['text']
    name = data['src_char']['participant']['name']
    print(f"{name}: {reply}")
else:
    print("Error: No reply from the character.")

# Check if the conversation is finished
if 'conversation_finished' in data and data['conversation_finished']:
    print("Conversation ended.")
    break

You: hello fellow hows your day
Traceback (most recent call last):
File "C:\Users\Administrator\Downloads\Consoles\XboxOne\A.py", line 8, in
data = client.chat.send_message('92i0UeYAM6hKG1ojgoprsR4MwStyZfrHS8qDufRWo3A', message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\characterai\characterai.py", line 383, in send_message
info = PostResponse(
^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\characterai\characterai.py", line 82, in PostResponse
raise errors.ServerError(response.status_text)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
characterai.errors.ServerError: Unauthorized

Error when attempting to get response from character

File "C:\Users\alfred\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 861, in callit
    func(*args)
  File "C:\dat\Python\testing\c.ai-py.py", line 20, in chat
    data = client.chat.send_message(cid, message)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\alfred\AppData\Local\Programs\Python\Python311\Lib\site-packages\characterai\characterai.py", line 144, in send_message
    return json.loads('{"replies": ' + response.split(r'{"replies": ')[-1])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\alfred\AppData\Local\Programs\Python\Python311\Lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\alfred\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\alfred\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 13 (char 12)

code:

from characterai import pyCAI
import sys
import time

def log(string, instant_text="", new_line=True, pause_at_periods=True, pause_at_commas=True, sleep=0.025):
    string = str(string)
    sys.stdout.write(instant_text)
    for i, c in enumerate(string):
        sys.stdout.write(c)
        sys.stdout.flush()
        if i + 1 < len(string):
            if c not in [".", "!", "?"] and pause_at_periods == True and (string[i + 1] != " " or i + 2 < len(string)):
                time.sleep(sleep*5)
            elif c == "," and pause_at_commas == True:
                time.sleep(sleep*2.25)
            else:
                time.sleep(sleep)
        elif c == "," and pause_at_commas == True:
            time.sleep(sleep*2.25)
        else:
            time.sleep(sleep)
    if new_line == True: sys.stdout.write("\n")

token = '[token removed]'
character = '[id removed]'

client = pyCAI(token)

while True:
    message = input('> ')
    data = client.chat.send_message(character, message)
    log(data["replies"][0]["text"], f"{data['src_char']['participant']['name']}: ")

strangely, this error doesn't occur when the message has to wait for Cloudflare or when its the first message sent to the library.

EDIT: I set the library to print the output so that I could attempt to find out what was wrong. When the error was thrown, this was the output, which is definitely not JSON:

<html>
  <head>
    <title>Internal Server Error</title>
  </head>
  <body>
    <h1><p>Internal Server Error</p></h1>
    
  <script defer src="https://static.cloudflareinsights.com/beacon.min.js/v52afc6f149f6479b8c77fa569edb01181681764108816" integrity="sha512-jGCTpDpBAYDGNYR5ztKt4BQPGef1P0giN6ZGVUi835kFF88FOmmn8jBQWNgrNd8g/Yu421NdgWhwQoaOPFflDw==" data-cf-beacon='{"rayId":"7ca3fd09cb924126","token":"de6c8a8324c04a50b30bdeb96bc8d410","version":"2023.4.0","si":100}' crossorigin="anonymous"></script>
</body>
</html>

From the above output, I assume that something is wrong with either the way the library fetches data or just server errors on c.ai's side, although I can use the site normally so I'm leaning towards the former.

I stuck at get chat

My issue is at this line

`import asyncio
from characterai import PyAsyncCAI

async def main():
Token='**********************'
client = PyAsyncCAI(Token)
await client.start()

char = 'y9ChWSyBEiCcpo1npsilkLZ_UR3qrhaobMWUbuxs-e8'

# Save tgt and history_external_id 
# to avoid making a lot of requests
chat = await client.chat.get_chat(char)

`

Traceback (most recent call last):
File "cai.py", line 37, in
asyncio.run(main())
File "d:\ProgramData\Anaconda3\lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "d:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "cai.py", line 13, in main
chat = await client.chat.get_chat(char)

File "d:\ProgramData\Anaconda3\lib\site-packages\characterai\pyasynccai.py", line 364, in get_chat
return await PostResponse(
File "d:\ProgramData\Anaconda3\lib\site-packages\characterai\pyasynccai.py", line 66, in PostResponse
await page.evaluate(
File "d:\ProgramData\Anaconda3\lib\site-packages\playwright\async_api_generated.py", line 8653, in evaluate
await self._impl_obj.evaluate(
File "d:\ProgramData\Anaconda3\lib\site-packages\playwright_impl_page.py", line 395, in evaluate
return await self._main_frame.evaluate(expression, arg)
File "d:\ProgramData\Anaconda3\lib\site-packages\playwright_impl_frame.py", line 277, in evaluate
await self._channel.send(
File "d:\ProgramData\Anaconda3\lib\site-packages\playwright_impl_connection.py", line 61, in send
return await self._connection.wrap_api_call(
File "d:\ProgramData\Anaconda3\lib\site-packages\playwright_impl_connection.py", line 482, in wrap_api_call
return await cb()
File "d:\ProgramData\Anaconda3\lib\site-packages\playwright_impl_connection.py", line 97, in inner_send
result = next(iter(done)).result()
playwright._impl._api_types.Error: NetworkError when attempting to fetch resource.
Exception ignored in: <function BaseSubprocessTransport.del at 0x000002096D7FA280>
Traceback (most recent call last):
File "d:\ProgramData\Anaconda3\lib\asyncio\base_subprocess.py", line 126, in del
File "d:\ProgramData\Anaconda3\lib\asyncio\base_subprocess.py", line 104, in close
File "d:\ProgramData\Anaconda3\lib\asyncio\proactor_events.py", line 108, in close
File "d:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 719, in call_soon
File "d:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 508, in _check_closed
RuntimeError: Event loop is closed

the character AI isn't responding to me back

aaaa
when i input , the code just run without giving error but it is also not responding to my input , like i waited 30 min after inputting and it doesn't do anything ;-;. hope you can help!

Markdown styling is ignored

This library ignores if text is italicized or in bold on c.ai's site. I've also noticed that interaction with new lines is finnicky.
To put this issue into perspective, if the character says "Haha!

I get up." on the site, it shows up like this when printed: "Haha!
โ€‹
โ€‹
โ€‹
โ€‹
I get up."

click response error

retrying click action, attempt #56
waiting 500ms
waiting for element to be visible, enabled and stable
element is visible, enabled and stable
scrolling into view if needed
done scrolling

โ€ฆ
from
โ€ฆ
subtree intercepts pointer events retrying click action, attempt #57 waiting 500ms

Exception has occurred: JSONDecodeError

image

from characterai import PyCAI

client = PyCAI('-')
chat = client.chat.get_chat('gs_RN6o6wkLTOYRB18UDC1bDb3YFfzvPhsaDHfIFfCs')
Exception has occurred: JSONDecodeError
Expecting value: line 1 column 1 (char 0)
StopIteration: 0

During handling of the above exception, another exception occurred:

  File "C:\Users\Aurus\CharAI\main.py", line 4, in <module>
    chat = client.chat.get_chat('gs_RN6o6wkLTOYRB18UdC1bDb3YFfzvPhsaDHfIFfCs')
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

characterai.errors.ServerError: Not Found

from characterai import PyCAI

client = PyCAI("MyToken", headless=False)

char = "2T3Xhqf5B_b9Wrn8Bg0FeCYR7BPx2LtJQJJCIB4Qe18" # hyperglot

chat = client.chat.get_chat(char)

When opening the browser, I see the tab name "Chat now with HyperGlot" but the window closes with these error message

characterai.errors.ServerError: Not Found

Traceback (most recent call last):
File "c:\Users\gsapp\Documents\prog\python\Hope\CAi_test.py", line 7, in
chat = client.chat.get_chat(char)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\gsapp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\characterai\characterai.py", line 362, in get_chat
return PostResponse(
^^^^^^^^^^^^^
File "C:\Users\gsapp\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\characterai\characterai.py", line 82, in PostResponse
raise errors.ServerError(response.status_text)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Can you help me ?

Thanks in advance.

Add to documentation how to get the tgt value

The documentation has no where specific mentioning the retrival of the tgt value. Add this code under the https://pycai.gitbook.io/welcome/api/values "tgt" section which retrives the tgt value:

PyCai("token").chat.get_chat("char")["participants"][0]["user"]["username"] if not PyCai("token").chat.get_chat("char")[
    "participants"][0]["is_human"] else PyCai("token").chat.get_chat("char")["participants"][1]["user"]["username"]

`goto` and `GetResponse` methods don't work in Python 3.11

The underscore in the method names inside the pyCAI class prevents it from working or something, but removing the underscore seems to make it work fine.

There is also the fact that when c.ai is overloaded, it simply gives you an error instead of waiting until it gains access to the site.

No eligible candidates in send_message()

While executing: cli.chat.send_message(chat['external_id'], tgt, msg) (as in example)

Full exception text:

Traceback (most recent call last):
  File "/usr/lib/python3.11/runpy.py", line 198, in _run_module_as_main
    return _run_code(code, main_globals, None,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/runpy.py", line 88, in _run_code
    exec(code, run_globals)
  File "/home/risenanderson/.vscode/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/__main__.py", line 39, in <module>
    cli.main()
  File "/home/risenanderson/.vscode/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 430, in main
    run()
  File "/home/risenanderson/.vscode/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 284, in run_file
    runpy.run_path(target, run_name="__main__")
  File "/home/risenanderson/.vscode/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 321, in run_path
    return _run_module_code(code, init_globals, run_name,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/risenanderson/.vscode/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 135, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "/home/risenanderson/.vscode/extensions/ms-python.python-2023.14.0/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 124, in _run_code
    exec(code, run_globals)
  File "/home/risenanderson/projects/dsbots/Scarabot/main.py", line 22, in <module>
    data = cli.chat.send_message(chat['external_id'], tgt, msg)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/risenanderson/.local/lib/python3.11/site-packages/characterai/characterai.py", line 593, in send_message
    raise errors.FilterError('No eligible candidates')
characterai.errors.FilterError: No eligible candidates

Error occurs if there is a wait time on the site?

I haven't been able to get my code to work yet fully, if I run it it opens up the correct chat in the browser, but before the page loads the code shows errors. I think this may be caused by the fact that usually there is a wait time for the Character AI site and that might be throwing it off? It could be something else though. Here are the error messages it displays:

/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/unix_events.py:878: RuntimeWarning: A loop is being detached from a child watcher with pending handlers
RuntimeWarning)
Traceback (most recent call last):
File "/Users/hexgeissinger/Desktop/caitest.py", line 39, in
asyncio.run(main())
File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 587, in run_until_complete
return future.result()
File "/Users/hexgeissinger/Desktop/caitest.py", line 15, in main
chat = await client.chat.get_chat(char)
File "/Users/hexgeissinger/Library/Python/3.7/lib/python/site-packages/characterai/pyasynccai.py", line 369, in get_chat
token=token
File "/Users/hexgeissinger/Library/Python/3.7/lib/python/site-packages/characterai/pyasynccai.py", line 57, in PostResponse
await goto(link, wait=wait, token=token)
File "/Users/hexgeissinger/Library/Python/3.7/lib/python/site-packages/characterai/pyasynccai.py", line 38, in goto
raise errors.NoResponse('The Site is Overloaded')
AttributeError: module 'characterai.errors' has no attribute 'NoResponse'

UPDATE: I just ran it when there wasn't a wait time on the website and it worked fine. what should I do so that the code will know to wait until the page loads properly?

NameError: name 'page' is not defined

File MYDIRECTORY/venv\lib\site-packages\characterai\pyasynccai.py", line 16, in goto
await page.goto(f'https://beta.character.ai/{link}')
NameError: name 'page' is not defined

This is the error when I try sending a message to the api with my code below: (not all of the code is shown below because of the other project i'm working on, a discord bot)

from characterai import PyAsyncCAI

caiToken = "CENSORED"

cclient = PyAsyncCAI(caiToken)
print(f"{char}: {msg}")
data = await cclient.chat.send_message(char, msg)

cannot use client.chat.get_chat(char)

I'm following the chatting code example on documentation. I'm having the following error when I use client.chat.get_chat(char):

Obs.: I'm using venv

Traceback (most recent call last):
chat = client.chat.get_chat(roxy_char)
File "D:\files\cai api\venv\lib\site-packages\characterai\characterai.py", line 567, in get_chat
return _PostResponse(
File "D:\files\cai api\venv\lib\site-packages\characterai\characterai.py", line 58, in _PostResponse
_goto('', wait=wait, token=token)
File "D:\files\cai api\venv\lib\site-packages\characterai\characterai.py", line 22, in _goto
raise errors.UnknownError(E)
characterai.errors.UnknownError: 'NoneType' object has no attribute 'goto'

What might be causing this error?

Traceback (most recent call last):
File "C:\Users\meets\PycharmProjects\AI-Vtuber\eleven labs.py", line 8, in
client = pyCAI(token)
File "C:\Users\meets\PycharmProjects\AI-Vtuber\venv\lib\site-packages\characterai\characterai.py", line 55, in init
self.browser = sync_playwright().start().firefox.launch(headless=headless)
File "C:\Users\meets\PycharmProjects\AI-Vtuber\venv\lib\site-packages\playwright\sync_api_generated.py", line 14723, in launch
self._sync(
File "C:\Users\meets\PycharmProjects\AI-Vtuber\venv\lib\site-packages\playwright_impl_sync_base.py", line 109, in _sync
return task.result()
File "C:\Users\meets\PycharmProjects\AI-Vtuber\venv\lib\site-packages\playwright_impl_browser_type.py", line 95, in launch
Browser, from_channel(await self._channel.send("launch", params))
File "C:\Users\meets\PycharmProjects\AI-Vtuber\venv\lib\site-packages\playwright_impl_connection.py", line 61, in send
return await self._connection.wrap_api_call(
File "C:\Users\meets\PycharmProjects\AI-Vtuber\venv\lib\site-packages\playwright_impl_connection.py", line 482, in wrap_api_call
return await cb()
File "C:\Users\meets\PycharmProjects\AI-Vtuber\venv\lib\site-packages\playwright_impl_connection.py", line 97, in inner_send
result = next(iter(done)).result()
playwright._impl._api_types.Error: Executable doesn't exist at C:\Users\meets\AppData\Local\ms-playwright\firefox-1408\firefox\firefox.exe
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘ Looks like Playwright was just installed or updated. โ•‘
โ•‘ Please run the following command to download new browsers: โ•‘
โ•‘ โ•‘
โ•‘ playwright install โ•‘
โ•‘ โ•‘
โ•‘ <3 Playwright Team โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

chat2.new_chat returns "characterai.errors.ServerError: create_chat already exists"

Here I'm trying to reset the chat by using new_chat (I hope I'm doing it right...)

chat = (await cai_client.chat2.get_chat(CHAR))["chats"][0]
user = (await cai_client.user.info())["user"]["user"]
async with cai_client.connect() as chat2:
    await chat2.new_chat(
        char=env("CHAR"),
        chat_id=chat["chat_id"],
        creator_id=str(user["id"]),
)

And here's what I receive

File "~~~\Lib\site-packages\characterai\pyasynccai.py", line 718, in new_chat
    raise errors.ServerError(response['comment'])
characterai.errors.ServerError: create_chat already exists

Is this code still working? I only get timeouts...

I'm able to retrieve my account information via client.user.info() so the token is correct! (this is good :)
But then any send_message call ends up in a timeout.
I'm a "+" user so there should be no access issues. Works fine in a browser at the same time.
xxx = obvious obfuscation.
I can't get telegram to work..

Here is my code:

from characterai import pyCAI
client = pyCAI('9xxxxxxxxxxxxxxxxx4')
print (client.user.info() )

while True:
message = input('You: ')
data = client.chat.send_message('ixxxxxxxxxxxxxxxxM', message, wait=True)
print(f"{data['src_char']['participant']['name']}: {data['replies'][0]['text']}")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.