Skip to content

Commit

Permalink
Merge pull request #38
Browse files Browse the repository at this point in the history
  • Loading branch information
abhint authored Dec 4, 2021
2 parents d0531d9 + c15964d commit 4dbfb2c
Show file tree
Hide file tree
Showing 27 changed files with 370 additions and 547 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#Bot Logger
log.txt
#Bot
*.txt
old
#22
*.session
# Byte-compiled / optimized / DLL files
Expand Down
113 changes: 75 additions & 38 deletions bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,80 @@
# Copyright ABHIJITH N T
# Thank you https://github.com/pyrogram/pyrogram

import os
import logging
from .env import get_env
from logging.handlers import RotatingFileHandler

logging.basicConfig(level=logging.INFO,
handlers=[logging.FileHandler(
'log.txt'), logging.StreamHandler()],
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
LOGGER = logging.getLogger(__name__)
logging.getLogger("pyrogram").setLevel(logging.WARNING)

ENV = bool(os.environ.get('ENV', False))
try:
if ENV:
AUTH_USER = []
BOT_TOKEN = os.environ.get('BOT_TOKEN')
APP_ID = os.environ.get('APP_ID')
API_HASH = os.environ.get('API_HASH')
BOT_USE = bool(os.environ.get('BOT_USE', False))
GET_AUTH_USER = os.environ.get('AUTH_USER')
for i in GET_AUTH_USER.split(','):
AUTH_USER.append(int(i))
else:
from sample_config import Config

BOT_TOKEN = Config.BOT_TOKEN
APP_ID = Config.APP_ID
API_HASH = Config.API_HASH
BOT_USE = Config.BOT_USE
AUTH_USER = Config.AUTH_USERS
except KeyError:
LOGGER.error('One or more configuration values are missing exiting now.')
exit(1)


class Msg:
source = "\nsource: https://github.com/AbhijithNT/TelegramFiletoCloud"
start = "\n<b>This bot uploads telegram files to MixDrop.co,File.io.\nAdmin: @thankappan369</b>"
error = "something is went wrong\n{error} \ncontact admin @thankappan369"
help = "Usage: <b>Send any file and the bot will upload it to MixDrop.co,File.io</b>"
API_ID = get_env('API_ID')
API_HASH = get_env('API_HASH')
BOT_TOKEN = get_env('BOT_TOKEN')


# messages

SOURCE = "\nsource: https://github.com/AbhijithNT/TelegramFiletoCloud"
START = "\n<b>This bot uploads telegram files to MixDrop.co,File.io.\nAdmin: @thankappan369</b>"
ERROR = "something is went wrong\n{error} \ncontact admin @thankappan369"
HELP = "Usage: <b>Send any file and the bot will upload it to MixDrop.co,File.io</b>"


# LOGGER

LOGGER_FILE_NAME = "filetocloud_log.txt"
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s - %(levelname)s] - %(name)s - %(message)s",
datefmt='%d-%b-%y %H:%M:%S',
handlers=[
RotatingFileHandler(
LOGGER_FILE_NAME, maxBytes=50000000, backupCount=10),
logging.StreamHandler()
])
logging.getLogger('pyrogram').setLevel(logging.WARNING)


def LOGGER(log: str) -> logging.Logger:
"""Logger function"""
return logging.getLogger(log)


# import os
# import logging

# logging.basicConfig(level=logging.INFO,
# handlers=[logging.FileHandler(
# 'log.txt'), logging.StreamHandler()],
# format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
# )
# LOGGER = logging.getLogger(__name__)
# logging.getLogger("pyrogram").setLevel(logging.WARNING)

# ENV = bool(os.environ.get('ENV', False))
# try:
# if ENV:
# AUTH_USER = []
# BOT_TOKEN = os.environ.get('BOT_TOKEN')
# APP_ID = os.environ.get('APP_ID')
# API_HASH = os.environ.get('API_HASH')
# BOT_USE = bool(os.environ.get('BOT_USE', False))
# GET_AUTH_USER = os.environ.get('AUTH_USER')
# for i in GET_AUTH_USER.split(','):
# AUTH_USER.append(int(i))
# else:
# from sample_config import Config

# BOT_TOKEN = Config.BOT_TOKEN
# APP_ID = Config.APP_ID
# API_HASH = Config.API_HASH
# BOT_USE = Config.BOT_USE
# AUTH_USER = Config.AUTH_USERS
# except KeyError:
# LOGGER.error('One or more configuration values are missing exiting now.')
# exit(1)


# class Msg:
# source = "\nsource: https://github.com/AbhijithNT/TelegramFiletoCloud"
# start = "\n<b>This bot uploads telegram files to MixDrop.co,File.io.\nAdmin: @thankappan369</b>"
# error = "something is went wrong\n{error} \ncontact admin @thankappan369"
# help = "Usage: <b>Send any file and the bot will upload it to MixDrop.co,File.io</b>"
15 changes: 15 additions & 0 deletions bot/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import os
from dotenv import load_dotenv
load_dotenv()


def get_env(name: str, terminal_action: bool = True) -> str:
if name in os.environ:
return os.environ[name]
if terminal_action:
value = input(f'Enter your {name}: ')
with open('.env', 'a') as f:
f.write(f'{name}={value}\n')
return value
else:
return name
12 changes: 6 additions & 6 deletions bot/filetocloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@
import datetime
from bot import (
BOT_TOKEN,
APP_ID,
API_ID,
API_HASH,
LOGGER
)

class CloudBot(Client):

class CloudBot(Client):
def __init__(self):
name = self.__class__.__name__.lower()
self.logger = LOGGER(__name__)

super().__init__(
name,
api_id=APP_ID,
api_id=API_ID,
api_hash=API_HASH,
bot_token=BOT_TOKEN,
plugins={
Expand All @@ -25,9 +26,8 @@ def __init__(self):

async def start(self):
await super().start()
LOGGER.info(f"BOT IS STARTED {datetime.datetime.now()}")
print(f"BOT IS STARTED ")
self.logger.info(f"BOT IS STARTED {datetime.datetime.now()}")

async def stop(self, *args):
LOGGER.info(f"BOT IS STOPPED {datetime.datetime.now()}")
await super().stop()
self.logger.info(f"BOT IS STOPPED {datetime.datetime.now()}")
3 changes: 3 additions & 0 deletions bot/helpers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .keyboard import server_select
from .file_download import download_media
from .display import progress
6 changes: 4 additions & 2 deletions bot/plugins/display/__init__.py → bot/helpers/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
# Thank you https://github.com/pyrogram/pyrogram



from hurry.filesize import size
from bot.plugins.display.time import time_data
from .time import time_data
import time
from pyrogram.types import Message


async def progress(current, total, up_msg, message, start_time):
async def progress(current, total, up_msg, message: Message, start_time):

time_now = time.time()
time_diff = time_now - start_time
Expand Down
40 changes: 40 additions & 0 deletions bot/helpers/file_download.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import time
from bot import LOGGER
from ..filetocloud import CloudBot
from pyrogram.errors import RPCError
from pyrogram.types import CallbackQuery
from ..helpers.display import progress
# from ..helpers import progress


logger = LOGGER(__name__)


async def download_media(client: CloudBot, message: CallbackQuery, ) -> str:
# client.download_media(message)
now = time.time()
user_message = await client.edit_message_text(
chat_id=message.from_user.id,
message_id=message.message.message_id,
text="processing your request...please wait",
)
try:
media_id = message.message.reply_to_message
download_file_path = await client.download_media(media_id,
progress=progress,
progress_args=(
"Downloading...",
user_message,
now
)
)
print(download_file_path)
return download_file_path
except RPCError as e:
logger.error(e)
# client.edit_message_text(
# chat_id=message.from_user.id,
# message_id=message.message.message_id,
# text="Someting is error",
# )
raise Exception(e)
28 changes: 5 additions & 23 deletions bot/plugins/keyboard/__init__.py → bot/helpers/keyboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,45 +10,27 @@
)


def server_select():
def server_select(file_name: str, size: str):
upload_selection = [
[
InlineKeyboardButton(
"transfer.sh",
callback_data="transfersh"
callback_data=f'transfersh|{file_name}|{size}'
),
InlineKeyboardButton(
"File.io",
callback_data="File.io"
callback_data=f"fileio|{file_name}|{size}"
)
],
[
InlineKeyboardButton(
"gofile.io",
callback_data="gofileio"
callback_data=f"gofileio|{file_name}|{size}"
),
InlineKeyboardButton(
"anonymfiles.com",
callback_data="anonymfiles"
callback_data=f"anonymfiles|{file_name}|{size}"
)
]
]
return InlineKeyboardMarkup(upload_selection)


def completedKeyboard(dl):
replayMarkup = InlineKeyboardMarkup(
[[
InlineKeyboardButton(
"DOWNLOAD URL",
url=f"{dl}"
)
],
[
InlineKeyboardButton(
"🗂 SOURCE",
url="https://github.com/AbhijithNT/"
)
]])

return replayMarkup
75 changes: 75 additions & 0 deletions bot/helpers/servers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from bot import LOGGER
from ..filetocloud import CloudBot
from .upload import server_upload
from ..helpers import download_media
from pyrogram.types import CallbackQuery

logger = LOGGER(__name__)


async def upload_handler(client: CloudBot, message: CallbackQuery, file_name: str, file_size: str, callback_data: str):

try:
FILE_PATH = await download_media(client, message)
except Exception as e:
logger.error(f"{e}")
await client.edit_message_text(
chat_id=message.from_user.id,
message_id=message.message.message_id,
text=f"**File downloading error:** `{e}`",
)
return
try:
if callback_data.startswith('transfersh'):
await client.edit_message_text(
chat_id=message.message.chat.id,
text="Temporarily down",
message_id=message.message.message_id,
)
return

elif callback_data.startswith('gofileio'):
url = 'https://store1.gofile.io/uploadFile'
response = await server_upload(file=FILE_PATH, url=url)
_URL = await gofileIO(response)

elif callback_data.startswith('fileio'):
url = 'https://file.io/'
response = await server_upload(file=FILE_PATH, url=url)
_URL = await fileIO(response)

elif callback_data.startswith('anonfiles'):
url = 'https://api.anonfiles.com/upload'
response = await server_upload(file=FILE_PATH, url=url)
_URL = await anonfiles(response)

await client.edit_message_text(
chat_id=message.message.chat.id,
text=(
f"File Name: `{file_name}`"
f"\nFile Size: `{file_size}`"
f'\nURL: `{_URL}`'
),
message_id=message.message.message_id
# reply_markup=completedKeyboard(dl)
)
except Exception as e:
logger.error(f'{e}')
await client.edit_message_text(
chat_id=message.from_user.id,
message_id=message.message.message_id,
text=f"**File uploading error:** `{e}`",
)
return


async def anonfiles(response):
return response['data']['file']['url']['short']


async def fileIO(response):
return response['link']


async def gofileIO(response):
return response['data']['downloadPage']
File renamed without changes.
20 changes: 20 additions & 0 deletions bot/helpers/upload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import aiohttp
import asyncio

loop = asyncio.get_event_loop()
client_exceptions = (
aiohttp.ClientResponseError,
aiohttp.ClientConnectionError,
aiohttp.ClientPayloadError,
)


async def server_upload(url: str, file: str):
try:
async with aiohttp.ClientSession() as session:
files = {'file': open(file, 'rb')}
response = await session.post(url, data=files)
responce_json = await response.json()
return responce_json
except client_exceptions as e:
raise Exception(e)
Loading

0 comments on commit 4dbfb2c

Please sign in to comment.