commit a1da810c2df5221946862dd35b04de06f08c44c8 Author: krasi Date: Mon Jun 17 10:53:33 2024 +0300 130600 diff --git a/.idea/TGSendMess.iml b/.idea/TGSendMess.iml new file mode 100644 index 0000000..2c80e12 --- /dev/null +++ b/.idea/TGSendMess.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..89d0f2f --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..ac21435 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..fc7e45a --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..4e0dc5b --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..151ff73 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,237 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + { + "associatedIndex": 7 +} + + + + + { + "keyToString": { + "Python.downinstagram(01).executor": "Run", + "Python.downinstagram.executor": "Run", + "Python.downyoutube.executor": "Run", + "Python.main.executor": "Run", + "Python.mainai.executor": "Run", + "Python.testproxy.executor": "Run", + "Python.unitib.executor": "Run", + "RunOnceActivity.OpenProjectViewOnStart": "true", + "RunOnceActivity.ShowReadmeOnStart": "true", + "SHARE_PROJECT_CONFIGURATION_FILES": "true", + "git-widget-placeholder": "master", + "last_opened_file_path": "E:/code/python/BOTS/TGSendMess" + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1718211243865 + + + + \ No newline at end of file diff --git a/cookies.txt b/cookies.txt new file mode 100644 index 0000000..15090a4 --- /dev/null +++ b/cookies.txt @@ -0,0 +1,100 @@ +[ +{ + "domain": ".youtube.com", + "expirationDate": 1749808820, + "hostOnly": false, + "httpOnly": true, + "name": "__Secure-1PSIDTS", + "path": "/", + "sameSite": "unspecified", + "secure": true, + "session": false, + "storeId": "0", + "value": "sidts-CjIB3EgAEig6x8Zi1GICOToEqD1x6GhwHJgG5R0j5GV6t-27tchkeyT-FHm0-Y0xCYMJPRAA", + "id": 1 +}, +{ + "domain": ".youtube.com", + "expirationDate": 1752767720, + "hostOnly": false, + "httpOnly": false, + "name": "__Secure-3PAPISID", + "path": "/", + "sameSite": "no_restriction", + "secure": true, + "session": false, + "storeId": "0", + "value": "FfkpbSW7qg4cjkJY/AkpC4q-O3p3b3L0q-", + "id": 2 +}, +{ + "domain": ".youtube.com", + "expirationDate": 1752767720, + "hostOnly": false, + "httpOnly": true, + "name": "__Secure-3PSID", + "path": "/", + "sameSite": "no_restriction", + "secure": true, + "session": false, + "storeId": "0", + "value": "g.a000kghsPtdg15TJlEatSe9kUmdKojmpNxnkmBt3FJuuihP-pke-Ncw6Apxvn2la-U4KQfcIdAACgYKAZUSARASFQHGX2MiRWMw-0DwApH2_DAj01DK8hoVAUF8yKoc_FwmiTGATSiOQNJNuh0M0076", + "id": 3 +}, +{ + "domain": ".youtube.com", + "expirationDate": 1749808881, + "hostOnly": false, + "httpOnly": true, + "name": "__Secure-3PSIDCC", + "path": "/", + "sameSite": "no_restriction", + "secure": true, + "session": false, + "storeId": "0", + "value": "AKEyXzXyWZBYFlRUBDxnUBiaB9ay97nbpNZJr2GU0BBm9sQNxkR66DBAWuu4vJQUBjgVNjsFtQ", + "id": 4 +}, +{ + "domain": ".youtube.com", + "expirationDate": 1749808820, + "hostOnly": false, + "httpOnly": true, + "name": "__Secure-3PSIDTS", + "path": "/", + "sameSite": "no_restriction", + "secure": true, + "session": false, + "storeId": "0", + "value": "sidts-CjIB3EgAEig6x8Zi1GICOToEqD1x6GhwHJgG5R0j5GV6t-27tchkeyT-FHm0-Y0xCYMJPRAA", + "id": 5 +}, +{ + "domain": ".youtube.com", + "expirationDate": 1752767720, + "hostOnly": false, + "httpOnly": true, + "name": "LOGIN_INFO", + "path": "/", + "sameSite": "no_restriction", + "secure": true, + "session": false, + "storeId": "0", + "value": "AFmmF2swRAIgcYKxrqSte4Yn5n5-KOHYUhNIxCGXCRKkhwfEjJMnGqwCIHkLK_sRfFRA7MWIw3CiUrAKGsuwajDYekkkl6scjnlD:QUQ3MjNmeTNRTFQxQmtFWGFfVWVlM25IZ2xUeWZla0JOZVB0cUdVNkVZZnZEODRYUVh6WlJVWklTaURfN1hEa3R6cEZwVnI4ZXMyNlZ5QmJDMUROWDUySHg3cllOdlpoY1FlU1BTNWczS19tb0ZsWnBMbU95cmk2VVBac19Yd1h6MUhIWG14Q19kR3lYdFpadEprc01CWUMxblZPQjVvQzBn", + "id": 6 +}, +{ + "domain": ".youtube.com", + "expirationDate": 1752832881, + "hostOnly": false, + "httpOnly": false, + "name": "PREF", + "path": "/", + "sameSite": "unspecified", + "secure": true, + "session": false, + "storeId": "0", + "value": "f4=4000000&f6=40000000&tz=Europe.Moscow&f7=100", + "id": 7 +} +] \ No newline at end of file diff --git a/cookiesinst.txt b/cookiesinst.txt new file mode 100644 index 0000000..d70bec5 --- /dev/null +++ b/cookiesinst.txt @@ -0,0 +1,169 @@ +[ +{ + "domain": ".instagram.com", + "expirationDate": 1749755732, + "hostOnly": false, + "httpOnly": false, + "name": "csrftoken", + "path": "/", + "sameSite": "unspecified", + "secure": true, + "session": false, + "storeId": "0", + "value": "b0VvCnt6bpeRLHuNL05HSBGgRHPlity6", + "id": 1 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1752863864, + "hostOnly": false, + "httpOnly": true, + "name": "datr", + "path": "/", + "sameSite": "no_restriction", + "secure": true, + "session": false, + "storeId": "0", + "value": "djxrZgZtcBzybTD2CPPsp5jo", + "id": 2 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1718910575, + "hostOnly": false, + "httpOnly": false, + "name": "dpr", + "path": "/", + "sameSite": "no_restriction", + "secure": true, + "session": false, + "storeId": "0", + "value": "1.25", + "id": 3 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1726082132, + "hostOnly": false, + "httpOnly": false, + "name": "ds_user_id", + "path": "/", + "sameSite": "unspecified", + "secure": true, + "session": false, + "storeId": "0", + "value": "67280582376", + "id": 4 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1749839967, + "hostOnly": false, + "httpOnly": true, + "name": "ig_did", + "path": "/", + "sameSite": "unspecified", + "secure": true, + "session": false, + "storeId": "0", + "value": "ACAA553D-3700-44A5-BEC5-07D79F5D35A4", + "id": 5 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1749839872, + "hostOnly": false, + "httpOnly": false, + "name": "ig_nrcb", + "path": "/", + "sameSite": "unspecified", + "secure": true, + "session": false, + "storeId": "0", + "value": "1", + "id": 6 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1752863863, + "hostOnly": false, + "httpOnly": false, + "name": "mid", + "path": "/", + "sameSite": "unspecified", + "secure": true, + "session": false, + "storeId": "0", + "value": "Zms8dgALAAH52BW2v8XkpcE5vi3C", + "id": 7 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1752863968, + "hostOnly": false, + "httpOnly": true, + "name": "ps_l", + "path": "/", + "sameSite": "lax", + "secure": true, + "session": false, + "storeId": "0", + "value": "1", + "id": 8 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1752863968, + "hostOnly": false, + "httpOnly": true, + "name": "ps_n", + "path": "/", + "sameSite": "no_restriction", + "secure": true, + "session": false, + "storeId": "0", + "value": "1", + "id": 9 +}, +{ + "domain": ".instagram.com", + "hostOnly": false, + "httpOnly": true, + "name": "rur", + "path": "/", + "sameSite": "lax", + "secure": true, + "session": true, + "storeId": "0", + "value": "\"NCG\\05467280582376\\0541749842132:01f78301f9efc3e2cc154c1a54027e9eb25b3082dcbb57ef5dd97d150546e8fe16e3581f\"", + "id": 10 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1749841730, + "hostOnly": false, + "httpOnly": true, + "name": "sessionid", + "path": "/", + "sameSite": "unspecified", + "secure": true, + "session": false, + "storeId": "0", + "value": "67280582376%3A20ESIE9VAJ6jdr%3A29%3AAYddxd1rRNeY8tdrBEQ1T8aXfRqh-jWJDosM5aYuDg", + "id": 11 +}, +{ + "domain": ".instagram.com", + "expirationDate": 1718910575, + "hostOnly": false, + "httpOnly": false, + "name": "wd", + "path": "/", + "sameSite": "lax", + "secure": true, + "session": false, + "storeId": "0", + "value": "916x1024", + "id": 12 +} +] \ No newline at end of file diff --git a/downinstagram(01).py b/downinstagram(01).py new file mode 100644 index 0000000..b89867d --- /dev/null +++ b/downinstagram(01).py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +import logging +import os +import asyncio +from aiogram import Bot, Dispatcher, types +from aiogram.utils import executor +import instaloader + +# Ваш токен от BotFather +API_TOKEN = '5285575539:AAGu_qK23xq98fta1fJmV9oyDYoq9yhzeHM' + +# Настройка прокси +PROXY_URL = 'http://185.250.148.233:8899' +PROXY_AUTH = ('bots_man', 'Ax123456') + +# Настройка логирования с записью в файл +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('bot_instagram_logs.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера с использованием прокси +async def create_bot(): + bot = Bot(token=API_TOKEN) + dp = Dispatcher(bot) + return dp, bot + +# Функция для скачивания видео с Instagram с использованием cookies +def download_instagram_video(url): + L = instaloader.Instaloader() + # Загрузка cookies + L.load_session_from_file('bdg9840', 'session-bdg9840') + try: + post = instaloader.Post.from_shortcode(L.context, url.split("/")[-2]) + if post.is_video: + L.download_post(post, target="downloads") + video_filename = next((f for f in os.listdir("downloads") if f.endswith('.mp4')), None) + if video_filename: + video_path = os.path.join("downloads", video_filename) + return video_path, post.title + return None, None + except Exception as e: + logger.error(f"Ошибка при скачивании видео: {e}") + return None, None + +async def on_startup(dp): + logger.info('Start polling.') + +# Обработчик команды /start +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот для скачивания видео с Instagram. Отправьте ссылку на видео чтобы начать.") + +# Обработчик получения ссылки на Instagram +async def handle_instagram_link(message: types.Message): + link = message.text + await message.reply("Видео скачивается, пожалуйста подождите...") + + video_file, video_title = download_instagram_video(link) + if video_file: + caption = f"Вот ваше видео с Instagram: {video_title}" if video_title else "Вот ваше видео с Instagram" + with open(video_file, 'rb') as video: + await bot.send_video(message.chat.id, video, caption=caption) + os.remove(video_file) + else: + await message.reply("Произошла ошибка при скачивании видео. Пожалуйста, попробуйте ещё раз.") + +if __name__ == '__main__': + dp, bot = asyncio.run(create_bot()) + + dp.register_message_handler(send_welcome, commands=['start']) + dp.register_message_handler(handle_instagram_link) + + executor.start_polling(dp, skip_updates=True, on_startup=on_startup) diff --git a/downinstagram(OLD).py b/downinstagram(OLD).py new file mode 100644 index 0000000..e86b804 --- /dev/null +++ b/downinstagram(OLD).py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +import logging +import os +from aiogram import Bot, Dispatcher, types +from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton +from aiogram.utils import executor +import instaloader + +# Ваш токен от BotFather +API_TOKEN = '5285575539:AAGu_qK23xq98fta1fJmV9oyDYoq9yhzeHM' + +# Настройка логирования с записью в файл +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('bot_instagram_logs.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN) +dp = Dispatcher(bot) + +# Функция для скачивания видео с Instagram +def download_instagram_video(url): + L = instaloader.Instaloader() + try: + post = instaloader.Post.from_shortcode(L.context, url.split("/")[-2]) + if post.is_video: + L.download_post(post, target="downloads") + video_filename = next((f for f in os.listdir("downloads") if f.endswith('.mp4')), None) + if video_filename: + return os.path.join("downloads", video_filename) + return None + except Exception as e: + logger.error(f"Ошибка при скачивании видео: {e}") + return None + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот для скачивания видео с Instagram. Отправьте ссылку на видео чтобы начать.") + +# Обработчик получения ссылки на Instagram +@dp.message_handler() +async def handle_instagram_link(message: types.Message): + link = message.text + await message.reply("Видео скачивается, пожалуйста подождите...") + + video_file = download_instagram_video(link) + if video_file: + with open(video_file, 'rb') as video: + await bot.send_video(message.chat.id, video, caption="Вот ваше видео с Instagram") + os.remove(video_file) + else: + await message.reply("Произошла ошибка при скачивании видео. Пожалуйста, попробуйте ещё раз.") + +if __name__ == '__main__': + logger.info('Start polling.') + executor.start_polling(dp, skip_updates=True) diff --git a/downinstagram.py b/downinstagram.py new file mode 100644 index 0000000..19e768f --- /dev/null +++ b/downinstagram.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +import logging +import os +from aiogram import Bot, Dispatcher, types +from aiogram.utils import executor +import instaloader + +# Ваш токен от BotFather +API_TOKEN = '5285575539:AAGu_qK23xq98fta1fJmV9oyDYoq9yhzeHM' + +# Ваши учетные данные Instagram +INSTAGRAM_USERNAME = 'bdg9840' +INSTAGRAM_PASSWORD = '-4m5kRsf_xesAjZ' + + +# Путь к файлу cookie +COOKIE_FILE = 'cookiesinst.txt' + +# Настройка логирования с записью в файл +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('bot_instagram_logs.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN) +dp = Dispatcher(bot) + +# Функция для скачивания видео с Instagram +async def download_instagram_video(url): + L = instaloader.Instaloader() + + # Проверяем, существует ли файл cookie + if os.path.isfile(COOKIE_FILE): + L.load_session_from_file(INSTAGRAM_USERNAME, COOKIE_FILE) + else: + session = instaloader.Session() + session.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD) + L.context = instaloader.context.Context(session) + L.save_session_to_file(COOKIE_FILE) + + try: + post = instaloader.Post.from_shortcode(L.context, url.split("/")[-2]) + if post.is_video: + L.download_post(post, target="downloads") + video_filename = next((f for f in os.listdir("downloads") if f.endswith('.mp4')), None) + if video_filename: + return os.path.join("downloads", video_filename) + return None + except Exception as e: + logger.error(f"Ошибка при скачивании видео: {e}") + return None + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот для скачивания видео с Instagram. Отправьте ссылку на видео чтобы начать.") + +# Обработчик получения ссылки на Instagram +@dp.message_handler() +async def handle_instagram_link(message: types.Message): + link = message.text + await message.reply("Видео скачивается, пожалуйста подождите...") + + video_file = await download_instagram_video(link) + if video_file: + with open(video_file, 'rb') as video: + await bot.send_video(message.chat.id, video, caption="Вот ваше видео с Instagram") + os.remove(video_file) + else: + await message.reply("Произошла ошибка при скачивании видео. Пожалуйста, попробуйте ещё раз.") + +if __name__ == '__main__': + logger.info('Start polling.') + executor.start_polling(dp, skip_updates=True) \ No newline at end of file diff --git a/downyoutube(OLD).py b/downyoutube(OLD).py new file mode 100644 index 0000000..ad76007 --- /dev/null +++ b/downyoutube(OLD).py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +import logging +import os +from aiogram import Bot, Dispatcher, types +from aiogram.utils import executor +from pytube import YouTube, request +import youtube_dl +import yt_dlp as youtube_dl + +# Ваш токен от BotFather +API_TOKEN = '564432189:AAEF5uBBZZ3VLUl-njjwzDRlqF4HCA9ceGo' + +# Путь к файлу cookies.txt +COOKIES_FILE = 'cookies.txt' + +# Настройка логирования с записью в файл +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('bot_logs.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN) +dp = Dispatcher(bot) + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот для скачивания видео с YouTube. Отправьте команду /download чтобы начать.") + + +# Обработчик команды /download +@dp.message_handler(commands=['download']) +async def prompt_for_link(message: types.Message): + await message.reply("Пожалуйста, отправьте ссылку на видео или Shorts с YouTube.") + + +# Обработчик получения ссылки на YouTube +@dp.message_handler() +async def download_youtube_video(message: types.Message): + link = message.text + + try: + ydl_opts = { + 'outtmpl': '%(title)s.%(ext)s', + 'cookies': COOKIES_FILE, + } + + with youtube_dl.YoutubeDL(ydl_opts) as ydl: + info_dict = ydl.extract_info(link, download=True) + video_file = ydl.prepare_filename(info_dict) + + await message.reply("Видео скачивается, пожалуйста подождите...") + + with open(video_file, 'rb') as video: + await bot.send_video(message.chat.id, video, caption="Вот ваше видео с YouTube") + + os.remove(video_file) + except Exception as e: + logger.error(f"Ошибка при скачивании видео: {e}") + await message.reply("Произошла ошибка при скачивании видео. Пожалуйста, попробуйте ещё раз.") + +if __name__ == '__main__': + logger.info('Start polling.') + executor.start_polling(dp, skip_updates=True) \ No newline at end of file diff --git a/downyoutube.py b/downyoutube.py new file mode 100644 index 0000000..4851c5f --- /dev/null +++ b/downyoutube.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +import logging +import os +from aiogram import Bot, Dispatcher, types +from aiogram.utils import executor +import yt_dlp as youtube_dl + +# Ваш токен от BotFather +API_TOKEN = '564432189:AAEF5uBBZZ3VLUl-njjwzDRlqF4HCA9ceGo' + +# Путь к файлу cookies.txt +COOKIES_FILE = 'cookies.txt' + +# Настройка логирования с записью в файл +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('bot_down_tube_logs.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN) +dp = Dispatcher(bot) + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот для скачивания видео с YouTube. Отправьте команду /download чтобы начать.") + +# Обработчик команды /download +@dp.message_handler(commands=['download']) +async def prompt_for_link(message: types.Message): + await message.reply("Пожалуйста, отправьте ссылку на видео или Shorts с YouTube.") + +# Обработчик получения ссылки на YouTube +@dp.message_handler() +async def download_youtube_video(message: types.Message): + link = message.text + + try: + ydl_opts = { + 'outtmpl': '%(title)s.%(ext)s', + 'format': 'bestvideo+bestaudio/best', + 'merge_output_format': 'mp4', + } + + with youtube_dl.YoutubeDL(ydl_opts) as ydl: + info_dict = ydl.extract_info(link, download=True) + video_file = ydl.prepare_filename(info_dict) + + await message.reply("Видео скачивается, пожалуйста подождите...") + + with open(video_file, 'rb') as video: + caption = info_dict['title'] # Добавляем название видео к подписи + await bot.send_video(message.chat.id, video, caption=caption) + + os.remove(video_file) + except Exception as e: + logger.error(f"Ошибка при скачивании видео: {e}") + await message.reply("Произошла ошибка при скачивании видео. Пожалуйста, попробуйте ещё раз.") + +if __name__ == '__main__': + logger.info('Start polling.') + executor.start_polling(dp, skip_updates=True) \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..0e6bdb0 --- /dev/null +++ b/main.py @@ -0,0 +1,48 @@ +import logging +from telegram import Update +from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, dispatcher + +# Включаем логирование +logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO +) + +logger = logging.getLogger(__name__) + +# Ваш токен от BotFather +TOKEN = '7279978236:AAEnzp3moKdIUqOZ_rCLuim7tyQwVBJDGOU' + +# Список ID групп, куда будут пересылаться сообщения +TARGET_GROUP_IDS = [-1002243409068, -1002164079094_2, -1002150063511_2] # замените на реальные ID ваших групп + +def start(update: Update, context: CallbackContext) -> None: + update.message.reply_text('Привет! Я бот, который пересылает сообщения в группы.') + + +def forward_message(update: Update, context: CallbackContext) -> None: + logger.info(f"Получено сообщение в группе {update.message.chat_id}") + for group_id in TARGET_GROUP_IDS: + try: + context.bot.forward_message(chat_id=group_id, from_chat_id=update.message.chat_id, message_id=update.message.message_id) + logger.info(f"Сообщение переслано в группу {group_id}") + except Exception as e: + logger.error(f"Ошибка при пересылке сообщения в группу {group_id}: {e}") + +def main() -> None: + # Создание экземпляра Updater и Dispatcher + updater = Updater(TOKEN) + dispatcher = updater.dispatcher + + # Обработчик команды /start + dispatcher.add_handler(CommandHandler("start", start)) + + # Обработчик всех сообщений для пересылки + dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, forward_message)) + + # Запуск бота + updater.start_polling() + updater.idle() + +if __name__ == '__main__': + main() diff --git a/mainai(ORG).py b/mainai(ORG).py new file mode 100644 index 0000000..c70748d --- /dev/null +++ b/mainai(ORG).py @@ -0,0 +1,37 @@ +import logging +from aiogram import Bot, Dispatcher, types +from aiogram.types import ParseMode +from aiogram.utils import executor + +# Ваш токен от BotFather +API_TOKEN = '7279978236:AAEnzp3moKdIUqOZ_rCLuim7tyQwVBJDGOU' + +# Список ID групп, куда будут пересылаться сообщения +TARGET_GROUP_IDS = [-1002164079094, -1002243409068, -1002150063511] # замените на реальные ID ваших групп + + +# Настройка логирования +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN, parse_mode=ParseMode.HTML) +dp = Dispatcher(bot) + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот, который пересылает сообщения в группы.") + +# Обработчик всех типов сообщений для пересылки +@dp.message_handler(content_types=types.ContentType.ANY) +async def forward_message(message: types.Message): + for group_id in TARGET_GROUP_IDS: + try: + await bot.forward_message(chat_id=group_id, from_chat_id=message.chat.id, message_id=message.message_id) + logger.info(f"Сообщение переслано в группу {group_id}") + except Exception as e: + logger.error(f"Ошибка при пересылке сообщения в группу {group_id}: {e}") + +if __name__ == '__main__': + executor.start_polling(dp, skip_updates=True) diff --git a/mainai.py b/mainai.py new file mode 100644 index 0000000..6b5d5af --- /dev/null +++ b/mainai.py @@ -0,0 +1,73 @@ +import logging +from aiogram import Bot, Dispatcher, types +from aiogram.types import ParseMode +from aiogram.utils import executor + +# Ваш токен от BotFather +API_TOKEN = '7279978236:AAEnzp3moKdIUqOZ_rCLuim7tyQwVBJDGOU' +# ID группы, из которой будут пересылаться сообщения +#SOURCE_GROUP_ID = -1002243409068 # замените на реальный ID вашей основной группы +# Список ID групп, куда будут пересылаться сообщения +TARGET_GROUP_IDS = [-1002164079094, -1002243409068, -1002150063511, -1002191147447] # замените на реальные ID ваших групп + +# Список ID разрешённых пользователей +ALLOWED_USER_IDS = [523763687, 1000964643, 794413216, 954527694] # замените на реальные ID разрешённых пользователей + +# Настройка логирования с записью в файл +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('bot_logs.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN, parse_mode=ParseMode.HTML) +dp = Dispatcher(bot) + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот, который пересылает сообщения в группы.") + +# Обработчик всех типов сообщений для пересылки из личных сообщений боту +@dp.message_handler(content_types=types.ContentType.ANY) +async def forward_message(message: types.Message): + if message.chat.type == 'private': # Проверка, что сообщение пришло в личный чат + if message.from_user.id in ALLOWED_USER_IDS: # Проверка, что пользователь разрешён + for group_id in TARGET_GROUP_IDS: + try: + if message.content_type == types.ContentType.TEXT: + await bot.send_message(chat_id=group_id, text=message.text, disable_notification=True) + logger.info(f"Текстовое сообщение отправлено в группу {group_id}") + elif message.content_type == types.ContentType.PHOTO: + await bot.send_photo(chat_id=group_id, photo=message.photo[-1].file_id, caption=message.caption, disable_notification=True) + logger.info(f"Фото отправлено в группу {group_id}") + elif message.content_type == types.ContentType.DOCUMENT: + await bot.send_document(chat_id=group_id, document=message.document.file_id, caption=message.caption, disable_notification=True) + logger.info(f"Документ отправлен в группу {group_id}") + elif message.content_type == types.ContentType.VIDEO: + await bot.send_video(chat_id=group_id, video=message.video.file_id, caption=message.caption, disable_notification=True) + logger.info(f"Видео отправлено в группу {group_id}") + elif message.content_type == types.ContentType.AUDIO: + await bot.send_audio(chat_id=group_id, audio=message.audio.file_id, caption=message.caption, disable_notification=True) + logger.info(f"Аудио отправлено в группу {group_id}") + elif message.content_type == types.ContentType.VOICE: + await bot.send_voice(chat_id=group_id, voice=message.voice.file_id, caption=message.caption, disable_notification=True) + logger.info(f"Голосовое сообщение отправлено в группу {group_id}") + elif message.content_type == types.ContentType.VIDEO_NOTE: + await bot.send_video_note(chat_id=group_id, video_note=message.video_note.file_id, disable_notification=True) + logger.info(f"Видеозаметка отправлена в группу {group_id}") + else: + logger.warning(f"Тип сообщения {message.content_type} не поддерживается") + except Exception as e: + logger.error(f"Ошибка при отправке сообщения в группу {group_id}: {e}") + else: + logger.warning(f"Пользователь {message.from_user.id} не имеет доступа к боту") + await message.reply("У вас нет доступа к этому боту.") + +if __name__ == '__main__': + executor.start_polling(dp, skip_updates=True) \ No newline at end of file diff --git a/mainai_01.py b/mainai_01.py new file mode 100644 index 0000000..b602083 --- /dev/null +++ b/mainai_01.py @@ -0,0 +1,67 @@ +import logging +from aiogram import Bot, Dispatcher, types +from aiogram.types import ParseMode +from aiogram.utils import executor +from pytube import YouTube + +# Ваш токен от BotFather +API_TOKEN = '7279978236:AAEnzp3moKdIUqOZ_rCLuim7tyQwVBJDGOU' +# ID группы, из которой будут пересылаться сообщения +#SOURCE_GROUP_ID = -1002243409068 # замените на реальный ID вашей основной группы +# Список ID групп, куда будут пересылаться сообщения +TARGET_GROUP_IDS = [-1002164079094, -1002243409068, -1002150063511] # замените на реальные ID ваших групп + +# Список ID разрешённых пользователей +ALLOWED_USER_IDS = [523763687, 1000964643, 794413216] # замените на реальные ID разрешённых пользователей + +# Настройка логирования +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN, parse_mode=ParseMode.HTML) +dp = Dispatcher(bot) + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот, который пересылает сообщения в группы.") + +# Обработчик всех типов сообщений для пересылки из личных сообщений боту +@dp.message_handler(content_types=types.ContentType.ANY) +async def forward_message(message: types.Message): + if message.chat.type == 'private': # Проверка, что сообщение пришло в личный чат + if message.from_user.id in ALLOWED_USER_IDS: # Проверка, что пользователь разрешён + for group_id in TARGET_GROUP_IDS: + try: + if message.content_type == types.ContentType.TEXT: + await bot.send_message(chat_id=group_id, text=message.text, disable_notification=True) + logger.info(f"Текстовое сообщение отправлено в группу {group_id}") + elif message.content_type == types.ContentType.PHOTO: + await bot.send_photo(chat_id=group_id, photo=message.photo[-1].file_id, caption=message.caption, disable_notification=True) + logger.info(f"Фото отправлено в группу {group_id}") + elif message.content_type == types.ContentType.DOCUMENT: + await bot.send_document(chat_id=group_id, document=message.document.file_id, caption=message.caption, disable_notification=True) + logger.info(f"Документ отправлен в группу {group_id}") + elif message.content_type == types.ContentType.VIDEO: + await bot.send_video(chat_id=group_id, video=message.video.file_id, caption=message.caption, disable_notification=True) + logger.info(f"Видео отправлено в группу {group_id}") + elif message.content_type == types.ContentType.AUDIO: + await bot.send_audio(chat_id=group_id, audio=message.audio.file_id, caption=message.caption, disable_notification=True) + logger.info(f"Аудио отправлено в группу {group_id}") + elif message.content_type == types.ContentType.VOICE: + await bot.send_voice(chat_id=group_id, voice=message.voice.file_id, caption=message.caption, disable_notification=True) + logger.info(f"Голосовое сообщение отправлено в группу {group_id}") + elif message.content_type == types.ContentType.VIDEO_NOTE: + await bot.send_video_note(chat_id=group_id, video_note=message.video_note.file_id, disable_notification=True) + logger.info(f"Видеозаметка отправлена в группу {group_id}") + else: + logger.warning(f"Тип сообщения {message.content_type} не поддерживается") + except Exception as e: + logger.error(f"Ошибка при отправке сообщения в группу {group_id}: {e}") + else: + logger.warning(f"Пользователь {message.from_user.id} не имеет доступа к боту") + await message.reply("У вас нет доступа к этому боту.") + +if __name__ == '__main__': + executor.start_polling(dp, skip_updates=True) \ No newline at end of file diff --git a/session-bdg9840 b/session-bdg9840 new file mode 100644 index 0000000..8015aef Binary files /dev/null and b/session-bdg9840 differ diff --git a/testproxy.py b/testproxy.py new file mode 100644 index 0000000..e3957a6 --- /dev/null +++ b/testproxy.py @@ -0,0 +1,14 @@ +import aiohttp +import asyncio + +async def fetch(session, url): + proxy_auth = aiohttp.BasicAuth('bots_man', 'Ax123456') + async with session.get(url, proxy='http://185.250.148.233:8899', proxy_auth=proxy_auth) as response: + return await response.text() + +async def main(): + async with aiohttp.ClientSession() as session: + html = await fetch(session, 'http://example.com') + print(html) + +asyncio.run(main()) diff --git a/unitib.py b/unitib.py new file mode 100644 index 0000000..d034c32 --- /dev/null +++ b/unitib.py @@ -0,0 +1,95 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +import logging +import os +from aiogram import Bot, Dispatcher, types +from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton +from aiogram.utils import executor + +# Ваш токен от BotFather +API_TOKEN = '7437033939:AAHmX2KvRecp0Y2uKFlldWGtoZXgNvRKRUk' + +# Настройка логирования с записью в файл +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('bot_uniti_logs.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +# Инициализация бота и диспетчера +bot = Bot(token=API_TOKEN) +dp = Dispatcher(bot) + +# Переменная для хранения состояния пользователя +user_states = {} + +# Функция для создания клавиатуры с inline-кнопками +def get_inline_keyboard(): + keyboard = InlineKeyboardMarkup() + button1 = InlineKeyboardButton("Скачать с YouTube", callback_data="action_2") + button2 = InlineKeyboardButton("Отправить в группы", callback_data="action_1") + button3 = InlineKeyboardButton("Скачать с Instagram", callback_data="action_3") + keyboard.add(button1, button3) + keyboard.add(button2) + return keyboard + +# Функция для создания клавиатуры с кнопкой отмены +def get_cancel_keyboard(): + keyboard = InlineKeyboardMarkup() + cancel_button = InlineKeyboardButton("Отмена", callback_data="cancel") + keyboard.add(cancel_button) + return keyboard + +# Функция для создания клавиатуры с кнопкой "Назад" +def get_back_keyboard(): + keyboard = InlineKeyboardMarkup() + back_button = InlineKeyboardButton("Назад", callback_data="back") + keyboard.add(back_button) + return keyboard + +# Обработчик команды /start +@dp.message_handler(commands=['start']) +async def send_welcome(message: types.Message): + await message.reply("Привет! Я бот с inline-кнопками. Выберите действие:", reply_markup=get_inline_keyboard()) + +# Обработчик нажатий на inline-кнопки +@dp.callback_query_handler(lambda c: c.data and c.data.startswith('action_')) +async def process_callback_button(callback_query: types.CallbackQuery): + action = callback_query.data + if action == 'action_1': + await bot.answer_callback_query(callback_query.id, text='Вы выбрали действие 1!') + # Отправить ссылку на другого бота + keyboard = InlineKeyboardMarkup() + keyboard.add(InlineKeyboardButton("Перейти в бот перессылки", url="https://t.me/TGSendMessageFiPiBot")) + await bot.send_message(callback_query.from_user.id, "Нажмите на кнопку, чтобы перейти в другой бот.", + reply_markup=keyboard) + elif action == 'action_2': + await bot.answer_callback_query(callback_query.id, text='Вы выбрали действие 2!') + # Отправить ссылку на другого бота + keyboard = InlineKeyboardMarkup() + keyboard.add(InlineKeyboardButton("Перейти в бота скачиваний с YouTube", url="https://t.me/haligali_bot")) + await bot.send_message(callback_query.from_user.id, "Нажмите на кнопку, чтобы перейти в другой бот.", + reply_markup=keyboard) + elif action == 'action_3': + await bot.answer_callback_query(callback_query.id, text='Вы выбрали действие 3!') + # Отправить ссылку на другого бота + keyboard = InlineKeyboardMarkup() + keyboard.add(InlineKeyboardButton("Перейти в бота скачиваний с Instagram", url="https://t.me/irktestass_bot")) + await bot.send_message(callback_query.from_user.id, "Нажмите на кнопку, чтобы перейти в другой бот.", reply_markup=keyboard) + + await bot.edit_message_reply_markup(callback_query.from_user.id, callback_query.message.message_id, reply_markup=None) + +# Обработчик нажатия на кнопку "Отмена" или "Назад" +@dp.callback_query_handler(lambda c: c.data and (c.data == 'cancel' or c.data == 'back')) +async def process_cancel_or_back_button(callback_query: types.CallbackQuery): + user_states[callback_query.from_user.id] = None + await bot.answer_callback_query(callback_query.id, text='Действие отменено.') + await bot.send_message(callback_query.from_user.id, "Действие отменено.", reply_markup=get_inline_keyboard()) + +if __name__ == '__main__': + logger.info('Start polling.') + executor.start_polling(dp, skip_updates=True) \ No newline at end of file