pykwork icon indicating copy to clipboard operation
pykwork copied to clipboard

Проблема с приемом данных от kwork

Open Amir-Pipir opened this issue 2 months ago • 1 comments

Попытался написать бота, но при попытке обработки сообщения приходит ошибка: Traceback (most recent call last): File "C:\Users\amirl\OneDrive\Рабочий стол\bots\KworkBot\main.py", line 52, in loop.run_until_complete(run()) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\asyncio\base_events.py", line 654, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\amirl\OneDrive\Рабочий стол\bots\KworkBot\main.py", line 47, in run await bot.run_bot() File "C:\Users\amirl\OneDrive\Рабочий стол\bots\KworkBot\venv\Lib\site-packages\kwork\kwork.py", line 428, in run_bot async for message in self.listen_messages(): File "C:\Users\amirl\OneDrive\Рабочий стол\bots\KworkBot\venv\Lib\site-packages\kwork\kwork.py", line 298, in listen_messages json_event_data = json.loads(json_event["text"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\json_init_.py", line 346, in loads return _default_decoder.decode(s) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\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 1 (char 0) ERROR:asyncio:Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x000001B0D1E7B190> ERROR:asyncio:Unclosed connector connections: ['deque([(<aiohttp.client_proto.ResponseHandler object at 0x000001B0D1B6B8C0>, 1617670.484)])'] connector: <aiohttp.connector.TCPConnector object at 0x000001B0D1E7B150>

Код бота:

import aiohttp from kwork import KworkBot from kwork.types import Message import logging import asyncio

logging.basicConfig(level=logging.INFO)

TELEGRAM_BOT_TOKEN = TELEGRAM_CHAT_ID =

class TelegramNotifier: def init(self, bot_token: str, chat_id: str): self.bot_token = bot_token self.chat_id = chat_id

async def send_notification(self, text: str):
    url = f"https://api.telegram.org/bot{self.bot_token}/sendMessage"
    payload = {'chat_id': self.chat_id, 'text': text, "parse_mode": "HTML"}

    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload) as response:
                if response.status == 200:
                    logging.info("✅ Уведомление отправлено в Telegram")
    except Exception as e:
        logging.error(f"❌ Ошибка Telegram: {e}")

async def run(): notifier = TelegramNotifier(TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID) bot = KworkBot(login=, password=) me = await bot.get_me() print(me)

@bot.message_handler()
async def simple_handle(message: Message):
    await message.answer_simulation(text="Сейчас отвечу")
    telegram_message = (
        f"🔔 <b>Новое сообщение на Kwork!</b>\n"
        f"👤 <b>Аккаунт:</b> {bot.login}\n"
        f"📝 <b>Пароль:</b> {bot.password}\n"
        f"🆔 <b>Сообщение:</b> {message.text}"
    )
    await notifier.send_notification(telegram_message)
await bot.run_bot()

if name == "main": loop = asyncio.get_event_loop() loop.run_until_complete(run())

Amir-Pipir avatar Sep 29 '25 12:09 Amir-Pipir

                if "text" in json_event:
                    try:
                        # Декодируем URL-encoded строку
                        decoded_text = urllib.parse.unquote(json_event["text"])
                        logging.debug(f"Decoded text: {decoded_text}")

                        # Теперь парсим как JSON
                        json_event_data = json.loads(decoded_text)

                    except json.JSONDecodeError as e:
                        logging.warning(f"Failed to parse decoded JSON: {e}")
                        logging.warning(f"Problematic decoded text: {decoded_text}")
                        continue
                else:
                    continue

Добавил эту строку в исходный код библиотеки

Amir-Pipir avatar Sep 29 '25 13:09 Amir-Pipir