def start(config): client = TelegramClient(config["session_name"], config["api_id"], config["api_hash"]) client.start() input_channels_entities = [] output_channel_entity = None for d in client.iter_dialogs(): if d.name in config["input_channel_names"]: input_channels_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) if d.name == config["output_channel_name"]: output_channel_entity = InputChannel(d.entity.id, d.entity.access_hash) if output_channel_entity is None: logger.error( f"Could not find the channel \"{config['output_channel_name']}\" in the user's dialogs" ) sys.exit(1) logging.info( f"Listening on {len(input_channels_entities)} channels. Forwarding messages to {config['output_channel_name']}." ) @client.on(events.NewMessage(chats=input_channels_entities)) async def handler(event): await client.forward_messages(output_channel_entity, event.message) logging.info(f"Event message: {event.message.message}.") with open('A:1.txt', 'w', encoding="utf-8") as filehandle: filehandle.write(event.message.message) filehandle.close() client.run_until_disconnected()
def start(config): client = TelegramClient(config["session_name"], config["api_id"], config["api_hash"], proxy=None #proxy=(socks.HTTP, '127.0.0.1', 1087) ) client.start() input_channels_entities = [] output_channel_entity = None for d in client.iter_dialogs(): if d.name in config["input_channel_names"]: input_channels_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) if d.name == config["output_channel_name"]: output_channel_entity = InputChannel(d.entity.id, d.entity.access_hash) if output_channel_entity is None: logger.error( f"Could not find the channel \"{config['output_channel_name']}\" in the user's dialogs" ) sys.exit(1) logging.info( f"Listening on {len(input_channels_entities)} channels. Forwarding messages to {config['output_channel_name']}." ) @client.on( events.NewMessage(chats=input_channels_entities, pattern=r'([\s\S]*)#福建([\s\S]*)')) async def handler(event): await client.forward_messages(output_channel_entity, event.message) client.run_until_disconnected()
def start(config): client = TelegramClient(config["session_name"], config["api_id"], config["api_hash"]) client.start() input_channels_entities = [] output_channel_entities = [] for d in client.iter_dialogs(): if d.name in config["input_channel_names"]: input_channels_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) if d.name in config["output_channel_names"]: output_channel_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) if not output_channel_entities: logger.error( f"Could not find any output channels in the user's dialogs") sys.exit(1) if not input_channels_entities: logger.error( f"Could not find any input channels in the user's dialogs") sys.exit(1) logging.info( f"Listening on {len(input_channels_entities)} channels. Forwarding messages to {len(output_channel_entities)} channels." ) @client.on(events.NewMessage(chats=input_channels_entities)) async def handler(event): for output_channel in output_channel_entities: await client.forward_messages(output_channel, event.message) client.run_until_disconnected()
def start(config): pytesseract.pytesseract.tesseract_cmd = config['tesseract_path'] client = TelegramClient(config["session_name"], config["api_id"], config["api_hash"]) client.start() input_channels_entities = [] output_channel_entity = None for d in client.iter_dialogs(): if d.name in config["input_channel_names"]: input_channels_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) if d.name == config["output_channel_name"]: output_channel_entity = InputChannel(d.entity.id, d.entity.access_hash) if output_channel_entity is None: logger.error( f"Could not find the channel \"{config['output_channel_name']}\" in the user's dialogs" ) sys.exit(1) logging.info( f"Listening on {len(input_channels_entities)} channels. Forwarding messages to {config['output_channel_name']}." ) @client.on(events.NewMessage(chats=input_channels_entities)) async def handler(event): message_text = None text_in_image = None if event.message.media is not None: if is_image(event.message.media): await client.download_media(event.message.media, config["temp_path"] + 'temp.jpg') time.sleep(2) # Get HOCR output hocr = pytesseract.image_to_pdf_or_hocr(config["temp_path"] + 'temp.jpg', extension='hocr') soup = BeautifulSoup(hocr.decode('utf-8'), 'html.parser') elements = soup.find_all("span", class_="ocrx_word") text = '' for elm in elements: text += elm.text text_in_image = re.findall(r'[A-Z]{3}\s*/\s*[A-Z]{3}', text) if len(text_in_image) > 0: text_in_image = "Symbol: " + text_in_image[0].replace( '/', '').replace(" ", "") message_from_sender = parese_message(event.message.message) if message_from_sender is not None and text_in_image is not None: message_text = text_in_image + "\n" + message_from_sender elif text_in_image is None: message_text = message_from_sender elif message_from_sender is None: message_text = text_in_image await client.send_message(output_channel_entity, message_text) client.run_until_disconnected()
def invite_to_channel(self): """ This definition adding contact to group, do not use it without def_channel() and def_usernames(). You can invite to channel from 1 session max 15 people after that you are at risk. You can be banned because too many requests from 1 session. """ if self.flag_channel and self.flag_user: for i in range(len(self.usernames)): try: if self.usernames[i][0]: sleep(31) self.client( InviteToChannelRequest( InputChannel(self.channel.id, self.channel.access_hash), [ InputUser(self.usernames[i][0].id, self.usernames[i][0].access_hash) ])) print('Successfully added ' + str(self.usernames[i][0]) + ' to ' + str(self.channel)) print('Успешно добавлен ' + str(self.usernames[i][0]) + ' в ' + str(self.channel)) print('------------------------') sleep(5) except Exception as err: print(err) print('------------------------') else: print( 'You don\'t define channel and users to add, please try again' 'Вы не определили канал и/или ползователей')
async def post_login(self) -> None: await self.init_permissions() info = await self.client.get_me() self.tgid = TelegramID(info.id) self.username = info.username self.mxid = pu.Puppet.get_mxid_from_id(self.tgid) chat_ids = [ chat_id for chat_id, chat_type in self.chats.items() if chat_type == "chat" ] response = await self.client(GetChatsRequest(chat_ids)) for chat in response.chats: if isinstance(chat, ChatForbidden) or chat.left or chat.deactivated: self.remove_chat(TelegramID(chat.id)) channel_ids = (InputChannel(chat_id, 0) for chat_id, chat_type in self.chats.items() if chat_type == "channel") for channel_id in channel_ids: try: await self.client(GetChannelsRequest([channel_id])) except (ChannelPrivateError, ChannelInvalidError): self.remove_chat(TelegramID(channel_id.channel_id))
def get_chat_messages(self, channel_name, all=False): """ Функция для получения всех сообщений из чата. :param channel_name: имя чата (например durov) :param all: количество сообщений. Если False - получает последние 5к сообщений :return: объекты сообщений """ chat_object = self.get_chat_info(channel_name) input_channel = InputChannel(chat_object['chat_id'], chat_object['access_hash']) channel = self.client.invoke(GetFullChannelRequest(input_channel)).__dict__ chat_peer = InputPeerChannel(channel['full_chat'].id, chat_object['access_hash']) all_messages = [] offset = 0 new_messages = self.client.invoke(GetHistoryRequest(chat_peer, 0, None, offset, LIMIT, 0, 0, )).messages if all: while len(new_messages) is not 0 and offset < MESSAGES_LIMIT: offset += 100 for new_message in new_messages: all_messages.append(new_message.__dict__) new_messages = self.client.invoke(GetHistoryRequest(chat_peer, 0, None, offset, LIMIT, 0, 0)).messages time.sleep(1) else: for new_message in new_messages: all_messages.append(new_message.__dict__) return all_messages
async def get_call( self, chat_id: int, ) -> Optional[InputGroupCall]: chat = await self._app.get_input_entity(chat_id) if isinstance(chat, InputPeerChannel): input_call = (await self._app( GetFullChannelRequest( InputChannel( chat.channel_id, chat.access_hash, ), ), )).full_chat.call else: input_call = (await self._app( GetFullChatRequest(chat_id), )).full_chat.call if input_call is not None: try: call: GroupCall = (await self._app( GetGroupCallRequest( call=input_call, limit=-1, ), )).call if call.schedule_date is not None: return None except Exception as e: print(e) return input_call
async def post_login(self) -> None: await self.init_permissions() info = await self.client.get_me() self.tgid = info.id self.username = info.username self.mxid = pu.Puppet.get_mxid_from_id(self.tgid) chat_ids = [chat_id for chat_id, chat_type in self.chats.items() if chat_type == "chat"] response = await self.client(GetChatsRequest(chat_ids)) for chat in response.chats: if isinstance(chat, ChatForbidden) or chat.left or chat.deactivated: self.remove_chat(chat.id) channel_ids = [InputChannel(chat_id, 0) for chat_id, chat_type in self.chats.items() if chat_type == "channel"] for channel_id in channel_ids: try: await self.client(GetChannelsRequest([channel_id])) except (ChannelPrivateError, ChannelInvalidError): self.remove_chat(channel_id.channel_id) if config["bridge.catch_up"]: try: await self.client.catch_up() except Exception: self.log.exception("Failed to run catch_up() for bot")
def get_participants_ids(channel: Channel, raw_users: bool = False) -> list: channel = InputChannel(channel.id, channel.access_hash) result = client( GetParticipantsRequest(channel, ChannelParticipantsSearch(''), 0, 10000, 5)) if not raw_users: ids = [user.id for user in result.users if not user.bot] return ids else: return result.users
async def run(self): await self.tg_client.connect() await self.tg_client.start() for ch_id in self.config["telegram"]["channels"]: result = await self.tg_client(ResolveUsernameRequest(ch_id)) channel = InputChannel(result.peer.channel_id, result.chats[0].access_hash) await self.tg_client(JoinChannelRequest(channel)) self.tg_client.add_event_handler(self._tg_event_handler) logging.info("Bot has been started") await self.tg_client.run_until_disconnected()
def from_group_ten_first_persons(group, togroup): flag = True if group == '-': flag = False return flag elif togroup == '-': flag = False return flag users = client.get_participants(group) channel = client.get_entity(togroup) for i in range(10): try: contact = InputPhoneContact(client_id=user[i].id, phone=user[i].phone, first_name=user[i].first_name, last_name=user[i].last_name) result = client.invoke(ImportContactsRequest([contact])) client( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(users[i].id, users[i].access_hash)])) except errors.rpcerrorlist.UserPrivacyRestrictedError as err: print('>>>>0. UserPrivacyRestrictedError...') print(err) except errors.rpcerrorlist.ChatAdminRequiredError as err: print('>>>>1. ChatAdminRequiredError...') print(err) except errors.rpcerrorlist.ChatIdInvalidError as err: print('>>>>2. ChatIdInvalidError...') print(err) except errors.rpcerrorlist.InputUserDeactivatedError as err: print('>>>>3. InputUserDeactivatedError...') print(err) except errors.rpcerrorlist.PeerIdInvalidError as err: print('>>>>4. PeerIdInvalidError...') print(err) except errors.rpcerrorlist.UserAlreadyParticipantError as err: print('>>>>5. UserAlreadyParticipantError...') print(err) except errors.rpcerrorlist.UserIdInvalidError as err: print('>>>>6. UserIdInvalidError...') print(err) except errors.rpcerrorlist.UserNotMutualContactError as err: print('>>>>>7. UserNotMutualContactError...') print(err) except errors.rpcerrorlist.UsersTooMuchError as err: print('>>>>>8. UsersTooMuchError...') print(err) except errors.rpcerrorlist.PeerFloodError as err: print( '>>>>>9. PeerFloodError try again in 24 Hours...Yes, you in spam' ) print(err) return flag
def get_users(group_username): users_list = [] channel = client(ResolveUsernameRequest(group_username)) offset_counter = 0 while True: users = client(GetParticipantsRequest(InputChannel(channel.peer.channel_id, channel.chats[0].access_hash), limit=200, offset=offset_counter, filter=ChannelParticipantsRecent())) if len(users.participants) == 0: break offset_counter += 200 users_list.extend(users.users) time.sleep(5) return users_list
def __load_output_chats(self): dialogs = self.telegram.get_dialogs() for username in self.output_chat_usernames: dialog = next( filter(lambda e: e.entity.username == username, dialogs), None) if dialog: self.output_chats.append( InputChannel(dialog.entity.id, dialog.entity.access_hash)) else: raise RuntimeError(f"Output chat '{username}' was not found")
def start(config): client = TelegramClient(config["session_name"], config["api_id"], config["api_hash"]) client.start() input_channels_entities = [] output_channel_entity = None for d in client.iter_dialogs(): if d.id in config["input_channel_ids"]: input_channels_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) if d.id == config["output_channel_id"]: output_channel_entity = InputChannel(d.entity.id, d.entity.access_hash) if d.id == config["test_channel_id"]: test_channel_entity = InputChannel(d.entity.id, d.entity.access_hash) if output_channel_entity is None: logger.error( f"Could not find the channel \"{config['output_channel_id']}\" in the user's dialogs" ) sys.exit(1) logging.info( f"Listening on {len(input_channels_entities)} channels. Forwarding messages to {config['output_channel_name']}." ) @client.on(events.NewMessage(chats=input_channels_entities)) async def handler(event): chat = await event.get_chat() if chat.id == 1365813396: logging.info("Sending new message to Monitor Test") await client.send_message(test_channel_entity, event.message) else: logging.info("Sending new message to Monitor") await client.send_message(output_channel_entity, event.message) client.run_until_disconnected()
def join_to_channel(bot, list_ids=tlg_chats): success_rate = 0 for id in list_ids: try: i = InputChannel(bot.get_entity(id).id, bot.get_entity(id).access_hash) bot.invoke(JoinChannelRequest(i)) success_rate += 1 print("присоединился к {}".format(id)) time.sleep(5) except: print('не могу присоединиться к {}'.format(id)) list_ids.remove(id) return success_rate/len(list_ids), list_ids
def get_telegram_usernames(write_results=True): print('Fetching telegram followers... This may take a few minutes') api_id = config['TELEGRAM']['ID'] # Your api_id api_hash = config['TELEGRAM']['HASH'] # Your api_hash phone_number = config['TELEGRAM']['PHONE'] # Your phone number client = TelegramClient(phone_number, api_id, api_hash) client.session.report_errors = False client.connect() # will need to enter code from message if session is not active if not client.is_user_authorized(): client.send_code_request(phone_number) client.sign_in(phone_number, input('Enter the code: ')) channel = client(ResolveUsernameRequest( config['TELEGRAM']['CHANNEL'])) # Your channel input_channel = InputChannel(channel.chats[0].id, channel.chats[0].access_hash) offset = 0 limit = 100 all_participants = [] # Can pull up to 10000 participants in one shot. Will need to filter if you have more users than that. while True: participants = client( GetParticipantsRequest(input_channel, ChannelParticipantsSearch(''), offset, limit, 0)) if not participants.users: break all_participants.extend(participants.users) offset += len(participants.users) print(offset) telegram_usernames = [] for participant in all_participants: if participant.username: telegram_usernames.append(participant.username.lower()) # telegram_usernames = [_user.username.lower() for _user in all_participants] if write_results: telegram_file = open('telegram_usernames.csv', 'w') telegram_writer = csv.writer(telegram_file, quoting=csv.QUOTE_ALL) for username in telegram_usernames: telegram_writer.writerow([username]) return telegram_usernames
async def get_channel_entity(project_url: str) -> dict: cache = getEntityByURL(cache_db, project_url) #check if targetchannel is in db if cache: entity = InputChannel(cache['channel_id'], cache['access_hash']) client_alias = cache['client_alias'] returnDict = { 'channel_id': cache['channel_id'], 'title': cache['title'], 'username': cache['username'] } print("using cache") if not cache: returned_entity = await telegram.client.get_entity(project_url) client_alias = telegram.active_client_alias entityDict = { 'client_alias': client_alias, 'type': 'channel', 'project_url': project_url, 'channel_id': returned_entity.id, 'access_hash': returned_entity.access_hash, 'username': returned_entity.username, 'scam': returned_entity.scam, 'megagroup': returned_entity.megagroup, 'verified': returned_entity.verified, 'title': returned_entity.title } returnDict = entityDict insertEntity(cache_db, entityDict) entity = InputChannel(returned_entity.id, returned_entity.access_hash) print("using RPC") return { 'channel': entity, 'client_alias': client_alias, 'details': returnDict }
def getId(client, chatName, limit, debug=False): #Checking for not existing try: resolve = client(ResolveUsernameRequest(chatName)) except UsernameInvalidError: print("Incorrect name of chat! Try again.") return False except UsernameNotOccupiedError: print("Incorrect name of chat! Try again.") return False #Checking for chat or no try: access_hash = resolve.chats[0].access_hash chat_id = resolve.chats[0].id except IndexError: print("It's not a chat!") return False input_channel = InputChannel(chat_id, access_hash) filter = ChannelParticipantsSearch('') offset = 0 hash = 0 allId = [] #Checking for channel/private chat try: client( GetParticipantsRequest(input_channel, filter, offset, limit, hash)) except ChatAdminRequiredError: print('It is channel/private chat!') return False count = 0 while True: if count == limit: break part = client( GetParticipantsRequest(input_channel, filter, offset, limit, hash), ) if not part.users: break allId.append(part.users[count].id) count += 1 offset += 1 print('{}/{}'.format(count, limit), end='\r') if debug: print(part.users[count].id) return allId
async def get_call( self, chat_id: int, ) -> Optional[InputGroupCall]: chat = await self._app.get_input_entity(chat_id) if isinstance(chat, InputPeerChannel): return (await self._app( GetFullChannelRequest( InputChannel( chat.channel_id, chat.access_hash, ), ), )).full_chat.call else: return (await self._app(GetFullChatRequest(chat_id), )).full_chat.call
def add_users_2_channel_fun(user_group_id: int, tag_id: int): print('start add users 2 channel.') try: global id_add_users_2_channel user_group = db.session.query(UserGroup).filter( UserGroup.group_id == user_group_id).scalar() if user_group is None: print('user group is none.') else: inputChannel = InputChannel(channel_id=user_group.group_id, access_hash=user_group.access_hash) user_tag_infos = db.session.query(UserTAGInfo).filter( UserGroup.tag_id == tag_id).all() if user_tag_infos is None: print("user tag infos is none.") else: inputUsers = [] all_count = len(user_tag_infos) count = 1 for user_tag_info in user_tag_infos: inputUser = InputUser(user_id=int(user_tag_info.user_id), access_hash=int( user_tag_info.user_hash)) try: user_1( InviteToChannelRequest(inputChannel, [inputUser])) except: print("invite to channel error.userId=" + str(user_tag_info.user_id) + ";userHash=" + str(user_tag_info.user_hash)) # inputUsers.append(inputUser) # if count % 100 == 0 or all_count == count: # print('add users 2 channel.') # try: # client(InviteToChannelRequest(inputChannel, inputUsers)) # except: # print("invite to channel error." + str(user_tag_info.user_id)) # inputUsers.clear() # count += 1 # print('all_count=' + str(all_count) + ';count=' + str(count)) id_add_users_2_channel = False print('add users 2 channel finish.') except: id_add_users_2_channel = False print('add users 2 channel get error.')
def count_members(id, access_hash): offset = 0 limit = 10000 all_participants = [] while True: participants = client( GetParticipantsRequest(InputChannel(id, access_hash), ChannelParticipantsSearch(''), offset, limit, hash=0)) if not participants.users: break all_participants.extend(participants.users) offset += len(participants.users) return len(all_participants)
async def main(): await client.connect() if not await client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) channel = await client.get_entity( 'https://t.me/qwertyuiop1234567890' ) #channel_ id https://t.me/bloXrouteLabsCommunity users_in_channel = await client.get_participants( 'https://t.me/qwertyuiop1234567890') #channel id or https://t.me/ncent print(users_in_channel) def is_in_group(username): if username in users_in_channel: return True else: return False with open('im.txt', 'r') as f: # file with list of usernames for line in f: print(line) tmp = line[1:].replace('\n', '') print(tmp) try: user = client.get_input_entity( tmp) # (ResolveUsernameRequest(tmp)) print(user) except UsernameInvalidError as err: print(err) continue if user: try: sleep(301) client.invoke( InviteToChannelRequest( InputChannel(channel.id, channel.access_hash), [InputUser(user.user_id, user.access_hash)])) except UserNotMutualContactError as err: print(err) except UserIdInvalidError as err: print(err) else: continue await client.disconnect()
def get_saving_group(): # user = client.get_entity("@Jude12") # print(user) # channel = client.get_entity("@mktesttttttttttt") # print(channel) # channel_id = channel.id # channel_hash = channel.access_hash # user_id = user.id # user_hash = user.access_hash channel_id = 1247985828 channel_hash = -8866180916535177199 user_id = 490342664 user_hash = -7707849152056625292 inputChannel = InputChannel(channel_id=channel_id, access_hash=channel_hash) print(inputChannel) inputUser = InputUser(user_id=user_id, access_hash=user_hash) print(inputUser) test = user_1(InviteToChannelRequest(inputChannel, [inputUser])) print(test) return "saving group is:" + saving_group
def inviteToChannel(client, channel, id_list): #Checking for not existing try: resolve = client(ResolveUsernameRequest(channel)) except UsernameInvalidError: print("Incorrect name of channel! Try again.") return False except UsernameNotOccupiedError: print("Incorrect name of channel! Try again.") return False chat_id = resolve.chats[0].id access_hash = resolve.chats[0].access_hash input_channel = InputChannel(chat_id, access_hash) for id in id_list: input_user = InputUser(id, 0) InviteToChannelRequest(input_channel, input_user) return True
def dump_users(chat, client): counter = 0 offset = 0 chat_object = InputChannel(chat['chat_id'], chat['access_hash']) all_participants = [] print('Process...') while True: participants = client.invoke( GetParticipantsRequest(chat_object, ChannelParticipantsSearch(''), offset, limit)) if not participants.users: break all_participants.extend( ['{} {}'.format(x.id, x.username) for x in participants.users]) users_count = len(participants.users) offset += users_count counter += users_count print('{} users collected'.format(counter)) sleep(2) with open('users.txt', 'w') as file: file.write('\n'.join(map(str, all_participants)))
def add_users(client, file_name): dialogs, entities = client.get_dialogs(100) avail_channels = {} channel = None channel_id = None channel_access_hash = None for i, entity in enumerate(entities): if not isinstance(entity, User) and not isinstance(entity, Chat): avail_channels[str(i)] = [ entity, entity.id, entity.access_hash, entity.title ] for k, v in avail_channels.items(): print(k, v[3]) channel_index = input( "Please select number of supergroup where you want to add users> ") #participants = client.invoke(GetParticipantsRequest(avail_channels[channel_index][0], ChannelParticipantsSearch(''), 0, 0)) #count_of_members_before_adding = len(participants.users) users = None try: with open(file_name, 'r') as f: users = json.load(f) except Exception: print( 'Invalid file name, make sure you have added extension or if file even exists, if not, run scrape_channel_users.py to create one!' ) sys.exit() count = int( input('Do you want to add only subset of users(' + str(len(users)) + ')? if so, enter the number of users to be added: ')) users_to_save_back = users[ count:] # only users, which didnt be used, will be saved to file again print( str(len(users_to_save_back)) + ' users to be saved back to json file!') users = users[:count] # users to be added print(str(len(users)) + ' users to be removed from list!') print() with open(file_name, 'w') as f: json.dump(users_to_save_back, f, indent=4) input_users = [] for item in users: input_users.append(InputUser(item['id'], item['access_hash'])) user_chunks = list(chunks(input_users, 40)) for item in user_chunks: try: client( InviteToChannelRequest( InputChannel(avail_channels[channel_index][1], avail_channels[channel_index][2]), item)) print('Adding chunk of ' + str(len(item)) + ' users...') time.sleep(2) except Exception as e: print(str(e)) print('some error occurred, skipping to next chunk.') time.sleep(2) print('There was attempt to add ' + str(len(input_users)) + ' users in total.') #participants = client.invoke(GetParticipantsRequest(avail_channels[channel_index][0], ChannelParticipantsSearch(''), 0, 0)) #count_of_members_after_adding = len(participants.users) #print('Count of members before adding: ' + str(count_of_members_before_adding)) #print('Count of members after adding: ' + str(count_of_members_after_adding)) print() #print('True number of added users: ' + str(count_of_members_after_adding - count_of_members_before_adding)) print('added')
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()
def start(config): # Get information from config file: session_name = config["session_name"] api_id = config["api_id"] api_hash = config["api_hash"] trigger_words = config["trigger_words"] quit_key_words = config["quit_key_words"] # Initialisations: input_channels_entities = [] output_channel_entity = None connectivity = () # Acquire entities: with TelegramClient(session_name, api_id, api_hash) as client: for d in client.iter_dialogs(): if d.name in config["input_channel_names"]: if (config["mode"] in ['1', '2', '3']): input_channels_entities.append( InputChannel(d.entity.id, d.entity.access_hash)) else: input_channels_entities.append(InputPeerChat(d.entity.id)) if d.name == config["output_channel_name"]: if (config["mode"] in ['1', '4']): output_channel_entity = InputChannel( d.entity.id, d.entity.access_hash) elif (config["mode"] in ['2', '5']): output_channel_entity = InputPeerChat(d.entity.id) else: output_channel_entity = InputPeerUser( d.entity.id, d.entity.access_hash) # Do a check on entities acquired: if output_channel_entity is None: connectivity = connectivity + (0, ) print("Requested output channel entity could not be found") else: connectivity = connectivity + (1, ) if len(input_channels_entities) == 0: connectivity = connectivity + (0, ) print("Requested input channel entity(s) cannot be found") else: connectivity = connectivity + (1, ) if 0 in connectivity: print("Shutting down due to entity-check failure...") sys.exit(1) else: print("Entity-check successful!") print( "Listening on %d channels. Forwarding messages to %s." % (len(input_channels_entities), config['output_channel_name'])) # Create events to listen to: # For more recipes, visit https://arabic-telethon.readthedocs.io/en/stable/ @client.on(events.NewMessage(chats=input_channels_entities)) async def forwarding_handler(event): client = event.client # if trigger_words in event.raw_text.lower(): if any(word in event.raw_text.lower() for word in trigger_words): # await event.reply('hi!') # extra await client.forward_messages(output_channel_entity, event.message) @client.on( events.NewMessage(chats=output_channel_entity, outgoing=True)) async def control_handler(event): # if quit_key_words in event.raw_text.lower(): if any(word in event.raw_text.lower() for word in quit_key_words): await client.disconnect() client.run_until_disconnected()
def start(source, config): # setup the Telegram client telegram_client = setup_telegram(config) #setup discord client discord_client = setup_discord(config) #setup telegram output channels telegram_output_channel_entities = [] for d in telegram_client.iter_dialogs(): if 'Channel' == type(d.entity).__name__ and d.name in config["output_channel_names"]: telegram_output_channel_entities.append(InputChannel(d.entity.id, d.entity.access_hash)) if not telegram_output_channel_entities: logger.error(f"Could not find any Telegram output channels in the user's dialogs") sys.exit(1) logging.info(f"Forwarding messages to {len(telegram_output_channel_entities)} Telegram channels.") discord_subscribed_channels = [] #setup guilds (servers) and channels @discord_client.event async def on_ready(): print('We have logged in as {0.user}'.format(discord_client)) for guild in discord_client.guilds: if guild.name == config["discord_input_guild_name"]: print("Starting Discord forwarder on server '"+guild.name+"'") print("Forwarding the following channels:") for channel in guild.channels: if channel.name in config["discord_channel_names"]: print(channel) discord_subscribed_channels.append(channel) # Wait for messages and reply (debug) or forward to telegram @discord_client.event async def on_message(message): if message.author == discord_client.user: return if message.content.startswith('$hello'): if message.channel in discord_subscribed_channels: await message.channel.send('Hello!') else: if message.channel in discord_subscribed_channels: for output_channel in telegram_output_channel_entities: if len(message.attachments) == 1: for attachment in message.attachments: await telegram_client.send_file(output_channel, attachment.url, caption=message.content) elif len(message.attachments) > 1: if message.content.length > 0: await telegram_client.send_message(output_channel, message.content) for attachment in message.attachments: await telegram_client.send_file(output_channel, attachment.url) else: await telegram_client.send_message(output_channel, message.content) if source == 'telegram': listen_telegram(telegram_client, config) else if source == 'discord' listen_discord(discord_client, config) else: raise Error('SourceArgumentMissing')