from aiogram import Bot, Dispatcher, types, executor
import asyncio
import pyperclip
from PIL import ImageGrab
from pathlib import Path
from tkinter import Tk, TclError
import hashlib
import os
import io
sendingFileSize = 5##mb
TOKEN = '1111'
USERID = int('1111')
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
def get_clipboard_as_path():#https://python-forum.io/thread-24315.html
root = Tk()
root.withdraw()
try:
content = root.selection_get(selection="CLIPBOARD")
except TclError:
return None
finally:
root.destroy()
file = Path(content)
try:
if file.exists():
return file
except OSError:
pass
return None
def getClipboard():
if get_clipboard_as_path():
return get_clipboard_as_path(),'file'
else:
return pyperclip.paste(),'text'
async def get_content_hash(content):
if isinstance(content, bytes):
return hashlib.md5(content).hexdigest()
else:
return hashlib.md5(content.encode()).hexdigest()
async def main():
clipboard = ''
while True:
content, type = getClipboard()
try:
content,type = getClipboard()
if content != clipboard and type == 'file':
clipboard = content#
with open(content,'rb') as f:
stat = os.stat(f.name)
size = stat.st_size
if (size/1024/1024) <= sendingFileSize:
print('send file')
await bot.send_document(chat_id=USERID, document=f)
else:
screenshot = ImageGrab.grabclipboard()
if screenshot:
with io.BytesIO() as output:
screenshot.save(output, format="PNG")
screenshot_bytes = output.getvalue()
screenshot_hash = await get_content_hash(screenshot_bytes)
if clipboard != screenshot_hash:
clipboard = screenshot_hash#
print('send image')
await bot.send_photo(chat_id=USERID, photo=screenshot_bytes)
elif content != clipboard and type == 'text':
clipboard = content#
print('send text',content)
await bot.send_message(chat_id=USERID, text=content)
except Exception as e:
print('[error]',e)
@dp.message_handler()
def echo(message: types.Message):
# await bot.send_message(message.chat.id, message.text)
pyperclip.copy(message.text)
print('copy ',message.text)
asyncio.run(main())
# executor.start_polling(dp) ##не знаю почему, но не работает если есть беск.цыкл в скрипте, исправите кароч, мне и этого хватает)