Exemplo n.º 1
0
def sendtelegram(tipe, user_id, notice, caption):
    if tipe == 1:
        handler = "Document"
        pramas = {"chat_id": user_id, "document": notice, "caption": caption}
    elif tipe == 2:
        handler = "Message"
        pramas = {
            "chat_id": user_id,
            "text": caption,
        }
    elif tipe == 3:
        handler = "Animation"
        pramas = {"chat_id": user_id, "animation": notice, "caption": caption}
    try:
        token = TG_BOT_TOKEN
        r = requests.get(
            "https://api.telegram.org/bot{}/send{}".format(token, handler),
            params=pramas,
        )
        logging.info(r.status_code)
        if r.status_code == 200 and r.json()["ok"]:
            return 200
        elif r.status_code == 403:
            return 403
        else:
            raise Exception
    except Exception as e:
        logging.error(e)
        logging.info("[*] Could not send telegram message.")
        return 69
Exemplo n.º 2
0
def get_mod(client: Client):
    req_result = request_time(Client)
    mes2 = "[{}]: DTU Website has not been Updated.\nLast Notice - \n{}".format(
        datetime.now().strftime("%Y-%m-%d %H:%M:%S"), req_result[1])
    if req_result[0] == 404:
        logging.info("[*] DTU Website has not been Updated.")
    elif req_result[0] == 200:
        file_id = getDocId(req_result[4])
        broadcast_list = user_list()
        total = len(broadcast_list)
        mongo_url, db1 = MONGO_URL.split("net/")
        mongo_url = mongo_url + 'net/dtu'
        os.system(
            "mongoexport --uri={} -c=users --type json --out bot/hf/users_{}".
            format(mongo_url,
                   datetime.now().strftime("%Y_%m_%d_%H_%M_%S")))
        time.sleep(10)
        alerts = 0
        while alerts < 2:
            failed = 0
            for i in range(0, (total)):
                try:
                    pp = "[{}]: DTU Site has been Updated!\n\nLatest Notice Title - \n{}\n\nUnder Tab --> {}\n\nCheers!".format(
                        datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        req_result[3], req_result[5])
                    send_status = sendtelegram(1, broadcast_list[i], file_id,
                                               pp)
                    if send_status == 200:
                        i += 1
                        logging.info("[*] Alert Sent to {}/{} people.".format(
                            i, total))
                        time.sleep(0.3)
                    elif send_status == 404:
                        failed += 1
                        i += 1
                        remove_client_from_db(broadcast_list[i])
                        time.sleep(0.3)
                except Exception as e:
                    logging.error("[*] {}".format(e))
            alerts += 1
            time.sleep(1)
        os.remove("bot/hf/recorded_status.json")
        time.sleep(2)
        done = "[*] Notice Alert Sent to {}/{} people.\n {} user(s) were removed from database.".format(
            (int(total - failed)), total, failed)
        logging.critical(done)
        sendtelegram(3, AUTH_CHANNEL,
                     "https://telegra.ph/file/d88f31ee50c8362e86aa8.mp4", done)
    with open("bot/plugins/check.txt", "w+") as f:
        f.write(mes2)
        f.close()
    try:
        looped = threading.Timer(int(REQUEST_INTERVAL),
                                 lambda: get_mod(Client))
        looped.daemon = True
        looped.start()
    except Exception as e:
        logging.critical(e)
        sendtelegram(2, AUTH_CHANNEL, "_", e)
    return mes2
Exemplo n.º 3
0
 def __init__(self, bot: commands.Bot, user: discord.User,
              message: discord.Message, reacts: Dict[str, str], callback):
     logging.info('Creating reaction prompt')
     self.bot = bot
     self.user = user
     self.message = message
     self.reacts = reacts
     self.callback = callback
Exemplo n.º 4
0
async def missed_noti(client: Client, message: Message):
    inputm = message.text
    try:
        comm, url, title, tab = inputm.split("|")
    except:
        await client.send_message(
            chat_id=AUTH_CHANNEL,
            text="Format:\n/send|notice_url|notice_title|notice_tab",
        )
        return
    file_id = getDocId(url)
    broadcast_list = user_list()
    total = len(broadcast_list)
    mongo_url, db1 = MONGO_URL.split("net/")
    mongo_url = mongo_url + "net/dtu"
    os.system(
        "mongoexport --uri={} -c=users --type json --out bot/hf/users_{}".
        format(mongo_url,
               datetime.now().strftime("%Y_%m_%d_%H_%M_%S")))
    _, _, filenames = next(os.walk("bot/hf/"))
    logging.info(filenames)
    for f in filenames:
        if not ".py" in f:
            await message.reply_document("bot/hf/{}".format(f))
    time.sleep(3)
    alerts = 1
    failed_users = set()
    failed = 0
    while alerts < 2:
        for i in range(0, (total)):
            try:
                pp = "[{}]: DTU Site has been Updated!\n\nLatest Notice Title - \n{}\n\nUnder Tab --> {}\n\nCheers!".format(
                    datetime.now().strftime("%Y-%m-%d %H:%M:%S"), title, tab)
                send_status = sendtelegram(1, broadcast_list[i], file_id, pp)
                if send_status == 200:
                    i += 1
                    logging.info("[*] Alert Sent to {}/{} people.".format(
                        i, total))
                    time.sleep(0.3)
                elif send_status == 404:
                    failed += 1
                    i += 1
                    failed_users.add(broadcast_list[i])
                    time.sleep(0.3)
            except Exception as e:
                logging.error("[*] {}".format(e))
        alerts += 1
        time.sleep(1)

    time.sleep(1)
    done = "[*] Notice Alert Sent to {}/{} people.\n {} user(s) were removed from database.".format(
        (int(total - failed)), total, failed)
    sendtelegram(3, AUTH_CHANNEL,
                 "https://telegra.ph/file/d88f31ee50c8362e86aa8.mp4", done)
    logging.critical(done)
    sys.exit()
async def request(URL):
    """
    do request and return answer in json
    :param URL: str
    :return: json
    """
    async with aiohttp.ClientSession() as session:
        async with session.get(URL) as resp:
            logging.info('request return' + (await resp.text())[:45] + '...')
            return await resp.json()
Exemplo n.º 6
0
 def __init__(self, bot: Starbot, default_config):
     self.bot = bot
     with self.cog_db() as db:
         for key in default_config:
             if key not in db or type(db[key]) is not type(
                     default_config[key]):
                 logging.info(
                     f'Updating "{key}" in DB to default value ("{default_config[key]}")'
                 )
                 db[key] = default_config[key]
Exemplo n.º 7
0
def check_status(user_id, usname):
    sendtelegram(
        2, user_id, '_',
        "Sending an alert in 5 seconds!\nPlease minimize the app if you want to check notification settings."
    )
    time.sleep(6)
    req_result = request_time(Client)
    sendtelegram(
        2, user_id, '_',
        '[*] Last Check - [{}]\nLast Notice - \n{}\nHave a Look - {}'.format(
            datetime.now().strftime("%Y-%m-%d %H:%M:%S"), req_result[1],
            req_result[2]))
    logging.info("[*] {} requested for a status update!".format(usname))
Exemplo n.º 8
0
def add_client_to_db(chat_id, f_name, usname):
    # Add user to database
    mydb = client.dtu
    mycol = mydb.users
    chat_id = str(chat_id)
    mydict = {
        "Chat Id": "{}".format(chat_id),
        "First Name": "{}".format(f_name),
        "Username": "******".format(usname),
    }
    mm = mydb.users.count_documents({"Chat Id": "{}".format(chat_id)})
    add_status = 0
    if mm == 0:
        mycol.insert_one(mydict)
        logging.info("[*] New user, {} added!".format(usname))
        add_status = 1
    else:
        add_status = 0
    total_users = len(mycol.distinct("Chat Id"))
    client.close()
    return add_status, total_users
Exemplo n.º 9
0
def getDocId(notice):
    try:
        token = TG_BOT_TOKEN
        r = requests.get(
            "https://api.telegram.org/bot{}/sendDocument".format(token),
            params={
                "chat_id": AUTH_CHANNEL,
                "document": notice,
                "caption": "[Logs] New Notice."
            })
        if r.status_code == 200 and r.json()["ok"]:
            doc_file_id = r.json()['result']['document']['file_id']
            return doc_file_id
        else:
            raise Exception
    except Exception as e:
        logging.error(e)
        logging.info("[*] [{}]: Could not send telegram message.".format(
            datetime.now()))
        doc_file_id = 0
        return doc_file_id
Exemplo n.º 10
0
def getDocId(notice):
    try:
        token = TG_BOT_TOKEN
        r = requests.get(
            "https://api.telegram.org/bot{}/sendDocument".format(token),
            params={
                "chat_id": AUTH_CHANNEL,
                "document": notice,
                "caption": "[Logs] New Notice.",
            },
        )
        if r.status_code == 200 and r.json()["ok"]:
            doc_file_id = r.json()["result"]["document"]["file_id"]
            return doc_file_id
        else:
            raise Exception
    except Exception as e:
        logging.error(e)
        logging.info("[*] [{}]: Error Sending Logs File!!.".format(
            datetime.now()))
        doc_file_id = 0
        sys.exit()
        return doc_file_id
Exemplo n.º 11
0
async def missed_noti(client: Client, message: Message):
    inputm = message.text
    try:
        comm, mess = inputm.split("|")
    except:
        await client.send_message(
            chat_id=AUTH_CHANNEL,
            text="Format:\n/promo |message",
        )
        return
    broadcast_list = user_list()
    total = len(broadcast_list)
    failed_users = []
    failed = 0
    for i in range(0, (total)):
        try:
            send_status = sendtelegram(2, broadcast_list[i], '', mess)
            if send_status == 200:
                i += 1
                logging.info("[*] Alert Sent to {}/{} people.".format(
                    i, total))
                time.sleep(0.3)
            elif send_status == 403:
                failed += 1
                i += 1
                failed_users.append(broadcast_list[i])
                time.sleep(0.3)
        except Exception as e:
            logging.error("[*] {}".format(e))
    done = "[*] Notice Alert Sent to {}/{} people.\n {} user(s) were removed from database.".format(
        (int(total - failed)), total, failed)
    logging.info(failed_users)
    sendtelegram(3, AUTH_CHANNEL,
                 "https://telegra.ph/file/d88f31ee50c8362e86aa8.mp4", done)
    logging.critical(done)
    sys.exit()
async def set_commands():
    await bot.set_my_commands(empty)
    await bot.set_my_commands(commands)
    logging.info('Commands set complete')
Exemplo n.º 13
0
    AUTH_CHANNEL,
    COMMM_AND_PRE_FIX,
    ONLINE_CHECK_START_TEXT,
    START_COMMAND,
    START_OTHER_USERS_TEXT,
    LOG_FILE_ZZGEVC,
    REQUEST_INTERVAL,
    HELP_MEHH,
)
from bot.mongodb.users import add_client_to_db
from .broadcast import get_mod, check_status
from bot import logging
from bot.__banner.banner import bannerTop

banner = bannerTop()
logging.info("\n{}".format(banner))

get_mod(Client)


@Client.on_message(
    filters.command(START_COMMAND, COMMM_AND_PRE_FIX)
    & ~filters.chat(AUTH_CHANNEL))
async def num_start_message(client: Client, message: Message):
    with open("bot/plugins/check.txt", "r") as f:
        last_check = f.read()
    await message.reply_text(START_OTHER_USERS_TEXT.format(last_check),
                             quote=True)
    add_status, total_users = add_client_to_db(message.from_user.id,
                                               message.from_user.first_name,
                                               message.from_user.username)