TypeError:类型Coroutine的对象不是JSON序列化的

发布于 2025-01-29 02:00:40 字数 5181 浏览 3 评论 0原文

我最近对日期转换功能有问题。

代码本身与Telegram Core API一起使用,应从我需要的频道接收消息。该函数本身似乎可以正常工作,除了代码序列化的代码部分,此错误发生了:

Unhandled exception on list
Traceback (most recent call last):
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\updates.py", line 467, in _dispatch_update
    await callback(event)
  File "E:\freelance\bot_admin\launch2.py", line 83, in list
    await dump_all_messages( channel )
  File "E:\freelance\bot_admin\launch2.py", line 74, in dump_all_messages
    json.dump(all_messages, outfile, ensure_ascii=False, cls=DateTimeEncoder)
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 179, in dump
    for chunk in iterable:
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 429, in _iterencode
    yield from _iterencode_list(o, _current_indent_level)
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 325, in _iterencode_list
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 325, in _iterencode_list
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 325, in _iterencode_list
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 439, in _iterencode
    yield from _iterencode(o, _current_indent_level)
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 438, in _iterencode
    o = _default(o)
  File "E:\freelance\bot_admin\launch2.py", line 49, in default
    return json.JSONEncoder.default(self, o)
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type coroutine is not JSON serializable

这是我目前所拥有的所有代码:

import configparser
import json
import datetime

from telethon.sync import TelegramClient , events
from telethon import connection


from datetime import date, datetime


from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch


from telethon.tl.functions.messages import GetHistoryRequest


config = configparser.ConfigParser()
config.read("config.ini")


api_id   = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']
username = config['Telegram']['username']
bot__token = config['Telegram']['bot_token']

client = TelegramClient( username, api_id, api_hash )
bot = TelegramClient( 'bot' , api_id , api_hash ).start( bot_token = bot__token )


current_action = ''

async def dump_all_messages(channel):
    offset_msg = 0 
    limit_msg = 100
    
    all_messages = []
    total_messages = 0
    total_count_limit = 2
    
    class DateTimeEncoder(json.JSONEncoder):
        
        def default(self, o):
            if isinstance(o, datetime):
                return o.isoformat()
            if isinstance(o, bytes):
                return list(o)
            return json.JSONEncoder.default(self, o)
                
    while True:
        history = await client( GetHistoryRequest (
                peer=channel,
                offset_id=offset_msg,
                offset_date=None,
                add_offset=0,
                limit=limit_msg, 
                max_id=0, 
                min_id=0,
                hash=0
            )
        )
        if not history.messages:
            break
        messages = history.messages
        for message in messages:
            all_messages.append(message.to_dict())
        offset_msg = messages[len(messages) - 1].id
        total_messages = len(all_messages)
        if total_count_limit != 0 and total_messages >= total_count_limit:
            break
        
    with open('channel_messages.json', 'w', encoding='utf8') as outfile:
        json.dump(all_messages, outfile, ensure_ascii=False, cls=DateTimeEncoder)



@bot.on( events.NewMessage )
async def list( event ):
    match current_action:
        case '/tracking':
            channel = await client.get_entity( event.message.message )
            await dump_all_messages( channel )
            raise events.StopPropagation


@bot.on( events.NewMessage( pattern = '/tracking' ) )
async def link(event):
    global current_action
    current_action = '/tracking'
    await event.respond('I\'m expecting a link')
    raise events.StopPropagation

client.start()
bot.run_until_disconnected( )

为什么会发生这种情况(或者是在哪里发生问题是)?

I have recently had a problem with the date conversion function.

The code itself works with the Telegram Core API and should receive messages from the channels I need. The function itself seems to work fine, except for the part of the code where the date and time are serialized, this error occurs in it:

Unhandled exception on list
Traceback (most recent call last):
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\updates.py", line 467, in _dispatch_update
    await callback(event)
  File "E:\freelance\bot_admin\launch2.py", line 83, in list
    await dump_all_messages( channel )
  File "E:\freelance\bot_admin\launch2.py", line 74, in dump_all_messages
    json.dump(all_messages, outfile, ensure_ascii=False, cls=DateTimeEncoder)
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 179, in dump
    for chunk in iterable:
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 429, in _iterencode
    yield from _iterencode_list(o, _current_indent_level)
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 325, in _iterencode_list
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 325, in _iterencode_list
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 325, in _iterencode_list
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 439, in _iterencode
    yield from _iterencode(o, _current_indent_level)
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 438, in _iterencode
    o = _default(o)
  File "E:\freelance\bot_admin\launch2.py", line 49, in default
    return json.JSONEncoder.default(self, o)
  File "C:\Users\79607\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type coroutine is not JSON serializable

And here is all the code I have at this moment:

import configparser
import json
import datetime

from telethon.sync import TelegramClient , events
from telethon import connection


from datetime import date, datetime


from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch


from telethon.tl.functions.messages import GetHistoryRequest


config = configparser.ConfigParser()
config.read("config.ini")


api_id   = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']
username = config['Telegram']['username']
bot__token = config['Telegram']['bot_token']

client = TelegramClient( username, api_id, api_hash )
bot = TelegramClient( 'bot' , api_id , api_hash ).start( bot_token = bot__token )


current_action = ''

async def dump_all_messages(channel):
    offset_msg = 0 
    limit_msg = 100
    
    all_messages = []
    total_messages = 0
    total_count_limit = 2
    
    class DateTimeEncoder(json.JSONEncoder):
        
        def default(self, o):
            if isinstance(o, datetime):
                return o.isoformat()
            if isinstance(o, bytes):
                return list(o)
            return json.JSONEncoder.default(self, o)
                
    while True:
        history = await client( GetHistoryRequest (
                peer=channel,
                offset_id=offset_msg,
                offset_date=None,
                add_offset=0,
                limit=limit_msg, 
                max_id=0, 
                min_id=0,
                hash=0
            )
        )
        if not history.messages:
            break
        messages = history.messages
        for message in messages:
            all_messages.append(message.to_dict())
        offset_msg = messages[len(messages) - 1].id
        total_messages = len(all_messages)
        if total_count_limit != 0 and total_messages >= total_count_limit:
            break
        
    with open('channel_messages.json', 'w', encoding='utf8') as outfile:
        json.dump(all_messages, outfile, ensure_ascii=False, cls=DateTimeEncoder)



@bot.on( events.NewMessage )
async def list( event ):
    match current_action:
        case '/tracking':
            channel = await client.get_entity( event.message.message )
            await dump_all_messages( channel )
            raise events.StopPropagation


@bot.on( events.NewMessage( pattern = '/tracking' ) )
async def link(event):
    global current_action
    current_action = '/tracking'
    await event.respond('I\'m expecting a link')
    raise events.StopPropagation

client.start()
bot.run_until_disconnected( )

Why is this happening (or rather where may the problem be)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文