CharacterAI icon indicating copy to clipboard operation
CharacterAI copied to clipboard

Building a Telegram Chat Bot with this Code

Open Pavex53 opened this issue 1 year ago • 2 comments

Hey I am trying to convert the messages from the console to Telegram to start an engaging AI Bot for a community. So we can prompt the text for example "/ai hey how are you" and this message will get redirected to my Bot, waiting for answer and respond back to telegram. But I have some errors here like "Object of type BotAnswer is not JSON serializable".

Here is the code

import datetime
import time
import asyncio
import telebot
from characterai import aiocai

TOKEN = 'My Telegram API from Telegram bot'
CHARACTER_API_KEY = 'Char Token here'
TARGET_CHAT_ID = 'My chat id from telegram group'

bot = telebot.TeleBot(TOKEN)
ai_client = aiocai.Client(CHARACTER_API_KEY)


@bot.message_handler(commands=['ai'])
def handle_ai_request(message):
    chat_id = message.chat.id
    user_message = message.text.split(maxsplit=1)[1]  # Get the text after '/ai '

    async def ai_response():
        me = await ai_client.get_me()
        async with await ai_client.connect() as chat:
            new_chat = await chat.new_chat('The Char ID', me.id)
            new_chat_id = new_chat[1]  # Assuming chat.new_chat returns a tuple (new, chat_id)
            _, response = await chat.send_message('The Char ID', new_chat_id, user_message)

            return response.text

    async def send_ai_response():
        response_text = await ai_response()
        print(f'AI: {response_text}')  # Print to console
        await bot.send_message(chat_id, response_text)  # Send response to Telegram

    asyncio.run(send_ai_response())


while True:
    try:
        bot.polling(none_stop=True, timeout=10)
    except Exception as e:
        print(datetime.datetime.now(), e)
        time.sleep(5)
        continue

Sometimes it say the package is to big? Sometimes it says BotAnswer is not JSON serializable. So I thought what If I save the printed message on the console because this is just text but still errors. The Bot works without telegram integration.

Basic Code without Telegram, just for Python Compiler:

from characterai import aiocai
import asyncio


async def main():
    char = 'Your Char ID'

    client = aiocai.Client('Char 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())

Pavex53 avatar Apr 13 '24 13:04 Pavex53

im sorry , i might be late I fixed the code like this. I couldn't use Aiocai because telebot is not asynchronous and throws an error.

import telebot
from characterai import pycai
import datetime
import time

TOKEN = 'My Telegram API from Telegram bot'
CHARACTER_API_KEY = 'Char Token here'

bot = telebot.TeleBot(TOKEN)
ai_client = pycai.Client(CHARACTER_API_KEY)
def ai_response(user_message):
    me = ai_client.get_me()
    with ai_client.connect() as chat:
        new, answer = chat.new_chat(
            'The Char ID', me.id
        )
        response = chat.send_message(
          'The Char ID', new.chat_id, user_message
        )

        return response.text

@bot.message_handler(commands=['ai'])
def handle_ai_request(message):
    chat_id = message.chat.id
    print(chat_id)
    user_message = message.text.split(maxsplit=1)[1]
    print(user_message)
    response_text = ai_response(user_message)
    print(f'AI: {response_text}')  # Print to console
    bot.send_message(chat_id, response_text)



while True:
    try:
        bot.polling(none_stop=True, timeout=10)
    except Exception as e:
        print(datetime.datetime.now(), e)
        time.sleep(5)
        continue

rmarsu avatar May 30 '24 16:05 rmarsu

thank you

Pavex53 avatar Jun 26 '24 23:06 Pavex53