4
1
Fork 1

Compare commits

..

1 Commits
main ... v1.1

Author SHA1 Message Date
trueold89 92c17e9c73
Add multi language support
- Add multi language support
- Set English as default language
2023-11-01 02:22:19 +03:00
7 changed files with 26 additions and 193 deletions

View File

@ -1,10 +1,9 @@
FROM alpine:latest FROM alpine:latest
COPY bot /opt/bot COPY bot /opt/bot
RUN apk update && apk add tzdata bash python3 py-pip wget icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib && pip install telebot RUN apk update && apk add bash python3 py-pip wget icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib && pip install telebot
RUN wget https://github.com/fedarovich/qbittorrent-cli/releases/download/v1.7.22315.1/qbt-linux-alpine-x64-1.7.22315.1.tar.gz && \ RUN wget https://github.com/fedarovich/qbittorrent-cli/releases/download/v1.7.22315.1/qbt-linux-alpine-x64-1.7.22315.1.tar.gz && \
mkdir /opt/qbt && \ mkdir /opt/qbt && \
tar -zxf qbt-linux-alpine-x64-1.7.22315.1.tar.gz -C /opt/qbt && \ tar -zxf qbt-linux-alpine-x64-1.7.22315.1.tar.gz -C /opt/qbt && \
chmod a+x /opt/qbt/* && \ chmod a+x /opt/qbt/* && \
ln -sf /opt/qbt/qbt /bin/qbt && ln -sf /opt/bot/bot.py /bin/bot ln -sf /opt/qbt/qbt /bin/qbt && ln -sf /opt/bot/bot.py /bin/bot
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
ENTRYPOINT ["/bin/bot"] ENTRYPOINT ["/bin/bot"]

View File

@ -49,12 +49,10 @@ docker run \
-v /path/to/media:/path/to/media \ -v /path/to/media:/path/to/media \
-e TOKEN="<YOUR_BOT_TOKEN_HERE>" \ -e TOKEN="<YOUR_BOT_TOKEN_HERE>" \
-e PASS="change_me" \ -e PASS="change_me" \
-e QURL="http://<YOUR_QBIT_SERVER_IP_HERE>:<PORT>" \ -e QURL="<http://<YOUR_QBIT_SERVER_IP_HERE>:<PORT>" \
-e QUSER="<YOUR_QBIT_USERNAME>" \ -e QUSER="<YOUR_QBIT_USERNAME>"
-e QPASS="<YOUR_QBIT_PASSWORD>" \ -e QPASS="<YOUR_QBIT_PASSWORD>"
-e LANG="YOUR_LANG" \ -d your_image_here
-e TZ="Europe/Moscow" \
-d -it your_image_here
``` ```
##### or ##### or
@ -64,7 +62,6 @@ docker run \
services: services:
qbitdl_bot: qbitdl_bot:
image: <YOUR_IMAGE_HERE> image: <YOUR_IMAGE_HERE>
tty: true
container_name: qbitdl_bot container_name: qbitdl_bot
volumes: volumes:
- /path/to/config:/etc/bot - /path/to/config:/etc/bot
@ -73,60 +70,11 @@ services:
environment: environment:
TOKEN: "<YOUR_BOT_TOKEN_HERE>" TOKEN: "<YOUR_BOT_TOKEN_HERE>"
PASS: "change_me" PASS: "change_me"
QURL: "http://<YOUR_QBIT_SERVER_IP_HERE>:<PORT>" QURL: "<http://<YOUR_QBIT_SERVER_IP_HERE>:<PORT>"
QUSER: "<YOUR_QBIT_USERNAME>" QUSER: "<YOUR_QBIT_USERNAME>"
QPASS: "<YOUR_QBIT_PASSWORD>" QPASS: "<YOUR_QBIT_PASSWORD>"
LANG: "<YOUR_LANG>"
TZ: "Europe/Moscow"
``` ```
```bash ```bash
docker compose up -d docker compose up -d
``` ```
---
![](https://cloud.orudo.ru/apps/files_sharing/publicpreview/ffSABnXQ3cQrLZG?file=/&fileId=23851&x=1920&y=1200&a=true&etag=d2d4704b2ab90afe5edee647a19a5540)
## Run natively:
### 1. Install deps:
- python3
- py3-pip
- [qbittorrent-cli](https://github.com/fedarovich/qbittorrent-cli)
### 2. Install TeleBot lib:
```bash
pip install telebot
```
### 3. Set system ENV
```bash
# Linux
export TOKEN="YOUR_BOT_TOKEN"
export PASS="change_me"
export QURL="http://<YOUR_QBIT_SERVER_IP_HERE>:<PORT>"
export QUSER="<YOUR_QBIT_USERNAME>"
export QPASS="<YOUR_QBIT_PASSWORD>"
export LANG="<YOUR_LANG>"
# Windows PS
set TOKEN="YOUR_BOT_TOKEN"
set PASS="change_me"
set QURL="http://<YOUR_QBIT_SERVER_IP_HERE>:<PORT>"
set QUSER="<YOUR_QBIT_USERNAME>"
set QPASS="<YOUR_QBIT_PASSWORD>"
set LANG="<YOUR_LANG>"
```
#### 3.1 On windows change PATH var in `db.py`
### 4. Run
```bash
python3 bot.py
```
---
### Available languages:
##### - **"ENG"** - English
##### - **"RU"** - Russian

View File

@ -1,11 +1,11 @@
#!/usr/bin/python3 #!/usr/bin/python3
# -- coding: utf-8 -- # -- coding: utf-8 --
import func, telebot, os, log, sys import func, telebot, os
from db import PATH from db import PATH
from lang import LANG as msg from lang import LANG as msg
TOKEN = os.environ.get('TOKEN','None') TOKEN = os.environ["TOKEN"]
bot = telebot.TeleBot(TOKEN) bot = telebot.TeleBot(TOKEN)
folder_list = [] folder_list = []
dir = None dir = None
@ -31,9 +31,8 @@ def home():
@bot.message_handler(commands=['login']) @bot.message_handler(commands=['login'])
def login(message): def login(message):
id = message.from_user.id id = message.from_user.id
name = message.from_user.first_name
passwd = message.text.replace('/login ', '') passwd = message.text.replace('/login ', '')
f = str(func.u_auth(name,id,passwd)) f = str(func.u_auth(id,passwd))
if f == str(msg.get('sucauth')) or f == str(msg.get('alauth')): if f == str(msg.get('sucauth')) or f == str(msg.get('alauth')):
bot.reply_to(message,f,reply_markup=home()) bot.reply_to(message,f,reply_markup=home())
else: else:
@ -63,12 +62,11 @@ def folder_menu():
@bot.message_handler(commands=['add']) @bot.message_handler(commands=['add'])
def add(message): def add(message):
id = message.from_user.id id = message.from_user.id
name = message.from_user.first_name
txt = message.text.split(' ', 2) txt = message.text.split(' ', 2)
if len(txt) == 3: if len(txt) == 3:
key = txt[1] key = txt[1]
path = txt[2] path = txt[2]
f = str(func.add_dir(name,id,key,path)) f = str(func.add_dir(id,key,path))
else: else:
f = str(msg.get('aerr')) f = str(msg.get('aerr'))
bot.reply_to(message,f,reply_markup=home()) bot.reply_to(message,f,reply_markup=home())
@ -77,9 +75,8 @@ def add(message):
@bot.message_handler(commands=['del']) @bot.message_handler(commands=['del'])
def rm(message): def rm(message):
id = message.from_user.id id = message.from_user.id
name = message.from_user.first_name
folder = message.text.replace('/del ', '') folder = message.text.replace('/del ', '')
f = func.del_dir(name,id,folder) f = func.del_dir(id,folder)
bot.reply_to(message,str(f),reply_markup=home()) bot.reply_to(message,str(f),reply_markup=home())
# Magnet # Magnet
@ -116,7 +113,6 @@ def file(message):
@bot.message_handler(content_types=['document']) @bot.message_handler(content_types=['document'])
def download(message): def download(message):
id = message.from_user.id id = message.from_user.id
name = message.from_user.first_name
if func.auth_check(id): if func.auth_check(id):
global type, dir, folder_list global type, dir, folder_list
if dir != None and type == 'file': if dir != None and type == 'file':
@ -127,7 +123,7 @@ def download(message):
file_name = os.path.join(PATH, message.document.file_name) file_name = os.path.join(PATH, message.document.file_name)
with open(file_name, 'wb') as dl: with open(file_name, 'wb') as dl:
dl.write(file) dl.write(file)
f = str(func.file(name,id,file_name,dir)) f = str(func.file(id,file_name,dir))
dir, type, folder_list = None,None,[] dir, type, folder_list = None,None,[]
bot.reply_to(message,f) bot.reply_to(message,f)
else: else:
@ -150,34 +146,18 @@ def dirchoose(message):
def unknown(message): def unknown(message):
global type, dir, folder_list global type, dir, folder_list
id = message.from_user.id id = message.from_user.id
name = message.from_user.first_name
if func.auth_check(id): if func.auth_check(id):
txt = message.text txt = message.text
if txt in folder_list: if txt in folder_list:
dirchoose(message) dirchoose(message)
return None return None
if dir != None and type == 'magnet': if dir != None and type == 'magnet':
f = str(func.magnet(name,id,txt,dir)) f = str(func.magnet(id,txt,dir))
dir, type, folder_list = None,None,[] dir, type, folder_list = None,None,[]
bot.reply_to(message,f) bot.reply_to(message,f)
bot.reply_to(message,str(msg.get('type')),reply_markup=home()) bot.reply_to(message,str(msg.get('type')),reply_markup=home())
else: else:
bot.reply_to(message,str(msg.get('adeny'))) bot.reply_to(message,str(msg.get('adeny')))
def run():
if os.path.exists(PATH) == False:
os.mkdir(PATH)
log.start()
try:
func.qbt() func.qbt()
except:
log.errqbt()
sys.exit(1)
try:
bot.polling() bot.polling()
except:
log.errtelebot()
sys.exit(1)
if __name__ == "__main__":
run()

View File

@ -1,7 +1,7 @@
#!/usr/bin/python3 #!/usr/bin/python3
# -- coding: utf-8 -- # -- coding: utf-8 --
import db, os, log, subprocess import db, os
from db import * from db import *
from lang import LANG as msg from lang import LANG as msg
@ -12,14 +12,12 @@ def qbt():
commands = [ commands = [
f"qbt settings set url {url}", f"qbt settings set url {url}",
f"qbt settings set username {username}", f"qbt settings set username {username}",
f"echo {password} | qbt settings set password --no-warn", f"echo {password} | qbt settings set password --no-warn"
f"qbt server info "
] ]
for command in commands: for command in commands:
os.system(f"bash -c '{command}'") os.system(f"bash -c '{command}'")
output = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def u_auth(name,id,passwd): def u_auth(id,passwd):
list = [] list = []
if db.check('obj',AUTH_FILE): if db.check('obj',AUTH_FILE):
list = db.read(AUTH_FILE) list = db.read(AUTH_FILE)
@ -29,7 +27,6 @@ def u_auth(name,id,passwd):
if passwd == os.environ['PASS']: if passwd == os.environ['PASS']:
list.append(id) list.append(id)
db.write(list,AUTH_FILE) db.write(list,AUTH_FILE)
log.auth(name,id)
return msg.get('sucauth') return msg.get('sucauth')
else: else:
return msg.get('wrauth') return msg.get('wrauth')
@ -42,7 +39,7 @@ def auth_check(id):
if id in list: if id in list:
return True return True
def add_dir(name,id,dir,path): def add_dir(id,dir,path):
if auth_check(id): if auth_check(id):
if os.path.exists(path) == False: if os.path.exists(path) == False:
return str(msg.get('pne')).format(path) return str(msg.get('pne')).format(path)
@ -52,12 +49,11 @@ def add_dir(name,id,dir,path):
dict = {} dict = {}
dict.setdefault(dir,path) dict.setdefault(dir,path)
db.write(dict,DIR_FILE) db.write(dict,DIR_FILE)
log.add(name,id,dir,path)
return str(msg.get('fsa')).format(dir) return str(msg.get('fsa')).format(dir)
else: else:
return msg.get('adeny') return msg.get('adeny')
def del_dir(name,id,dir): def del_dir(id,dir):
if auth_check(id): if auth_check(id):
if db.check('obj',DIR_FILE): if db.check('obj',DIR_FILE):
dict = db.read(DIR_FILE) dict = db.read(DIR_FILE)
@ -66,32 +62,29 @@ def del_dir(name,id,dir):
if dir in dict: if dir in dict:
del dict[dir] del dict[dir]
db.write(dict,DIR_FILE) db.write(dict,DIR_FILE)
log.rm(name,id,dir)
return str(msg.get('frm')).format(dir) return str(msg.get('frm')).format(dir)
else: else:
return str(msg.get('fne')).format(dir) return str(msg.get('fne')).format(dir)
else: else:
return msg.get('adeny') return msg.get('adeny')
def magnet(name,id,link,dir): def magnet(id,link,dir):
if auth_check(id): if auth_check(id):
dict = db.read(DIR_FILE) dict = db.read(DIR_FILE)
path = dict[dir] path = dict[dir]
command = f'''qbt torrent add url "{link}" -f "{path}"''' command = f'''qbt torrent add url "{link}" -f "{path}"'''
os.system(f"bash -c '{command}'") os.system(f"bash -c '{command}'")
log.addmagnet(name,id,link)
return msg.get('add') return msg.get('add')
else: else:
return msg.get('adeny') return msg.get('adeny')
def file(name,id,file,dir): def file(id,file,dir):
if auth_check(id): if auth_check(id):
dict = db.read(DIR_FILE) dict = db.read(DIR_FILE)
path = dict[dir] path = dict[dir]
command = f'''qbt torrent add file "{file}" -f {path}''' command = f'''qbt torrent add file "{file}" -f {path}'''
os.system(f"bash -c '{command}'") os.system(f"bash -c '{command}'")
os.remove(file) os.remove(file)
log.addfile(name,id,file)
return msg.get('add') return msg.get('add')
else: else:
return msg.get('adeny') return msg.get('adeny')

View File

@ -24,17 +24,7 @@ RU = {
'ntorr': 'Неверное расширение файла', 'ntorr': 'Неверное расширение файла',
'sendm': 'Отправте Magnet-ссылку', 'sendm': 'Отправте Magnet-ссылку',
'sendf': 'Отправте .torrent файл', 'sendf': 'Отправте .torrent файл',
'adeny': 'Этот бот запривачен, гнида, блять', 'adeny': 'Этот бот запривачен, гнида, блять'
# Logs
'l_create': "Log Файл '{}' создан",
'l_start': 'Запуск бота...',
'l_auth': "Пользователь '{} ({})' успешно авторизировался",
'l_add': "Пользователь '{} ({})' добавил папку '{}' по пути '{}'",
'l_rm': "Пользователь '{} ({})' удалил папку '{}'",
'l_file': "Пользователь '{} ({})' добавил в очередь файл '{}'",
'l_magnet': "Пользователь '{} ({})' добавил в очередь ссылку '{}'",
'l_errqbt': "Ошибка подключения к qBitTorrent",
'l_errtele': "Ошибка подключения к Telegram API, проверьте ваш токен",
} }
# English # English
@ -56,17 +46,7 @@ ENG = {
'ntorr': 'Incorrect file extension', 'ntorr': 'Incorrect file extension',
'sendm': 'Send Magnet link', 'sendm': 'Send Magnet link',
'sendf': 'Send .torrent file', 'sendf': 'Send .torrent file',
'adeny': "You do not have access, first authorize '/login <password>'", 'adeny': "You do not have access, first authorize '/login <password>'"
# Logs
'l_create': "Log File '{}' created",
'l_start': 'Start bot polling...',
'l_auth': "User '{} ({})' successfully authorized",
'l_add': "User '{} ({})' added a folder '{}' with the path '{}'",
'l_rm': "User '{} ({})' deleted '{}' folder",
'l_file': "User '{} ({})' added file '{}' to the queue",
'l_magnet': "User '{} ({})' added the link '{}' to the queue",
'l_errqbt': "Error connecting to qBitTorrent",
'l_errtele': "Error connecting to Telegram API, check your token"
} }
for i in langs: for i in langs:

View File

@ -1,65 +0,0 @@
#!/usr/bin/python3
# -- coding: utf-8 --
import os, uuid
from datetime import datetime
from lang import LANG as msg
from db import PATH
def dt():
date = datetime.now().date()
time = datetime.now().time()
str = f'{date} | {time.strftime("%H:%M:%S")}'
return str
DEFAULT = ['{} LOG: ','{} ERROR: ']
ID = str(uuid.uuid1())[0:7]
FILE = f'{ID}.txt'
def file(log):
if os.path.exists(f'{PATH}logs') == False:
os.mkdir(f'{PATH}logs')
with open(f'{PATH}logs/{FILE}','a') as logfile:
logfile.write(f'{log}\n')
logfile.close()
def start():
log1 = DEFAULT[0].format(dt()) + str(msg.get('l_create').format(FILE))
log2 = DEFAULT[0].format(dt()) + str(msg.get('l_start'))
file(log2)
print(f'{log1}\n{log2}')
def auth(name,id):
log = DEFAULT[0].format(dt()) + str(msg.get('l_auth').format(name,id))
file(log)
print(log)
def add(name,id,folder,path):
log = DEFAULT[0].format(dt()) + str(msg.get('l_add').format(name,id,folder,path))
file(log)
print(log)
def rm(name,id,folder):
log = DEFAULT[0].format(dt()) + str(msg.get('l_rm').format(name,id,folder))
file(log)
print(log)
def addfile(name,id,filename):
log = DEFAULT[0].format(dt()) + str(msg.get('l_file').format(name,id,filename[9:]))
file(log)
print(log)
def addmagnet(name,id,link):
log = DEFAULT[0].format(dt()) + str(msg.get('l_magnet').format(name,id,link))
file(log)
print(log)
def errqbt():
log = DEFAULT[1].format(dt()) + str(msg.get('l_errqbt'))
file(log)
print(log)
def errtelebot():
log = DEFAULT[1].format(dt()) + str(msg.get('l_errtele'))
file(log)
print(log)

View File

@ -1,7 +1,6 @@
services: services:
qbitdl_bot: qbitdl_bot:
image: <YOUR_IMAGE_HERE> image: <YOUR_IMAGE_HERE>
tty: true
container_name: qbitdl_bot container_name: qbitdl_bot
volumes: volumes:
- /path/to/config:/etc/bot - /path/to/config:/etc/bot
@ -10,8 +9,7 @@ services:
environment: environment:
TOKEN: "<YOUR_BOT_TOKEN_HERE>" TOKEN: "<YOUR_BOT_TOKEN_HERE>"
PASS: "change_me" PASS: "change_me"
QURL: "http://<YOUR_QBIT_SERVER_IP_HERE>:<PORT>" QURL: "<http://<YOUR_QBIT_SERVER_IP_HERE>:<PORT>"
QUSER: "<YOUR_QBIT_USERNAME>" QUSER: "<YOUR_QBIT_USERNAME>"
QPASS: "<YOUR_QBIT_PASSWORD>" QPASS: "<YOUR_QBIT_PASSWORD>"
LANG: "<YOUR_LANG>" LANG: "RU"
TZ: "Europe/Moscow"