Example #1
0
async def set_group_photo(gpic):
    """ For .setgpic command, changes the picture of a group """
    if not gpic.is_group:
        await gpic.edit("`I don't think this is a group.`")
        return
    replymsg = await gpic.get_reply_message()
    chat = await gpic.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    photo = None

    if not admin and not creator:
        await gpic.edit(NO_ADMIN)
        return

    if replymsg and replymsg.media:
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split('/'):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await gpic.edit(INVALID_MEDIA)

    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await
                                 gpic.client.upload_file(photo)))
            await gpic.edit(CHAT_PP_CHANGED)

        except PhotoCropSizeSmallError:
            await gpic.edit(PP_TOO_SMOL)
        except ImageProcessFailedError:
            await gpic.edit(PP_ERROR)
Example #2
0
async def oturumacvebotlogolustur(stri, aid, ahash):
    try:
        Client = TelegramClient(StringSession(stri), aid, ahash)
        await Client.start()
        ms = await Client.send_message('me', LANG['SIRIUSERBOT'])
        KanalId = await Client(
            CreateChannelRequest(title='SiriUserBot BotLog',
                                 about=LANG['AUTO_BOTLOG'],
                                 megagroup=True))

        KanalId = KanalId.chats[0].id

        Photo = await Client.upload_file(file='20210701_125852.jpg')
        await Client(EditPhotoRequest(channel=KanalId, photo=Photo))
        msg = await Client.send_message(KanalId, LANG['DONT_LEAVE'])
        await msg.pin()

        KanalId = str(KanalId)
        if "-100" in KanalId:
            return KanalId
        else:
            return "-100" + KanalId
    except:
        KanalId = 'err'
        return KanalId
Example #3
0
async def set_group_photo(gpic):
    """ .setgpic komutu ile grubunuzun fotoğrafını değiştirebilirsiniz """
    if not gpic.is_group:
        await gpic.edit("`Bunun bir grup olduğunu sanmıyorum.`")
        return
    replymsg = await gpic.get_reply_message()
    chat = await gpic.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    photo = None

    if not admin and not creator:
        await gpic.edit(NO_ADMIN)
        return

    if replymsg and replymsg.media:
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split('/'):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await gpic.edit(INVALID_MEDIA)

    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await
                                 gpic.client.upload_file(photo)))
            await gpic.edit(CHAT_PP_CHANGED)

        except PhotoCropSizeSmallError:
            await gpic.edit(PP_TOO_SMOL)
        except ImageProcessFailedError:
            await gpic.edit(PP_ERROR)
Example #4
0
async def setgrouppic(eventPic):
    if eventPic.text[0].isalpha() or eventPic.text[0] in ("/", "#", "@", "!"):
        return
    if eventPic.reply_to_msg_id:
        replymsg = await eventPic.get_reply_message()
        chat = await eventPic.get_chat()
        admin = chat.admin_rights
        creator = chat.creator
        photo = None
        if not admin and not creator:
            await eventPic.edit("`I am not an admin!`")
            return
        if replymsg and replymsg.media:
            if isinstance(replymsg.media, MessageMediaPhoto):
                photo = await eventPic.client.download_media(
                    message=replymsg.photo)
            elif "image" in replymsg.media.document.mime_type.split("/"):
                photo = await eventPic.client.download_file(
                    replymsg.media.document)
            else:
                await eventPic.edit("`Invalid Extension`")
        if photo:
            try:
                await eventPic.client(
                    EditPhotoRequest(eventPic.chat_id, await
                                     eventPic.client.upload_file(photo)))
                await eventPic.edit("`Chat Picture Changed`")

            except PhotoCropSizeSmallError:
                await eventPic.edit("`The image is too small`")
            except ImageProcessFailedError:
                await eventPic.edit("`Failure while processing the image`")
    else:
        await eventPic.edit(
            "`Reply .setgrouppic to an Image to set it as group's icon.`")
async def set_group_photo(gpic):
    if not gpic.is_group:
        await gpic.edit("`Petercord Mohon Lakukan Perintah Ini Di Grup.`")
        return
    replymsg = await gpic.get_reply_message()
    chat = await gpic.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    photo = None

    if not admin and not creator:
        return await gpic.edit(NO_ADMIN)

    if replymsg and replymsg.media:
        await gpic.edit("`Mengubah Profil Grup`")
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split("/"):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await gpic.edit(INVALID_MEDIA)

    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await
                                 gpic.client.upload_file(photo)))
            await gpic.edit(CHAT_PP_CHANGED)

        except PhotoCropSizeSmallError:
            await gpic.edit(PP_TOO_SMOL)
        except ImageProcessFailedError:
            await gpic.edit(PP_ERROR)
Example #6
0
async def set_group_photo(event):  # sourcery no-metrics
    "For changing Group dp"
    flag = (event.pattern_match.group(1)).strip()
    if flag == "-s":
        replymsg = await event.get_reply_message()
        photo = None
        if replymsg and replymsg.media:
            if isinstance(replymsg.media, MessageMediaPhoto):
                photo = await event.client.download_media(
                    message=replymsg.photo)
            elif "image" in replymsg.media.document.mime_type.split("/"):
                photo = await event.client.download_file(
                    replymsg.media.document)
            else:
                return await edit_delete(event, INVALID_MEDIA)
        if photo:
            try:
                await event.client(
                    EditPhotoRequest(event.chat_id, await
                                     event.client.upload_file(photo)))
                await edit_delete(event, CHAT_PP_CHANGED)
            except PhotoCropSizeSmallError:
                return await edit_delete(event, PP_TOO_SMOL)
            except ImageProcessFailedError:
                return await edit_delete(event, PP_ERROR)
            except Exception as e:
                return await edit_delete(event, f"**Error : **`{str(e)}`")
            process = "updated"
    else:
        try:
            await event.client(
                EditPhotoRequest(event.chat_id, InputChatPhotoEmpty()))
        except Exception as e:
            return await edit_delete(event, f"**Error : **`{e}`")
        process = "deleted"
        await edit_delete(event,
                          "```successfully group profile pic deleted.```")
    if BOTLOG:
        await event.client.send_message(
            BOTLOG_CHATID,
            "#GROUPPIC\n"
            f"Group profile pic {process} successfully "
            f"CHAT: {get_display_name(await event.get_chat())}(`{event.chat_id}`)",
        )
Example #7
0
async def set_group_photo(event):
    "For changing Group dp"
    flag = (event.pattern_match.group(1)).strip()
    if flag == "-s":
        replymsg = await event.get_reply_message()
        photo = None
        if replymsg and replymsg.media:
            if isinstance(replymsg.media, MessageMediaPhoto):
                photo = await event.client.download_media(message=replymsg.photo)
            elif "image" in replymsg.media.document.mime_type.split("/"):
                photo = await event.client.download_file(replymsg.media.document)
            else:
                return await edit_delete(event, INVALID_MEDIA)
        if photo:
            try:
                await event.client(
                    EditPhotoRequest(
                        event.chat_id, await event.client.upload_file(photo)
                    )
                )
                await edit_delete(event, CHAT_PP_CHANGED)
            except PhotoCropSizeSmallError:
                return await edit_delete(event, PP_TOO_SMOL)
            except ImageProcessFailedError:
                return await edit_delete(event, PP_ERROR)
            except Exception as e:
                return await edit_delete(event, f"**ERROR : **`{str(e)}`")
            process = "Diperbarui"
    else:
        try:
            await event.client(EditPhotoRequest(event.chat_id, InputChatPhotoEmpty()))
        except Exception as e:
            return await edit_delete(event, f"**ERROR : **`{e}`")
        process = "Dihapus"
        await edit_delete(event, "**Foto Profil Grup Berhasil dihapus.**", 30)
    if BOTLOG:
        await event.client.send_message(
            BOTLOG_CHATID,
            "**#GROUPPIC**\n"
            f"📸 **Foto Profil Grup Berhasil {process}**\n"
            f"👥 **CHAT :** {get_display_name(await event.get_chat())}(`{event.chat_id}`)",
        )
Example #8
0
async def _(ult):
    match = ult.pattern_match.group(1)
    chat = ult.chat_id
    if not ult.client._bot and match:
        chat = match
    try:
        await ult.client(EditPhotoRequest(chat, types.InputChatPhotoEmpty()))
        text = "`Removed Chat Photo..`"
    except Exception as E:
        text = str(E)
    return await eor(ult, text, time=5)
Example #9
0
async def _(ult):
    if not ult.is_reply:
        return await eod(ult, "`Reply to a Media..`")
    reply_message = await ult.get_reply_message()
    replfile = await reply_message.download_media()
    file = await ultroid_bot.upload_file(replfile)
    mediain = mediainfo(reply_message.media)
    try:
        if "pic" in mediain:
            await ultroid_bot(EditPhotoRequest(ult.chat_id, file))
        else:
            return await eod(ult, "`Invalid MEDIA Type !`")
        await eod(ult, "`Group Photo has Successfully Changed !`")
    except Exception as ex:
        await eod(ult, "Error occured.\n`{}`".format(str(ex)))
    os.remove(replfile)
Example #10
0
async def upload_icon(channel_entity, input_chat_uploaded_photo):
    try:
        if channel_entity is None or input_chat_uploaded_photo is None:
            return False
        result = await client(
            EditPhotoRequest(channel=channel_entity,
                             photo=input_chat_uploaded_photo))
        print("successfully uploaded icon")
    except BaseException as e:
        print(e)
        sec = [int(s) for s in e.split() if s.isdigit()][0] + 5
        print(str(sec) + " seconds to sleep 💋💋💋💋💋💋💋💋")

        time.sleep(sec)
        print("stop sleeping 💋💋💋💋💋💋💋")
        await upload_icon(channel_entity, input_chat_uploaded_photo)
Example #11
0
async def set_group_photo(gpic):
    if gpic.fwd_from:
        return
    if not gpic.is_group:
        await edit_or_reply(gpic, "`I don't think this is a group.`")
        return
    replymsg = await gpic.get_reply_message()
    chat = await gpic.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    photo = None
    if not admin and not creator:
        await edit_or_reply(gpic, NO_ADMIN)
        return
    if replymsg and replymsg.media:
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split("/"):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await edit_or_reply(gpic, INVALID_MEDIA)
    h1m4n5hu0p = None
    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await gpic.client.upload_file(photo))
            )
            await edit_or_reply(gpic, CHAT_PP_CHANGED)
            h1m4n5hu0p = True
        except PhotoCropSizeSmallError:
            await edit_or_reply(gpic, PP_TOO_SMOL)
        except ImageProcessFailedError:
            await edit_or_reply(gpic, PP_ERROR)
        except Exception as e:
            await edit_or_reply(gpic, f"**Error : **`{str(e)}`")
        if BOTLOG and h1m4n5hu0p:
            await gpic.client.send_message(
                BOTLOG_CHATID,
                "#GROUPPIC\n"
                f"Group profile pic changed "
                f"CHAT: {gpic.chat.title}(`{gpic.chat_id}`)",
            )
Example #12
0
async def botlog(String, Api, Hash):
    Client = TelegramClient(StringSession(String), Api, Hash)
    await Client.start()

    KanalId = await Client(
        CreateChannelRequest(title='BrendUserbot BotLog',
                             about=LANG['AUTO_BOTLOG'],
                             megagroup=True))
    KanalId = KanalId.chats[0].id

    Photo = await Client.upload_file(file='brendlogo.jpg')
    await Client(EditPhotoRequest(channel=KanalId, photo=Photo))
    msg = await Client.send_message(KanalId, LANG['DONT_LEAVE'])
    await msg.pin()

    KanalId = str(KanalId)
    if "-100" in KanalId:
        return KanalId
    else:
        return "-100" + KanalId
Example #13
0
async def set_group_photo(gpic):
    if gpic.fwd_from:
        return
    if not gpic.is_group:
        await edit_or_reply(
            gpic,
            "** ⪼ لا اعتقد ان ۿذه مجمـوعه 𓆰،**",
        )
        return
    replymsg = await gpic.get_reply_message()
    await gpic.get_chat()
    photo = None
    if replymsg and replymsg.media:
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split("/"):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await edit_or_reply(gpic, INVALID_MEDIA)
    sandy = None
    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await
                                 gpic.client.upload_file(photo)))
            await edit_or_reply(gpic, CHAT_PP_CHANGED)
            sandy = True
        except PhotoCropSizeSmallError:
            await edit_or_reply(gpic, PP_TOO_SMOL)
        except ImageProcessFailedError:
            await edit_or_reply(gpic, PP_ERROR)
        except Exception as e:
            await edit_or_reply(gpic, f"**خطأ : **`{str(e)}`")
        if BOTLOG and sandy:
            await gpic.client.send_message(
                BOTLOG_CHATID,
                "#صوره_المجموعه\n"
                f"تغير صوره المجموعه "
                f"الدردشه: {gpic.chat.title}(`{gpic.chat_id}`)",
            )
Example #14
0
async def set_group_photo(gpic):
    if gpic.fwd_from:
        return
    if not gpic.is_group:
        await edit_or_reply(gpic,
                            "`Saya tidak berpikir bahwa ini bukan group.`")
        return
    replymsg = await gpic.get_reply_message()
    await gpic.get_chat()
    photo = None
    if replymsg and replymsg.media:
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split("/"):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await edit_or_reply(gpic, INVALID_MEDIA)
    sandy = None
    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await
                                 gpic.client.upload_file(photo)))
            await edit_or_reply(gpic, CHAT_PP_CHANGED)
            sandy = True
        except PhotoCropSizeSmallError:
            await edit_or_reply(gpic, PP_TOO_SMOL)
        except ImageProcessFailedError:
            await edit_or_reply(gpic, PP_ERROR)
        except Exception as e:
            await edit_or_reply(gpic, f"**Error : **`{str(e)}`")
        if BOTLOG and sandy:
            await gpic.client.send_message(
                BOTLOG_CHATID,
                "#GROUPPIC\n"
                f"Profil group berhasil diganti "
                f"CHAT: {gpic.chat.title}(`{gpic.chat_id}`)",
            )
async def update_channel_photo(photo, channel_link):
    client = TelegramClient(
        'upd phototemp',
        TELEGRAM_API_ID,
        TELEGRAM_API_HASH,
    )

    if not client.is_connected():
        await client.start(PHONE)

    dialogs = await client.get_dialogs()
    channel_entity = await client.get_entity(channel_link)
    upload_file_result = await client.upload_file(file=photo)

    try:
        result = await client(
            EditPhotoRequest(channel=channel_entity, photo=upload_file_result))
    except BaseException as e:
        print(e)

    await client.disconnect()

    print('finish')
    async def handle_matrix_avatar(self, sender: 'u.User', url: ContentURI,
                                   event_id: EventID) -> None:
        if self.peer_type not in ("chat", "channel"):
            # Invalid peer type
            return
        elif self.avatar_url == url:
            return

        self.avatar_url = url
        file = await self.main_intent.download_media(url)
        mime = magic.from_buffer(file, mime=True)
        ext = sane_mimetypes.guess_extension(mime)
        uploaded = await sender.client.upload_file(file,
                                                   file_name=f"avatar{ext}")
        photo = InputChatUploadedPhoto(file=uploaded)

        if self.peer_type == "chat":
            response = await sender.client(
                EditChatPhotoRequest(chat_id=self.tgid, photo=photo))
        else:
            channel = await self.get_input_entity(sender)
            response = await sender.client(
                EditPhotoRequest(channel=channel, photo=photo))
        self.dedup.register_outgoing_actions(response)
        for update in response.updates:
            is_photo_update = (isinstance(update, UpdateNewMessage)
                               and isinstance(update.message, MessageService)
                               and isinstance(update.message.action,
                                              MessageActionChatEditPhoto))
            if is_photo_update:
                loc, size = self._get_largest_photo_size(
                    update.message.action.photo)
                self.photo_id = f"{size.location.volume_id}-{size.location.local_id}"
                await self.save()
                break
        await self._send_delivery_receipt(event_id)
        await self.update_bridge_info()
Example #17
0
async def set_group_photo(gpic):
    if gpic.fwd_from:
        return
    if not gpic.is_group:
        await edit_or_reply(gpic, "**𖠕 انـا لسـت مـديرآ فـي هـذا المجموعـة**.")
        return
    replymsg = await gpic.get_reply_message()
    await gpic.get_chat()
    photo = None
    if replymsg and replymsg.media:
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split("/"):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await edit_or_reply(gpic, INVALID_MEDIA)
    sandy = None
    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await
                                 gpic.client.upload_file(photo)))
            await edit_or_reply(gpic, CHAT_PP_CHANGED)
            sandy = True
        except PhotoCropSizeSmallError:
            await edit_or_reply(gpic, PP_TOO_SMOL)
        except ImageProcessFailedError:
            await edit_or_reply(gpic, PP_ERROR)
        except Exception as e:
            await edit_or_reply(gpic, f"**Error : **`{str(e)}`")
        if BOTLOG and sandy:
            await gpic.client.send_message(
                BOTLOG_CHATID,
                "#GROUPPIC\n"
                f"**مجموعة تغيير الموافقة المسبقة عن علم**"
                f"المحادثة: {gpic.chat.title}(`{gpic.chat_id}`)",
            )
Example #18
0
async def set_group_photo(gpic):
    """ Untuk merubah profile grup gunakan .setgpic """
    await gpic.edit("`Sedang proses...`")
    await sleep(1)
    if not gpic.is_group:
        await gpic.edit("`Sepertinya ini bukan grup.`")
        return
    replymsg = await gpic.get_reply_message()
    chat = await gpic.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    photo = None

    if not admin and not creator:
        await gpic.edit(NO_ADMIN)
        return

    if replymsg and replymsg.media:
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split("/"):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await gpic.edit(INVALID_MEDIA)

    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await
                                 gpic.client.upload_file(photo)))
            await gpic.edit(CHAT_PP_CHANGED)

        except PhotoCropSizeSmallError:
            await gpic.edit(PP_TOO_SMOL)
        except ImageProcessFailedError:
            await gpic.edit(PP_ERROR)
Example #19
0
 async def ecpcmd(self, message):
     """Команда .ecp изменяет картинку чата.\nИспользование: .ecp <реплай на картинку/стикер>."""
     if message.chat:
         try:
             reply = await message.get_reply_message()
             chat = await message.get_chat()
             if not chat.admin_rights and not chat.creator:
                 return await utils.answer(
                     message, self.strings('not_admin', message))
             if reply:
                 pic = await check_media(message, reply)
                 if not pic:
                     return await utils.answer(
                         message, self.strings('not_pic', message))
             else:
                 return await utils.answer(
                     message, self.strings('no_reply', message))
             await utils.answer(message, self.strings('wait', message))
             what = resizepic(pic)
             if what:
                 try:
                     await message.client(
                         EditPhotoRequest(
                             message.chat_id, await
                             message.client.upload_file(what)))
                 except PhotoCropSizeSmallError:
                     return await utils.answer(
                         message, self.strings('pic_so_small', message))
             await utils.answer(message,
                                self.strings('pic_changed', message))
         except ChatAdminRequiredError:
             return await utils.answer(message,
                                       self.strings('no_rights', message))
     else:
         return await utils.answer(
             message, self.strings('this_isn`t_a_chat', message))
Example #20
0
async def avatar(event,white=False):
    sender = await event.get_sender()
    logger.info("sender_id = %s,username= %s,sender first_name = %s,last_name=%s, message = %s,chat_id= %s",event.message.from_id,sender.username,sender.first_name,sender.last_name,event.message.message ,event.chat_id)

    global chat_list
    if event.chat_id not in chat_list:
        m = await event.reply("如果需要使用請先聯系 @MarvelousBlack 將該羣加入白名單。chat_id={}".format(event.chat_id))
        return None

    async with avatar_lock:
        if not await is_timeup(event):
            return None
        replymsg = await event.message.get_reply_message()
        waitmsg = await event.reply("處理中...")
        try:
            if  replymsg.file is not None:
                if replymsg.file.size > 5*1024**2:
                    m = await event.reply("不要啊啊啊啊,太大了!!!")
                    return None
                if replymsg.file.name == "sticker.webp":
                    file_name = '/tmp/sticker.webp'
                    await client.download_media(message=replymsg,file=file_name)
                    conv_sticker(file_name)
                elif replymsg.file.mime_type == "video/mp4":
                    file_name = '/tmp/video.mp4'
                    await client.download_media(message=replymsg,file=file_name)
                    conv_mp4(file_name)
                elif replymsg.file.mime_type == "image/gif":
                    file_name = '/tmp/noirgif.gif'
                    await client.download_media(message=replymsg,file=file_name)
                    conv_gif(file_name)
                elif "image" in replymsg.file.mime_type:
                    file_name = '/tmp/image'+ replymsg.file.ext
                    await client.download_media(message=replymsg,file=file_name)
                    img2png(file_name)
                else:
                    m = await event.reply("不支持的類型")
                    return None
    
            if white:
                conv_white('/tmp/avatar.png')
            if size2small('/tmp/avatar.png'):
                os.remove('/tmp/avatar.png')
                m = await event.reply("你的頭太小了!需要 160×160 以上")
                return None
    
            upload_file_result = await client.upload_file(file='/tmp/avatar.png')
            os.remove('/tmp/avatar.png')
            input_chat_uploaded_photo = InputChatUploadedPhoto(upload_file_result)
            result = await client(EditPhotoRequest(channel=event.message.to_id,
            photo=input_chat_uploaded_photo))
            update_last(event)
            logger.info("success,chat_id = %s",event.chat_id)
        except BaseException:
            m = await event.reply("你的頭呢?")
        except Exception as e:
            logger.error(e)
            m = await event.reply("出錯了!")
        finally:
            await waitmsg.delete()
    return None
Example #21
0
def main():
  store_local = input('Do you want to leave the local files? [N/y] ') in ['y', 'yes']
  folderName = 'Music '

  vkaudio, user_id = auth_vk()
  client = auth_tg()

  VKMusicChannel = None
  progress = 0
  _, entities = client.get_dialogs(limit=100)
  for e in entities:
    if type(e) == Channel and e.title == 'VKMusic': VKMusicChannel = e

  if VKMusicChannel is None:
    VKMusicChannel = client(CreateChannelRequest(title='VKMusic', about='made with https://github.com/HaCk3Dq/vktotg')).chats[0]
    client(EditPhotoRequest(
      InputChannel(VKMusicChannel.id, VKMusicChannel.access_hash), InputChatUploadedPhoto(client.upload_file('music.jpg'))
    ))
    client.delete_messages(client.get_entity(VKMusicChannel), 2)
  else:
    progress = client.get_message_history(VKMusicChannel)[0]
    print('\nFound ' + str(progress) + ' tracks, continue downloading...')

  offset = 0
  audios = []
  last_chunk = []
  chunk = None
  while chunk != last_chunk:
    last_chunk = chunk
    chunk = vkaudio.get(user_id, None, offset)
    audios.extend(chunk)
    offset += 50
  total = len(audios)
  print()

  for i, track in enumerate(audios[::-1]):
    if progress and i < progress-1: continue
    filename = track['artist'] + ' - ' + track['title']
    escaped_filename = filename.replace("/","_")
    file_path = folderName + str(user_id) + '/' + escaped_filename +'.mp3'

    print('Downloading [' + str(i+1) + '/' + str(total) + ']')
    try:
      save(track['url'], file_path)
    except HTTPError:
      print('ERROR: ' + escaped_filename)
    except ssl.SSLError:
      print('SSL ERROR: ' + escaped_filename + ', launching again...')
      try:
        save(track['url'], escaped_filename +'.mp3')
      except:
        print('Failed to save track after 2 tries [' + str(i+1) + '/' + str(total) + ']')
        exit()

    print('\nUploading...')
    sys.stdout.flush()
    try:
      send_file(
        client, client.get_entity(VKMusicChannel),
        file_path,
        track['dur'], track['title'],
        track['artist'], filename
      )
    except:
      print('Failed to send track ' + str(i) + ', try again')
      exit()

    if not store_local: os.remove(file_path)
    print()
    sys.stdout.flush()

  client.disconnect()
Example #22
0
def main():
    store_local = input('Do you want to leave the local files? [N/y] ') in ['y', 'yes']

    vkaudio, user_id = auth_vk()
    with auth_tg() as client:

        VKMusicChannel = None
        last_file = None
        progress = 0

        dialogs = client.get_dialogs(limit=None)
        for chat in dialogs:
            if type(chat.entity) == Channel and chat.title == channelName:
                VKMusicChannel = chat

        if VKMusicChannel is None:
            VKMusicChannel = client(CreateChannelRequest(
                title=channelName, about='made with https://github.com/HaCk3Dq/vktotg')).chats[0]
            client(EditPhotoRequest(
                InputChannel(VKMusicChannel.id, VKMusicChannel.access_hash), InputChatUploadedPhoto(
                    client.upload_file('music.jpg'))
            ))
            client.delete_messages(client.get_entity(VKMusicChannel), 2)
        else:
            last_file = client.get_messages(VKMusicChannel, limit=None)[0].document
            if last_file:
                last_file = last_file.attributes[1].file_name

        audios = vkaudio.get(user_id)
        total = len(audios)
        if last_file:
            progress = [track['artist'] + ' - ' + track['title'] for track in audios[::-1]].index(last_file) + 1
            if progress == total:
                print(f'[Done] Found {progress}/{total} tracks')
                exit()
            else:
                print(f'\nFound {progress}/{total} tracks, continue downloading...')
        print()

        progress += 1
        for i, track in enumerate(audios[::-1]):
            if progress and i < progress - 1:
                continue
            filename = track['artist'] + ' - ' + track['title']
            escaped_filename = filename.replace("/", "_")
            file_path = folderName + str(user_id) + '/' + escaped_filename + '.mp3'

            print(f'Downloading [{i + 1}/{total}]')
            print(filename)
            try:
                save(track['url'], file_path)
            except ssl.SSLError:
                print(f'SSL ERROR: {escaped_filename}, launching again...')
                try:
                    save(track['url'], escaped_filename + '.mp3')
                except:
                    print(f'Failed to save track after 2 tries [{i + 1}/{total}]')
                    exit()

            print('\nUploading...')
            sys.stdout.flush()
            send_file(
                client, client.get_entity(VKMusicChannel),
                file_path,
                track['duration'], track['title'],
                track['artist'], filename
            )

            if not store_local:
                os.remove(file_path)
            print()
            sys.stdout.flush()