LonamiWebs / Telethon

Pure Python 3 MTProto API Telegram client library, for bots too!
https://docs.telethon.dev
MIT License
9.95k stars 1.4k forks source link

SQLAlchemy with MySQL and allow_cache error #1256

Closed GetPHP-IR closed 4 years ago

GetPHP-IR commented 5 years ago

Checklist

when i set 'allow_cache = True' this error occur:

my sql code

CREATE TABLE `sent_files` (
  `session_id` varchar(255) NOT NULL,
  `md5_digest` blob NOT NULL,
  `file_size` bigint(20) NOT NULL,
  `type` int(11) NOT NULL,
  `id` bigint(20) DEFAULT NULL,
  `hash` bigint(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `sent_files`
  ADD PRIMARY KEY (`md5_digest`(255),`file_size`,`type`);
COMMIT;

Code that causes the issue

import getpass
import json
import re
from distutils.version import StrictVersion
from typing import Iterable
from alchemysession import AlchemySessionContainer
import MySQLdb
import click
import os

from telethon.tl.types import Message, DocumentAttributeFilename
from telethon.utils import pack_bot_file_id

from telegram_upload.files import get_file_attributes, get_file_thumb
from telethon.version import __version__ as telethon_version
from telethon import TelegramClient

if StrictVersion(telethon_version) >= StrictVersion('1.0'):
    import telethon.sync

container = AlchemySessionContainer('mysql://####')

CAPTION_MAX_LENGTH = 200

def phone_match(value):
    match = re.match(r'\+?[0-9.()\[\] \-]+', value)
    if match is None:
        raise ValueError('{} is not a valid phone'.format(value))
    return value

def get_progress_bar(action, file, length):
    bar = click.progressbar(label='{} {}'.format(action, file), length=length)

    def progress(current, total):
        bar.pos = 0
        bar.update(current)
    return progress

session = container.new_session('yt12')

class Client(TelegramClient):
    def __init__(self, config_file, **kwargs):
        config = json.load(open(config_file))
        super().__init__(session, config['api_id'], config['api_hash'], **kwargs)

    def start(
            self, bot_token='###'):
        return super().start(bot_token=bot_token)

    def send_files(self, entity, files, delete_on_success=False, print_file_id=False, by_id=False):
        for file in files:
            if not by_id:
                progress = get_progress_bar('Uploading', os.path.basename(file), os.path.getsize(file))
                name = '.'.join(os.path.basename(file).split('.')[:-1])
                thumb = get_file_thumb(file)
                caption = (name[:CAPTION_MAX_LENGTH] + '..') if len(name) > CAPTION_MAX_LENGTH else name
                try:
                    attributes = get_file_attributes(file)
                    message = self.send_file(entity, file, thumb=thumb,
                                            caption=caption,
                                            progress_callback=progress, attributes=attributes, allow_cache = False)
                except Exception:
                    raise
                finally:
                    if thumb:
                        os.remove(thumb)
                click.echo()
                if print_file_id:
                    click.echo('Uploaded successfully "{}" (file_id {})'.format(file, pack_bot_file_id(message.media)))
                if delete_on_success:
                    click.echo('Deleting {}'.format(file))
                    os.remove(file)
            else:
                #caption = (name[:CAPTION_MAX_LENGTH] + '..') if len(name) > CAPTION_MAX_LENGTH else name
                try:
                    message = self.send_file(entity, file, allow_cache = False)
                except Exception:
                    raise
                click.echo()          

    def find_files(self, entity):
        for message in self.iter_messages(entity):
            if message.document:
                yield message
            else:
                break

    def download_files(self, entity, messages: Iterable[Message], delete_on_success: bool = False):
        messages = reversed(list(messages))
        for message in messages:
            filename_attr = next(filter(lambda x: isinstance(x, DocumentAttributeFilename),
                                        message.document.attributes), None)
            filename = filename_attr.file_name if filename_attr else 'Unknown'
            progress = get_progress_bar('Downloading', filename, message.document.size)
            self.download_media(message, progress_callback=progress)
            if delete_on_success:
                self.delete_messages(entity, [message])
            print()

Traceback

Traceback (most recent call last):
  File "/usr/local/bin/telegram-upload", line 4, in <module>
    __import__('pkg_resources').run_script('telegram-upload==0.2.0', 'telegram-upload')
  File "/usr/local/lib/python3.7/dist-packages/pkg_resources/__init__.py", line 666, in run_script
    self.require(requires)[0].run_script(script_name, ns)
  File "/usr/local/lib/python3.7/dist-packages/pkg_resources/__init__.py", line 1453, in run_script
    exec(code, namespace, namespace)
  File "/usr/local/lib/python3.7/dist-packages/telegram_upload-0.2.0-py3.7.egg/EGG-INFO/scripts/telegram-upload", line 6, in <module>
    catch(upload)()
  File "/usr/local/lib/python3.7/dist-packages/telegram_upload-0.2.0-py3.7.egg/telegram_upload/exceptions.py", line 25, in wrap
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/click/core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python3.7/dist-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python3.7/dist-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/telegram_upload-0.2.0-py3.7.egg/telegram_upload/management.py", line 27, in upload
    client.send_files(to, files, delete_on_success, print_file_id, by_id)
  File "/usr/local/lib/python3.7/dist-packages/telegram_upload-0.2.0-py3.7.egg/telegram_upload/client.py", line 64, in send_files
    progress_callback=progress, attributes=attributes, allow_cache = True)
  File "/usr/local/lib/python3.7/dist-packages/telethon/sync.py", line 39, in syncified
    return loop.run_until_complete(coro)
  File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
    return future.result()
  File "/usr/local/lib/python3.7/dist-packages/telethon/client/uploads.py", line 343, in send_file
    msg = self._get_response_message(request, await self(request), entity)
  File "/usr/local/lib/python3.7/dist-packages/telethon/client/users.py", line 53, in __call__
    future = self._sender.send(request, ordered=ordered)
  File "/usr/local/lib/python3.7/dist-packages/telethon/network/mtprotosender.py", line 165, in send
    state = RequestState(request, self._loop)
  File "/usr/local/lib/python3.7/dist-packages/telethon/network/requeststate.py", line 17, in __init__
    self.data = bytes(request)
  File "/usr/local/lib/python3.7/dist-packages/telethon/tl/functions/messages.py", line 3631, in __bytes__
    bytes(self.media),
  File "/usr/local/lib/python3.7/dist-packages/telethon/tl/types/__init__.py", line 7639, in __bytes__
    bytes(self.file),
TypeError: 'str' object cannot be interpreted as an integer
Lonami commented 4 years ago

Sorry for taking so long to notice this issue. I'm going to close it because I don't think it's relevant anymore (I believe the error when converting media to bytes was fixed at some point, and it was caused by giving it the wrong types).