async def _list_messages_async(self, chat, user, output, print_stat=False): channel = await self._client.get_entity(chat) if user is not None: try: user = await self._client.get_entity(user) except ValueError as e: if user.isdecimal(): user = await self._client.get_entity(int(user)) else: raise e if output == 'channel': result = await self._client( CreateChannelRequest( "List Messages", "Messages For {} in {}".format( utils.get_display_name(user), channel.title))) created_channel = result.chats[0] self._logger.info("Channel: {} created.".format( created_channel.title)) await self._iter_messages_async(channel, user, '', created_channel, print_stat) else: self._set_file_handler('list_messages', channel, user) self._logger.debug(channel) self._logger.debug(user) await self._iter_messages_async(channel, user, '', 'log', print_stat) self._logger.info("Listing all messages {}in {}".format( 'for {} '.format(utils.get_display_name(user)) if user else '', channel.title))
async def grabUsername(e): global inGrab await e.edit( "__Il processo di grab è stato avviato! Per stopparlo usa .stopgrab__") inGrab = True createdPrivateChannel = await bot( CreateChannelRequest("BlackList", "BlackList", megagroup=False)) newChannelID = createdPrivateChannel.__dict__["chats"][0].__dict__["id"] newChannelAccessHash = createdPrivateChannel.__dict__["chats"][0].__dict__[ "access_hash"] desiredPublicUsername = e.text.split(" ", 1)[1].replace("@", "") while inGrab: try: checkUsernameResult = await bot( CheckUsernameRequest( InputPeerChannel(channel_id=newChannelID, access_hash=newChannelAccessHash), desiredPublicUsername)) if checkUsernameResult: publicChannel = await bot( UpdateUsernameRequest( InputPeerChannel(channel_id=newChannelID, access_hash=newChannelAccessHash), desiredPublicUsername)) inGrab = False await e.edit("__Grab Riuscito!__") else: await asyncio.sleep(1) except: await asyncio.sleep(1)
async def create_channel(chat_name): client = TelegramClient('allmemes_app', settings.TELEGRAM_API_ID, settings.TELEGRAM_API_HASH, flood_sleep_threshold=20) # await client.start() # return await client.connect() channel = await client( CreateChannelRequest( chat_name, 'Специально созданный чат для вас, сервисом Мой Двор\n' 'По хештегу #жалоба вы можете написать свою претензию, которая будет направлена администрации', broadcast=False, megagroup=True)) goshan_bot = await client.get_input_entity('my_dvorbot') await client(InviteToChannelRequest(channel.chats[0].id, [goshan_bot])) rights = ChatAdminRights(post_messages=True, add_admins=True, invite_users=True, change_info=True, ban_users=True, delete_messages=True, pin_messages=True, edit_messages=True) await client(EditAdminRequest(channel.chats[0].id, goshan_bot, rights)) buff = await client.get_entity(channel.chats[0].id) await client.disconnect() response = requests.get( f'https://api.telegram.org/bot{settings.TELEGRAM_BOT_TOKEN}/exportChatInviteLink?chat_id=-100{buff.id}' ) return { 'chat_id': f'-100{buff.id}', 'invite_link': json.loads(response.text).get('result') }
async def create_new_channel( self, channel_name, channel_desc, public=False, publicName=None, ): createdPrivateChannel = await self.client( CreateChannelRequest(channel_name, channel_desc, megagroup=False)) # if you want to make it public use the rest if public: newChannelID = createdPrivateChannel.__dict__["chats"][0].__dict__[ "id"] newChannelAccessHash = createdPrivateChannel.__dict__["chats"][ 0].__dict__["access_hash"] desiredPublicUsername = publicName checkUsernameResult = await self.client( CheckUsernameRequest( InputPeerChannel(channel_id=newChannelID, access_hash=newChannelAccessHash), desiredPublicUsername)) if (checkUsernameResult == True): try: await self.client( UpdateUsernameRequest( InputPeerChannel(channel_id=newChannelID, access_hash=newChannelAccessHash), desiredPublicUsername)) return 0, "Public channel created successfully!" except errors.rpcerrorlist.UsernameOccupiedError: return 1, "Username is already taken by someone else!" return 99, "Could not make the channel public..." return 0, "Private channel created successfully!"
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
async def _make_asset_channel(self): async with self._anti_double_asset_lock: if not self._assets_already_exists: self._assets_already_exists = True return (await self._client(CreateChannelRequest(f"user-{self._me.id}-assets", "// Don't touch", megagroup=True))).chats[0] else: return await self._find_data_channel()
async def channel_init(prefix, folder): channel_name = prefix + " - " + folder.split( os.sep)[-2] + " - " + folder.split(os.sep)[-1] print("channel name: " + channel_name) createdPrivateChannel = await client( CreateChannelRequest(channel_name, "", megagroup=False)) newChannelID = createdPrivateChannel.__dict__["chats"][0].__dict__["id"] print("new channel ID " + str(newChannelID)) return newChannelID
async def create_telegram_chat(self, source: 'u.User', invites: List[InputUser], supergroup: bool = False) -> None: if not self.mxid: raise ValueError( "Can't create Telegram chat for portal without Matrix room.") elif self.tgid: raise ValueError( "Can't create Telegram chat for portal with existing Telegram chat." ) if len(invites) < 2: if self.bot is not None: info, mxid = await self.bot.get_me() raise ValueError( "Not enough Telegram users to create a chat. " "Invite more Telegram ghost users to the room, such as the " f"relaybot ([{info.first_name}](https://matrix.to/#/{mxid}))." ) raise ValueError("Not enough Telegram users to create a chat. " "Invite more Telegram ghost users to the room.") if self.peer_type == "chat": response = await source.client( CreateChatRequest(title=self.title, users=invites)) entity = response.chats[0] elif self.peer_type == "channel": response = await source.client( CreateChannelRequest(title=self.title, about=self.about or "", megagroup=supergroup)) entity = response.chats[0] await source.client( InviteToChannelRequest(channel=await source.client.get_input_entity(entity), users=invites)) else: raise ValueError("Invalid peer type for Telegram chat creation") self.tgid = entity.id self.tg_receiver = self.tgid self.by_tgid[self.tgid_full] = self await self.update_info(source, entity) self.db_instance.insert() self.log = self.base_log.getChild(self.tgid_log) if self.bot and self.bot.tgid in invites: self.bot.add_chat(self.tgid, self.peer_type) levels = await self.main_intent.get_power_levels(self.mxid) if levels.get_user_level(self.main_intent.mxid) == 100: levels = self._get_base_power_levels(levels, entity) await self.main_intent.set_power_levels(self.mxid, levels) await self.handle_matrix_power_levels(source, levels.users, {}, None) await self.update_bridge_info()
async def _(event): if BOT_MODE: return await eor(event, "`Anda tidak bisa menggunakan perintah ini di BOT_MODE.`") tipe = event.pattern_match.group(1) nama = event.pattern_match.group(2) xx = await eor(event, "`Memprossess...`") if tipe == "g": try: r = await event.client( CreateChatRequest( users=["@missrose_bot"], title=nama, ), ) cht_id = r.chats[0].id await event.client( DeleteChatUserRequest( chat_id=cht_id, user_id="@missrose_bot" ) ) res = await event.client( ExportChatInviteRequest( peer=cht_id ) ) await xx.edit( f"[{nama}]({res.link}) Berhasil dibuat!", link_preview=False ) except Exception as EXcep: await xx.edit(str(EXcep)) elif tipe == "c": try: r = await event.client( CreateChannelRequest( title=nama, about="Join @KingUserbotSupport", megagroup=False ) ) cht_id = r.chats[0].id res = await event.client( ExportChatInviteRequest( peer=cht_id ) ) await xx.edit( f"[{nama}]({res.link}) Berhasil dibuat!", link_preview=False ) except Exception as EXcep: await xx.edit(str(EXcep))
async def _(e): type_of_group = e.pattern_match.group(1) group_name = e.pattern_match.group(2) username = None if " ; " in group_name: group_ = group_name.split(" ; ", maxsplit=1) group_name = group_[0] username = group_[1] xx = await eor(e, "`Processing...`") if type_of_group == "b": try: r = await e.client( CreateChatRequest( users=["@missrose_bot"], title=group_name, ), ) created_chat_id = r.chats[0].id await e.client( DeleteChatUserRequest( chat_id=created_chat_id, user_id="@missrose_bot", ), ) result = await e.client( ExportChatInviteRequest(peer=created_chat_id, ), ) await xx.edit( f"Your [{group_name}]({result.link}) Group Made Boss!", link_preview=False, ) except Exception as ex: await xx.edit(str(ex)) elif type_of_group in ["g", "c"]: try: r = await e.client( CreateChannelRequest( title=group_name, about="Join @TeamUltroid", megagroup=type_of_group != "c", )) created_chat_id = r.chats[0].id if username: await e.client(UpdateUsernameRequest(created_chat_id, username)) result = "https://t.me/" + username else: result = (await e.client( ExportChatInviteRequest(peer=created_chat_id, ), )).link await xx.edit( f"Your [{group_name}]({result}) Group/Channel Has been made Boss!", link_preview=False, ) except Exception as ex: await xx.edit(str(ex))
async def _(e): type_of_group = e.pattern_match.group(1) group_name = e.pattern_match.group(2) username = None if " ; " in group_name: group_ = group_name.split(" ; ", maxsplit=1) group_name = group_[0] username = group_[1] xx = await eor(e, get_string("com_1")) if type_of_group == "b": try: r = await e.client( CreateChatRequest( users=["@missrose_bot"], title=group_name, ), ) created_chat_id = r.chats[0].id await e.client( DeleteChatUserRequest( chat_id=created_chat_id, user_id="@missrose_bot", ), ) result = await e.client( ExportChatInviteRequest(peer=created_chat_id, ), ) await xx.edit( get_string("chats_4").format(group_name, result.link), link_preview=False, ) except Exception as ex: await xx.edit(str(ex)) elif type_of_group in ["g", "c"]: try: r = await e.client( CreateChannelRequest( title=group_name, about=get_string("chats_5"), megagroup=type_of_group != "c", )) created_chat_id = r.chats[0].id if username: await e.client(UpdateUsernameRequest(created_chat_id, username)) result = "https://t.me/" + username else: result = (await e.client( ExportChatInviteRequest(peer=created_chat_id, ), )).link await xx.edit( get_string("chats_6").format(f"[{group_name}]({result})"), link_preview=False, ) except Exception as ex: await xx.edit(str(ex))
async def create_channel_request(phone_number, channel_name): success = True try: client = await get_telegram_client(phone_number) await client(CreateChannelRequest(channel_name, "", megagroup=True)) except: print(f"Failed to create channel:") traceback.print_exc() success = False finally: await client.disconnect() return {"success": success}
async def _(e): if BOT_MODE: return await eor(e, "You Cant use this Command in BOT_MODE") type_of_group = e.pattern_match.group(1) group_name = e.pattern_match.group(2) xx = await eor(e, "`Processing...`") if type_of_group == "b": try: r = await e.client( CreateChatRequest( users=["@missrose_bot"], title=group_name, ), ) created_chat_id = r.chats[0].id await e.client( DeleteChatUserRequest( chat_id=created_chat_id, user_id="@missrose_bot", ), ) result = await e.client( ExportChatInviteRequest( peer=created_chat_id, ), ) await xx.edit( f"Your [{group_name}]({result.link}) Group Made Boss!", link_preview=False, ) except Exception as ex: await xx.edit(str(ex)) elif type_of_group == "g" or type_of_group == "c": try: r = await e.client( CreateChannelRequest( title=group_name, about="CREATED BY INFINATO", megagroup=False if type_of_group == "c" else True, ), ) created_chat_id = r.chats[0].id result = await e.client( ExportChatInviteRequest( peer=created_chat_id, ), ) await xx.edit( f"Your [{group_name}]({result.link}) Group/Channel Has been made Boss!", link_preview=False, ) except Exception as ex: await xx.edit(str(ex))
async def _make_data_channel(self): async with self._anti_double_lock: if self._data_already_exists: return await self._find_data_channel() self._data_already_exists = True return ( await self._client( CreateChannelRequest( f"friendly-{self._me.user_id}-data", "// Don't touch", megagroup=True, ) ) ).chats[0]
async def funcname(e): try: print("versuche Forward!") await e.forward_to("{}loggroup".format(e.from_id)) except: try: await e.client( CreateChannelRequest("{}loggroup".format(e.from_id), "about", megagroup=False)) await e.forward_to("{}loggroup".format(e.from_id)) except: pass
async def init_config_channel(): try: invite = settings.get("config_channel") config_channel = await client.get_entity(invite) if config_channel: return config_channel except: pass print("Config channel not found creating new one") channel = await client(CreateChannelRequest("config_channel", "Message retranslation control room", megagroup=False)) invite = await client(ExportChatInviteRequest(channel.updates[1].channel_id)) config_channel = await client.get_entity(invite.link) settings.set("config_channel", invite.link) settings.save() print("Config channel invite link: ", invite.link) return config_channel
async def autopilot(): LOGS.info("TUNGGU SEBENTAR. SEDANG MEMBUAT GROUP LOG USERBOT UNTUK ANDA") desc = "Group Log untuk Man-UserBot.\n\nHARAP JANGAN KELUAR DARI GROUP INI.\n\n✨ Powered By ~ @Lunatic0de ✨" try: grup = await bot( CreateChannelRequest(title="Log UserBot", about=desc, megagroup=True)) grup_id = grup.chats[0].id except Exception as e: LOGS.error(str(e)) LOGS.warning( "var BOTLOG_CHATID kamu belum di isi. Buatlah grup telegram dan masukan bot @MissRose_bot lalu ketik /id Masukan id grup nya di var BOTLOG_CHATID" ) if not str(grup_id).startswith("-100"): grup_id = int(f"-100{str(grup_id)}") heroku_var["BOTLOG_CHATID"] = grup_id
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
async def _search_mode(self, msg): try: chat = await self._parse_entity(msg.text, 'chat') user = await self._parse_entity(msg.text, 'user') query = self._parse_msg(msg.text, 'query', r'[\w]+') result = await self._client( CreateChannelRequest( "{}{}".format( '{} in '.format(utils.get_display_name(user)) if user else '', chat.title), "query={}".format(query))) created_channel = result.chats[0] self._logger.info("Channel: {} created.".format( created_channel.id)) await self._iter_messages_async(chat, user, query, created_channel) except: traceback.print_exc() finally: await msg.delete()
async def get_dest_channel(client, channel): dialogs = await client.get_dialogs() returnChannel = None for dialog in dialogs: if hasattr(dialog.entity, 'title'): if dialog.entity.title == channel: returnChannel = dialog.entity if returnChannel is None: logging.warn("Channel %s does not exist creating now" % channel) try: returnChannel = await client(CreateChannelRequest(channel, "Scripted channel create %s" % channel, megagroup=False)) returnChannel = returnChannel.chats[0] except Exception as e: logging.error("Failed to create channel %s to send messages to: %s" % (channel, e)) try: await client.send_message(entity=returnChannel, message="%s: Testing %s" % (socket.gethostname(), channel)) except Exception as e: logging.error("Failed to send message to %s: %s" % (channel, e)) return returnChannel
def main(): with TelegramClient('session2', app_id, app_hash) as client: chats_combiners = data['new_channels'] for channel in chats_combiners: channel_name = channel['channel_name'] logging.info('Initializing the channel: {}'.format(channel_name)) try: channel_entity = client.get_entity(channel_name) logging.info('Channel {} exists'.format(channel_name)) except ValueError: client( CreateChannelRequest(channel_name, "about", megagroup=False)) channel_entity = client.get_entity(channel_name) logging.info( 'Channel has been created: {}'.format(channel_name)) channels_to_be_combined = channel['channels_to_be_combined'] for channel_injected in channels_to_be_combined: logging.info( 'Messages from {} are being forwarded to {}'.format( channel_injected, channel_name)) @client.on(events.NewMessage(channel_injected)) async def handler(event): logging.debug('Message from {}: {}'.format( channel_injected, event.message.message)) await client.forward_messages(channel_entity, event.message) client.run_until_disconnected()
async def _search_messages_async(self, chat, query, slow, limit, user, output): _filter = InputMessagesFilterEmpty() peer = await self._client.get_entity(chat) if user is not None: user = await self._client.get_entity(user) self._set_file_handler('search_messages', peer, user, query) if slow: if output == 'channel': result = await self._client(CreateChannelRequest( "Search Messages", "Messages in {}".format(peer.title))) output = result.chats[0] self._logger.info("Channel: {} created.".format(output.title)) await self._iter_messages_async(peer, user, query, output) else: search_request = SearchRequest( peer=peer, q=query, filter=_filter, min_date=None, max_date=None, offset_id=0, add_offset=0, limit=limit, max_id=0, min_id=0, hash=0, from_id=user) result = await self._client(search_request) for msg in result.messages: sender = user if sender is None: sender = await self._client.get_entity(msg.from_id) self._log_message(msg, peer, sender)
async def forward_handler(self, new_forward: NewMessage.Event): try: print(type(new_forward)) await new_forward.reply("👌") forward_from = await self.client.get_entity( new_forward.message.forward.chat.id) print(forward_from) channel = None for auto_channel in self.auto_channels: if auto_channel.origin.id == forward_from.id: channel = auto_channel.channel break invite_link = '' if channel: try: # noinspection PyTypeChecker invite_link = (await self.client(ExportChatInviteRequest(channel) )).link except Exception as e: print(e) if not invite_link: created_private_channel = await self.client( CreateChannelRequest(forward_from.title + '*', '', megagroup=False)) channel_id = created_private_channel.chats[0].id new_channel_access_hash = created_private_channel.chats[ 0].access_hash print(new_channel_access_hash, channel_id) channel = await self.client.get_entity(channel_id) auto_channel = AutoChannel(channel, forward_from, {}) self.auto_channels.append(auto_channel) db_users.update_one({'_id': self.db_id}, { '$push': { 'autoChannels': { 'origin': forward_from.id, 'channel': channel_id, 'messagesMap': [], } } }) # noinspection PyTypeChecker invite_link = (await self.client(ExportChatInviteRequest(channel) )).link print(invite_link) await self.client.send_message( self.me, "**Your channel is created, but it's not ready yet:**\n%s\n\n" "Go [there](%s) and see the magic process. You should be patient until reach the" "most recent post __(to estimate when, see stamped date on the foot of each " "incoming post)__." % (invite_link, invite_link)) # pull history from original chat: reversed_messages = [] # Avoid `FloodWaitError` (70 messages per each 5 minutes MAX!): async for message in self.client.iter_messages(forward_from, limit=600): if type(message) == MessageService: print(message) continue if message.date < new_forward.message.forward.date: break reversed_messages.append(message) # send history for new channel: messages = reversed(reversed_messages) pushed_to_map = [] try: i = 0 for message in messages: i += 1 j = i / 2 while j.is_integer(): print(i) await asyncio.sleep(0.5) j = j / 2 date_time_stamp = '`' + en_to_fa( # Use timestamp-converting to avoid time-zone issues: JalaliDateTime.fromtimestamp( message.date.timestamp()).strftime( '%Y/%m/%d %H:%M')) + '`' sent_message = await self.send_message( date_time_stamp, message, auto_channel.messages_map, channel, forward_from, False) pushed_to_map.append({ 'origin': message.id, 'channel': sent_message.id }) db_users.update_one( { '_id': self.db_id, 'autoChannels': { '$elemMatch': { 'channel': channel.id } } }, { '$push': { 'autoChannels.$.messagesMap': { '$each': pushed_to_map } } }) except FloodWaitError: print(traceback.format_exc(), file=sys.stderr) return # noinspection PyUnboundLocalVariable await self.set_event_handlers(channel, forward_from, auto_channel.messages_map) self.client.remove_event_handler(forward_from) await self.client.send_message( self.me, '**Your channel is ready!** 👇\n' + invite_link) except: print(traceback.format_exc(), file=sys.stderr) try: await self.client.send_message(self.me, 'Unexpected error # 1894') except: print(traceback.format_exc(), file=sys.stderr)
async def _make_data_channel(self): return (await self._client(CreateChannelRequest(f"friendly-{self._me.id}-data", "// Don't touch", megagroup=True))).chats[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()
def create_channel(self, client, title, about): return client(CreateChannelRequest(title=title, about=about))
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()
api_hash, # Use one of the available connection modes. # Normally, this one works with most proxies. connection=connection.ConnectionTcpMTProxyRandomizedIntermediate, # Then, pass the proxy details as a tuple: # (host name, port, proxy secret) # # If the proxy has no secret, the secret must be: # '00000000000000000000000000000000' proxy=('tg-3.rknsosatb.pw', 443, 'dde99993ad3d7146fcf8f3baa789cc62ac')) client.start() def search_channel(): #поиск канала ///SomeCloud/// for dialog in client.iter_dialogs(): allDialog = dialog.name + "\n" #print(allDialog) if re.search("///SomeCloud///", allDialog): HaveChannel = True if HaveChannel: print("Канал уже создан") else: print("Надо создать канал") createdPrivateChannel = client( CreateChannelRequest("///SomeCloud///", "FileCloud", megagroup=False)) print("Канал успешно создан")
from telethon.tl.functions.channels import CreateChannelRequest, CheckUsernameRequest, UpdateUsernameRequest from telethon.tl.types import InputChannel, InputPeerChannel createdPrivateChannel = client(CreateChannelRequest("title","about",megagroup=False)) #if you want to make it public use the rest newChannelID = createdPrivateChannel.__dict__["chats"][0].__dict__["id"] newChannelAccessHash = createdPrivateChannel.__dict__["chats"][0].__dict__["access_hash"] desiredPublicUsername = "******" checkUsernameResult = client(CheckUsernameRequest(InputPeerChannel(channel_id=newChannelID, access_hash=newChannelAccessHash), desiredPublicUsername)) if(checkUsernameResult==True): publicChannel = client(UpdateUsernameRequest(InputPeerChannel(channel_id=newChannelID, access_hash=newChannelAccessHash), desiredPublicUsername))