Search code examples
pythontelegramtelegram-bottelethon

TypeError: cannot pickle 'sqlite3.Connection' object


I have a task to make changes to the message and forward it to other channels. By changes I mean replace some x strings to y both in message text and buttons. So I created something like below:

@client.on(events.NewMessage(chats=[channelId]))
async def handler(event):
    channels = get_channels()
    replacements = get_replacements()
    msg_first = copy.copy(event.message.text)
    btn_first = copy.deepcopy(event.message.buttons)
    for channel in channels:
        replacements_api = get_replacement(channel['channel_id'], replacements)
        message_text = msg_first
        message_buttons = btn_first
        for rep_api in replacements_api:
            message_text = message_text.replace(rep_api['word'], rep_api['word_replacement'])

            if message_buttons:
                for button in message_buttons:
                    text = button[0].button.text
                    url = button[0].button.url
                    button[0].button.text = text.replace(rep_api['word'], rep_api['word_replacement'])
                    button[0].button.url = url.replace(rep_api['word'], rep_api['word_replacement'])

        event.message.text = message_text
        await client.send_message(channel['channel_id'], message=event.message, buttons=message_buttons)

But here I got an error:

 File "/usr/lib/python3.9/copy.py", line 230, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/usr/lib/python3.9/copy.py", line 161, in deepcopy
    rv = reductor(4)
TypeError: cannot pickle 'sqlite3.Connection' object

Solution

  • An SQLite connection is a stateful object synchronized with your system via the IOs it performed. By SQLite's library design, it will not be able to support the duplication and the sharing of the underlying handles of system resources.

    The impossible copy might have been triggered by your call btn_first = copy.deepcopy(event.message.buttons). Make sure these buttons only contain copyable data, or consider making your client send something simpler.

    Note that if they are actual interactive buttons, they are attached to a system resource (a handle to the window system) and local callbacks, and therefore are not deeply copyable either.