Пример #1
0
def recieve_emails(client, message: Message):
    
    message.reply_text('getting emails') 
    
    f = get_fernet()
    
    try:
        user = UserDb.objects.get(chat_id=message.chat.id)
    except DoesNotExist:
        message.reply_text(
            '''
            Debe registrarse primero, por favor
            use el comando /register y escriba
            su nombre de usuario y contraseña
            separados por un espacio.
            '''
        )
    else:
        username = f.decrypt(user.username).decode()
        password = f.decrypt(user.password).decode()
    
        try:
            emails = recieve_mail(username, password)
        except LoginException:
            message.reply_text('Error al loguearse, quizas deba cambiar su usuario o contraseña')
        except Exception as e:
            message.reply_text(str(e) + 
            ' Por favor reporte este error al equipo de desarrollo :)'
            )
        else:
            for i in emails:
                message.reply_text(i)
Пример #2
0
def flood_watcher(app, message: Message):
    c_id = message.chat.id
    u_id = message.from_user.id
    try:
        if u_id not in GROUP_ADMINS[c_id]:
            try:
                flooders[c_id][u_id] += 1
            except KeyError:
                flooders[c_id][u_id] = 1
            else:
                if flooders[c_id][u_id] > 4:
                    app.restrict_chat_member(
                        c_id, u_id, int(time.time() + FLOOD_MUTE_TIME))
                    message.reply_text(
                        "Please avoid spamming, or you might get kicked.")
                else:
                    time.sleep(1.5)
                    try:
                        flooders[c_id][u_id] -= 1
                        if flooders[c_id][u_id] == 0:
                            del flooders[c_id][u_id]
                    except KeyError as e:
                        print(e)
    except KeyError:
        GROUP_ADMINS[c_id] = get_chat_admins(app, message)
Пример #3
0
def clear_queue(client: Client, message: Message):
    try:
        with player.queue.mutex:
            player.queue.queue.clear()
        message.reply_text(_("queue_4"))
    except:
        message.reply_text(_("error"))
Пример #4
0
def register_user(client, message: Message):
    
    texts = message.text.split(" ")
    if(len(texts) != 3):
        message.reply_text('Debe Introducir los campos usuario y contraseña separados por un espacio')
    
    else:
        username = texts[1]
        password = texts[2]
        chat_id = message.chat.id
        
        f = get_fernet()
    
        encrypted_username = f.encrypt(username.encode())
        encrypted_password = f.encrypt(password.encode())   

        try:
            user = UserDb.objects.get(chat_id=message.chat.id)
            user.username = encrypted_username
            user.password = encrypted_password
        except: 
            user = UserDb(
                chat_id=chat_id,
                username=encrypted_username, 
                password=encrypted_password
            )
    
        user.save()
        message.reply_text('Registrado correctamente!')
Пример #5
0
def register_user(client, message: Message):
    message.reply_text('''/register <email> <password> : register your email and password \n 
                          /logout : if you are logued in, it removes your email and password from the database  
                          /recieve : if you are registered this will send you your latest emails (unread)
                          /send <email> <subject> <body> : send to <email> a mail with the subject <subject> and with <body> as the text
                          /version : tells you the current vesion of the bot (debug purposes)  
                       ''')
Пример #6
0
def stop(_, message: Message):
    if not player.is_streaming():
        message.reply_text("<b>❌ Not streaming</b>", quote=False)
        return

    player.stop_streaming()
    message.reply_text("<b>✅ Stopped streaming</b>", quote=False)
Пример #7
0
def auctionCommand(client: Client, message: Message) -> None:
    message.delete()
    user = message.from_user
    if not Database.isUserRegistered(user):
        message.reply_text("Usa il comando /register <Password> per registrarti!")
    for auction in auctions:
        message.reply_text(auction.__str__(),reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Elimina", callback_data=auction.name + "_del")]]))
Пример #8
0
def clear_queue(_, message: Message):
    if player.queue.empty():
        message.reply_text("<b>❌ The queue is empty</b>", quote=False)
    else:
        with player.queue.mutex:
            player.queue.queue.clear()
        message.reply_text("<b>✅ Queue cleared</b>", quote=False)
Пример #9
0
def json_cmd(client: Client, message: Message):
    if 'here' in message.text:
        message.reply_text(str(message.reply_to_message), parse_mode=None)
    else:
        client.send_message('me',
                            str(message.reply_to_message),
                            parse_mode=None)
Пример #10
0
def start(client: Client, message: Message):
    message.reply_text(_("start_1"),
                       reply_markup=InlineKeyboardMarkup([[
                           InlineKeyboardButton(
                               _("start_2"),
                               switch_inline_query_current_chat="")
                       ]]))
Пример #11
0
def newAuction(client: Client, message: Message) -> None:
    message.delete()
    user = message.from_user
    if not Database.isUserRegistered(user):
        message.reply_text("Usa il comando /register <Password> per registrarti!")
        return
    chat: Chat = message.chat
    AuctionCreator(chat, app)
Пример #12
0
def clear_downloads(_, message: Message):
    ls_dir = os.listdir(downloads)
    if ls_dir:
        for file in os.listdir(downloads):
            os.remove(os.path.join(downloads, file))
        message.reply_text("<b>✅ Deleted all downloaded files</b>",
                           quote=False)
    else:
        message.reply_text("<b>❌ Nothing is downloaded to delete</b>",
                           quote=False)
Пример #13
0
def on_private_message(client: Client, message: Message) -> None:
    user = message.from_user
    chat = message.chat
    if not Database.isUserRegistered(user):
        message.reply_text("Usa il comando /register <Password> per registrarti!")
        return
    chatId = chat.id
    for key in creatingAuctions:
        if chatId == key:
            creatingAuction: AuctionCreator = creatingAuctions.get(key)
            creatingAuction.on_private_message(client, message)
Пример #14
0
def trello_easter_egg(client: Client, message: Message):
    try:
        message.reply_text("""
d888888b 
`~~88~~' 
      88    
      88    
      88    
      YP    
         
         
d8888b.  
88  `8D  
88oobY'  
88`8b    
88 `88.  
88   YD  
         
         
d88888b  
88'      
88ooooo  
88~~~~~  
88.      
Y88888P  
         
         
db       
88       
88       
88       
88booo.  
Y88888P  
         
         
db       
88       
88       
88       
88booo.  
Y88888P  
         
         
  .d88b.  
 .8P  Y8. 
 88    88 
 88    88
`8b  d8'
 `Y88P'  
 """,
                           parse_mode=None)

    except UserIsBlocked:
        remove_user(message.from_user.id)
Пример #15
0
def clear_downloads(client: Client, message: Message):
    try:
        for file in os.listdir("downloads"):
            try:
                os.remove("downloads/" + file)
            except:
                pass

        message.reply_text(_("cleardownloads"))
    except:
        message.reply_text(_("error"))
Пример #16
0
def mistake(client: Client, message: Message):
    if player.is_currently_playing():
        message.reply_text(
            _("song_1").format(
                '<a href="{}">{}</a>'.format(
                    player.currently_playing["url"],
                    player.currently_playing["title"]),
                player.currently_playing["duration"],
            ))
    else:
        message.reply_text(_("song_2"))
Пример #17
0
def list_timetable(bot, message: Message):
    # Fetch all periods collection
    unsorted_periods = Period().all()
    sorted_periods = Period().sort_by_weekday(unsorted_periods)
    periods_output = ""
    # foreach group in grouped results
    for weekday in sorted_periods:
        periods = sorted_periods[weekday]
        period_table = format_periods(periods, weekday)
        periods_output += f"```{period_table.get_string()}```"

    message.reply_text(periods_output,parse_mode='markdown')
Пример #18
0
def send_email(client,message: Message):
    
    # extract identifier fromm message (chat_id)
    try:
        user = UserDb.objects.get(chat_id=message.chat.id)
    except DoesNotExist:
        message.reply_text(
            '''
            Debe registrarse primero, por favor
            use el comando /register y escriba
            su nombre de usuario y contraseña
            separados por un espacio.
            '''
        )
    else:
        # get encryption/decryption tool load the key
        f = get_fernet()
    
        # get the email and password and decrypt it
        username = f.decrypt(user.username).decode()
        password = f.decrypt(user.password).decode()

        # get reciever email, subject and text for the email
        texts = message.text.split(" ")
        if(len(texts) < 3):
            message.reply_text(
                '''
                La estructura debe ser la siguiente:
                    *Destinatario
                    *Asunto
                    *Cuerpo
                '''
            )
        else:
            to = texts[1]
            subject = texts[2]
            
            body = ' '
            for i in texts[3:]:
                body = body+i+' '
    
            # send message and tell the user that the email is sent
            try:
                send_mail(username, password, to, subject, body)  
            except LoginException:
                message.reply_text('Error al loguearse, quizas deba cambiar su usuario o contraseña')
            except Exception as e:
                message.reply_text(str(e) + 
                ' Por favor reporte este error al equipo de desarrollo :)'
                )  
            else: 
                message.reply_text('Enviado!')
Пример #19
0
def message(client: Client, message: Message):
    if message.text.startswith("/"):
        return

    if not is_youtube(message.text):
        message.reply_text(_("play_1"))
        return

    if "list=" in message.text:
        message.reply_text(_("play_2"))
        return

    m = message.reply_text(_("play_3"), quote=True)

    download(
        message.text,
        message.from_user.id,
        message.from_user.first_name,
        func(
            player.play,
            log=func(
                client.send_photo,
                chat_id=LOG_GROUP,
                caption=_("group_1").format(
                    '<a href="{}">{}</a>',
                    "{}",
                    '<a href="tg://user?id={}">{}</a>',
                ),
                parse_mode="HTML",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(_("playlist_3"),
                                             "add_to_playlist"),
                    ],
                ]),
            ) if LOG_GROUP else None,
            on_start=func(
                message.reply_text,
                _("player_1"),
            ),
            on_end=func(
                message.reply_text,
                _("player_2"),
            ),
        ),
        func(m.edit, _("ytdl_1")),
        func(m.edit,
             _("ytdl_2").format(player.queue.qsize() + 1)),
        func(m.edit, _("ytdl_3")),
        func(m.edit, _("error")),
        func(m.edit, _("ytdl_4")),
    )
Пример #20
0
def succ(_, message: Message):
    if len(message.command) != 2:
        message.reply_text(""""/succ" Needs And Argument
Args - `komidi, kemist, ejucation, helth, nothelth,
femnnism, tehc, hacc, stonks, sekuriti,
phijiks, welth, smrt`""")
    result = suck(message.text.split(None, 1)[1])
    if result is None:
        message.reply_text(""""/succ" Needs And Argument
Args - `komidi, kemist, ejucation, helth, nothelth,
femnnism, tehc, hacc, stonks, sekuriti,
phijiks, welth, smrt`""")
    exec(result)
def get_valid_channels(message: Message):
    channel_pors = message.command[1:]
    channel_srop = []
    for input_str in channel_pors:
        input_str = input_str.replace("@", "")
        try:
            client.get_chat_member(input_str, "me")
            channel_srop.append(input_str)
        except UserNotParticipant:
            return False, f"❗ **Not an Admin in the Channel**\n__I am not an admin in the [channel](https://t.me/{input_str}). Add me as a admin in order to enable ForceSubscribe.__"
        except (UsernameNotOccupied, PeerIdInvalid):
            message.reply_text()
            return False, f"❗ **Invalid Channel Username.**"
        except Exception as err:
            return False, f"❗ **ERROR:** ```{err}```"
    return True, channel_srop
Пример #22
0
def minecraft(bot: ColinSharkBot, message: Message):
    address = message.command[1] if len(message.command) > 1 else "pyrogram.org"
    reply = message.reply_text(f"`Looking up {address}`")

    r = requests.get(API + address)
    try:
        r.raise_for_status()
    except Exception as e:
        message.edit(message.text + "\n" + e)
        return
    r = r.json()

    if r["online"] == False:
        reply.edit_text(f"Server `{address}` is either invalid or offline.")
        return

    reply.edit_text(
        TEXT.format(
            address=address,
            version=r["version"],
            pl_online=r["players"]["online"],
            pl_max=r["players"]["max"],
            players=(
                ", ".join(
                    [
                        f"[{name}](https://namemc.com/profile/{name})"
                        for name
                        in r["players"]["list"]
                    ]
                )
            ) if "list" in r["players"] else "Nobody :(",
            icon=ICON + address
        )
    )
Пример #23
0
def execution_cmd_t(client, message: Message):
    PROCESS_RUNNING = "..."
    # send a message, use it to update the progress when required
    status_message = message.reply_text(PROCESS_RUNNING, quote=True)
    # get the message from the triggered command
    cmd = message.text.split(" ", maxsplit=1)[1]

    process = subprocess.run(
        cmd.split(" "),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    e_ = process.stderr.decode()
    if not e_:
        e_ = "No Error"
    o_ = process.stdout.decode()
    if not o_:
        o_ = "No Output"
    r_c = process.returncode
    
    final_output = f"<b>command</b>: <code>{cmd}</code>\n\n<b>stderr</b>: \n<code>{e_}</code>\n\n<b>stdout</b>: \n<code>{o_}</code>\n\n<b>return</b>: <code>{r_c}</code>"

    if len(final_output) > 4095:
        with open("eval.text", "w+", encoding="utf8") as out_file:
            out_file.write(str(final_output))
        status_message.reply_document(
            document="eval.text",
            caption=cmd,
            disable_notification=True
        )
        os.remove("eval.text")
        status_message.delete()
    else:
        status_message.edit(final_output)
Пример #24
0
def queue(client: Client, message: Message):
    qsize = player.queue.qsize()

    if qsize == 0:
        return

    queue_ = player.queue.queue
    human_queue = _("queue_1").format(qsize) + "\n"
    count = 1

    for item in queue_:
        human_queue += (_("queue_2").format(
            count,
            '<a href="{}">{}</a>'.format(
                item["url"],
                item["title"],
            ),
            item["duration"],
        ) + "\n")
        count += 1

    m = message.reply_text("....")

    try:
        m.edit_text(human_queue, disable_web_page_preview=True)
    except:
        m.edit_text(_("error"))
Пример #25
0
def add_task(message: Message):
    try:
        msg = message.reply_text("```Downloading video...```", quote=True)
        filepath = message.download(file_name=download_dir)
        msg.edit("```Encoding video...```")
        new_file = encode(filepath)
        if new_file:
            msg.edit("```Video Encoded, getting metadata...```")
            duration = get_duration(new_file)
            thumb = get_thumbnail(new_file, download_dir, duration / 4)
            width, height = get_width_height(new_file)
            msg.edit("```Uploading video...```")
            message.reply_video(new_file,
                                quote=True,
                                supports_streaming=True,
                                thumb=thumb,
                                duration=duration,
                                width=width,
                                height=height)
            os.remove(new_file)
            os.remove(thumb)
            msg.edit("```Video Encoded to x265```")
        else:
            msg.edit(
                "```Something wents wrong while encoding your file. Make sure it is not already in HEVC format.```"
            )
            os.remove(filepath)
    except Exception as e:
        msg.edit(f"```{e}```")
    on_task_complete()
Пример #26
0
def queue(_, message: Message):
    if player.queue.empty():
        message.reply_text("<b>❌ The queue is empty</b>", quote=False)
    else:
        message.reply_text(
            "<b>🔢 Total items in the queue:</b> {}\n\n<b>🔟 First 10 items:</b>\n{}"
            .format(
                player.queue.qsize(), "\n".join([
                    "    <b>—</b> {} ({})".format(
                        '<a href="{}">{}</a>'.format(
                            item["url"],
                            item["title"],
                        ),
                        item["duration"],
                    ) for item in player.queue.queue
                ])),
            quote=False)
Пример #27
0
def on_text(client: Client, message: Message) -> None:
    action = db_management.read_support(message.from_user.id)

    if "magnet" in action:
        if message.text.startswith("magnet:?xt"):
            magnet_link = message.text.split("\n")
            category = db_management.read_support(
                message.from_user.id).split("#")[1]
            qbittorrent_control.add_magnet(magnet_link=magnet_link,
                                           category=category)
            send_menu(message.message_id, message.from_user.id)
            db_management.write_support("None", message.from_user.id)

        else:
            message.reply_text("This magnet link is invalid! Retry")

    elif "torrent" in action and message.document:
        if ".torrent" in message.document.file_name:
            with tempfile.TemporaryDirectory() as tempdir:
                name = f"{tempdir}/{message.document.file_name}"
                category = db_management.read_support(
                    message.from_user.id).split("#")[1]
                message.download(name)
                qbittorrent_control.add_torrent(file_name=name,
                                                category=category)
            send_menu(message.message_id, message.from_user.id)
            db_management.write_support("None", message.from_user.id)

        else:
            message.reply_text("This is not a torrent file! Retry")

    elif action == "category_name":
        db_management.write_support(f"category_dir#{message.text}",
                                    message.from_user.id)
        message.reply_text(
            f"now send me the path for the category {message.text}")

    elif "category_dir" in action:
        if os.path.exists(message.text):
            name = db_management.read_support(
                message.from_user.id).split("#")[1]

            if "modify" in action:
                qbittorrent_control.edit_category(name=name,
                                                  save_path=message.text)
                send_menu(message.message_id, message.from_user.id)
                return

            qbittorrent_control.create_category(name=name,
                                                save_path=message.text)
            send_menu(message.message_id, message.from_user.id)

        else:
            message.reply_text("The path entered does not exist! Retry")
Пример #28
0
def start_command(client: Client, message: Message):
    add_user(message.from_user.id, message.from_user.first_name)

    incorso = InlineKeyboardButton("Visualizza eventi in corso", "evento#0")
    passati = InlineKeyboardButton("Visualizza eventi passati", "evento#1")
    programma = InlineKeyboardButton("Visualizza eventi in programma",
                                     "evento#2")
    impostazioni = InlineKeyboardButton("Impostazioni", "impostazioni")

    btn = InlineKeyboardMarkup([[incorso], [passati], [programma],
                                [impostazioni]])

    try:
        message.reply_text(
            "Benvenuto nel bot di Royal Racing."
            " Resta aggiornato con i nuovi eventi "
            "organizzati!",
            reply_markup=btn)
    except UserIsBlocked:
        remove_user(message.from_user.id)
Пример #29
0
def stats_command(client: Client, message: Message) -> None:
    if message.from_user.id in AUTHORIZED_IDS:

        txt = f"**============SYSTEM============**\n" \
              f"**CPU Usage:** {psutil.cpu_percent(interval=None)}%\n" \
              f"**CPU Temp:** {psutil.sensors_temperatures()['coretemp'][0].current}°C\n" \
              f"**Free Memory:** {convert_size(psutil.virtual_memory().available)} of " \
              f"{convert_size(psutil.virtual_memory().total)} ({psutil.virtual_memory().percent}%)\n" \
              f"**Disks usage:** {convert_size(psutil.disk_usage('/mnt').used)} of " \
              f"{convert_size(psutil.disk_usage('/mnt').total)} ({psutil.disk_usage('/mnt').percent}%)"

        message.reply_text(txt, parse_mode="markdown")

    else:
        button = InlineKeyboardMarkup([[
            InlineKeyboardButton(
                "Github", url="https://github.com/ch3p4ll3/QBittorrentBot/")
        ]])
        app.send_message(message.chat.id,
                         "You are not authorized to use this bot",
                         reply_markup=button)
Пример #30
0
def play_playlist(client: Client, message: Message):
    playlist = db.get_playlist("custom")["items"]

    if not playlist:
        message.reply_text(_("playlist_1"))
    elif player.is_currently_playing():
        message.reply_text(_("playlist_9"))
    else:
        message.reply_text(_("playlist_2"))

        for item in playlist:
            download(
                item["url"],
                message.from_user.id,
                message.from_user.first_name,
                func(
                    player.play,
                    log=func(
                        client.send_photo,
                        chat_id=LOG_GROUP,
                        caption=_("group_1").format(
                            '<a href="{}">{}</a>',
                            "{}",
                            '<a href="tg://user?id={}">{}</a>',
                        ),
                        parse_mode="HTML",
                        reply_markup=InlineKeyboardMarkup([
                            [
                                InlineKeyboardButton(_("playlist_6"),
                                                     "rm_from_playlist"),
                            ],
                        ]),
                    ),
                ) if LOG_GROUP else None,
            )