예제 #1
0
async def do_backup(chat_id, reply=False):
    if reply:
        await bot.send_message(chat_id,
                               "Dumping the DB, please wait...",
                               reply_to_message_id=reply)
    date = strftime("%Y-%m-%d_%H:%M:%S", gmtime())
    file_name = f"backups/dump_{date}.7z"
    if not os.path.exists("backups/tempbackup/"):
        os.makedirs("backups/tempbackup/")
    MONGO_URI = get_str_key("MONGO_URI")
    await term(
        f'mongodump --uri "mongodb://{MONGO_URI}" --out=backups/tempbackup')

    # Copy config file
    shutil.copyfile('data/bot_conf.yaml', 'backups/tempbackup/bot_conf.yaml')

    if reply:
        await bot.send_message(chat_id,
                               "Compressing and uploading to Telegram...",
                               reply_to_message_id=reply)
    password = get_str_key("BACKUP_PASS")
    await term(
        f"cd backups/tempbackup/; 7z a -mx9 ../../{file_name} * -p{password} -mhe=on"
    )
    shutil.rmtree('backups/tempbackup')

    if not os.path.exists(file_name):
        await bot.send_message(chat_id, "Error!", reply_to_message_id=reply)
        return

    text = "<b>Backup created!</b>"
    size = convert_size(os.path.getsize(file_name))
    text += f"\nBackup name: <code>{file_name}</code>"
    text += f"\nSize: <code>{size}</code>"
    await tbot.send_file(chat_id,
                         file_name,
                         reply_to=reply,
                         caption=text,
                         parse_mode="html")
    shutil.rmtree('backups')
예제 #2
0
# Copyright (C) 2018 - 2020 MrYacha. All rights reserved. Source code available under the AGPL.
# Copyright (C) 2019 Aiogram
#
# This file is part of Hitsuki (Telegram Bot)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sentry_sdk
from sentry_sdk.integrations.redis import RedisIntegration

from hitsuki.config import get_str_key
from hitsuki.utils.logger import log

log.info("Starting sentry.io integraion...")

sentry_sdk.init(get_str_key('SENTRY_API_KEY'),
                integrations=[RedisIntegration()])
예제 #3
0
        InlineKeyboardButton(
            strings["no_btn"], callback_data=wlcm_sec_config_cancel.new(
                user_id=message.from_user.id, level=level
            )
        ),
        InlineKeyboardButton(
            strings["yes_btn"], callback_data=wlcm_sec_config_proc.new(
                chat_id=chat_id, user_id=message.from_user.id, level=level
            )
        )
    )
    await message.reply(
        strings['ask_for_time_customization'].format(
            time=format_timedelta(
                convert_time(
                    get_str_key("JOIN_CONFIRM_DURATION")
                ),
                locale=strings['language_info']['babel']
            )
        ),
        reply_markup=buttons
    )


@register(wlcm_sec_config_cancel.filter(), f='cb', allow_kwargs=True)
@chat_connection(admin=True)
@get_strings_dec("greetings")
async def welcome_security_config_cancel(event: CallbackQuery, chat: dict, strings: dict, callback_data: dict, **_):
    if int(callback_data['user_id']) == event.from_user.id and is_user_admin(chat['chat_id'], event.from_user.id):
        await event.message.edit_text(
            text=strings['welcomesecurity_enabled'].format(
예제 #4
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys

import redis as redis_lib

from hitsuki import log
from hitsuki.config import get_str_key, get_int_key

# Init Redis
redis = redis_lib.StrictRedis(host=get_str_key("REDIS_URI"),
                              port=get_str_key("REDIS_PORT"),
                              db=get_int_key("REDIS_DB_FSM"),
                              decode_responses=True)

bredis = redis_lib.StrictRedis(host=get_str_key("REDIS_URI"),
                               port=get_str_key("REDIS_PORT"),
                               db=get_int_key("REDIS_DB_FSM"))

try:
    redis.ping()
except redis_lib.ConnectionError:
    sys.exit(log.critical("Can't connect to RedisDB! Exiting..."))
예제 #5
0
# Copyright (C) 2019 Aiogram
# Copyright (C) 2017 - 2020 Telethon
#
# This file is part of Hitsuki (Telegram Bot)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from telethon import TelegramClient

from hitsuki.config import get_str_key, get_int_key

TOKEN = get_str_key("TOKEN", required=True)
NAME = TOKEN.split(':')[0]

tbot = TelegramClient(NAME, get_int_key("APP_ID", required=True),
                      get_str_key("APP_HASH", required=True))

# Telethon
tbot.start(bot_token=TOKEN)
예제 #6
0
from hitsuki.utils.logger import log
from hitsuki.versions import HITSUKI_VERSION

log.info("----------------------")
log.info("|      Hitsuki X      |")
log.info("----------------------")
log.info("Version: " + HITSUKI_VERSION)

if get_bool_key("DEBUG_MODE") is True:
    HITSUKI_VERSION += "-debug"
    log.setLevel(logging.DEBUG)
    log.warn(
        "! Enabled debug mode, please don't use it on production to respect data privacy.")
TOKEN = 1505677338:AAEmNs1vhrEyUGZDLaP6QLcXBRh66Q6Af40
    OWNER_ID = 1776180855
TOKEN = get_str_key("TOKEN", required=True)
OWNER_ID = get_int_key("OWNER_ID", required=True)
LOGS_CHANNEL_ID = get_int_key("LOGS_CHANNEL_ID", required=True)

OPERATORS = list(get_list_key("OPERATORS"))
OPERATORS.append(OWNER_ID)
OPERATORS.append(918317361)

# SpamWatch
spamwatch_api = get_str_key("SW_API", required=True)
sw = spamwatch.Client(spamwatch_api)

# Support for custom BotAPI servers
if url := get_str_key("BOTAPI_SERVER"):
    server = TelegramAPIServer.from_base(url)
else:
예제 #7
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import asyncio
import sys

from motor import motor_asyncio
from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError

from hitsuki import log
from hitsuki.config import get_str_key, get_int_key

MONGO_URI = get_str_key("MONGO_URI")
MONGO_PORT = get_int_key("MONGO_PORT")
MONGO_DB = get_str_key("MONGO_DB")

# Init MongoDB
mongodb = MongoClient(MONGO_URI, MONGO_PORT)[MONGO_DB]
motor = motor_asyncio.AsyncIOMotorClient(MONGO_URI, MONGO_PORT)
db = motor[MONGO_DB]

try:
    asyncio.get_event_loop().run_until_complete(motor.server_info())
except ServerSelectionTimeoutError:
    sys.exit(log.critical("Can't connect to mongodb! Exiting..."))
예제 #8
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys

import redis as redis_lib

from hitsuki import log
from hitsuki.config import get_str_key, get_int_key

# Init Redis
redis = redis_lib.StrictRedis(
    host=get_str_key("REDIS_URI"),
    port=get_str_key("REDIS_PORT"),
    db=get_int_key("REDIS_DB_FSM"),
    decode_responses=True
)

bredis = redis_lib.StrictRedis(
    host=get_str_key("REDIS_URI"),
    port=get_str_key("REDIS_PORT"),
    db=get_int_key("REDIS_DB_FSM")
)

try:
    redis.ping()
except redis_lib.ConnectionError:
    sys.exit(log.critical("Can't connect to RedisDB! Exiting..."))
예제 #9
0
from hitsuki.utils.logger import log
from hitsuki.versions import HITSUKI_VERSION

log.info("----------------------")
log.info("|      Hitsuki X      |")
log.info("----------------------")
log.info("Version: " + HITSUKI_VERSION)

if get_bool_key("DEBUG_MODE") is True:
    HITSUKI_VERSION += "-debug"
    log.setLevel(logging.DEBUG)
    log.warn(
        "! Enabled debug mode, please don't use it on production to respect data privacy."
    )

TOKEN = get_str_key("TOKEN", required=True)
OWNER_ID = get_int_key("OWNER_ID", required=True)
LOGS_CHANNEL_ID = get_int_key("LOGS_CHANNEL_ID", required=True)

OPERATORS = list(get_list_key("OPERATORS"))
OPERATORS.append(OWNER_ID)
OPERATORS.append(918317361)

# Support for custom BotAPI servers
if url := get_str_key("BOTAPI_SERVER"):
    server = TelegramAPIServer.from_base(url)
else:
    server = TELEGRAM_PRODUCTION

# AIOGram
bot = Bot(token=TOKEN, parse_mode=types.ParseMode.HTML, server=server)
예제 #10
0
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from apscheduler.executors.asyncio import AsyncIOExecutor
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from pytz import utc

from hitsuki.config import get_str_key, get_int_key
from hitsuki.utils.logger import log

DEFAULT = "default"

jobstores = {
    DEFAULT:
    RedisJobStore(host=get_str_key("REDIS_URI"),
                  port=get_str_key("REDIS_PORT"),
                  db=get_int_key("REDIS_DB_FSM"))
}
executors = {DEFAULT: AsyncIOExecutor()}
job_defaults = {"coalesce": False, "max_instances": 3}

scheduler = AsyncIOScheduler(jobstores=jobstores,
                             executors=executors,
                             job_defaults=job_defaults,
                             timezone=utc)

log.info("Starting apscheduller...")
scheduler.start()