Софт Отправка текста и фотографий из буфера обмена в Telegram

Vespan

loneliness
Проверенный
2,105
1,633
4. Переходим по пути папки и вводим в консоль. Это установит необходимые зависимости
Там много лишнего :[[[
я это установил и пошло:
asyncio
pyperclip
aiogram
PIL
hashlib
aapt
absl-py
aiofiles
aiogram
aiohttp
aiosignal
altgraph

Сделай отправку .gif и любых файлов(если размер файла <=3мб(или можно самому отредактировать под себя))
А ну не знаю ли нужно.. если отправить сообщение-файл тг боту то оно отправляется в буфер обмена пк

Теперь при копировании любых файлов они отправляются в телеграм(если размер файла не привышает <= sendingFileSize(в мегабайтах))
Python:
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) ##не знаю почему, но не работает если есть беск.цыкл в скрипте, исправите кароч, мне и этого хватает)
Шоб скомпилировать в .exe, перемеименуйте разширение файла на .pyw, после чего через pyinstaller компилируете файлик(pyinstaller --onefile path_file_.pyw)
Теперь запуск этого файлика не будет видно окно консоли, закрыть можно только через панель задач
 
Последнее редактирование:
  • Нравится
Реакции: colton.