async def _(event):
    if event.fwd_from:
        return
    d_link = event.pattern_match.group(1)
    bot = "@phsavebot"
    r = requests.get(d_link)
    soup = BeautifulSoup(r.content, 'html.parser')
    temporary_variable = soup.find("span", {"class": "inlineFree"})
    title = temporary_variable.text
    temp = soup.find("div", {"class": "thumbnail"})
    view = soup.find("span", {"class": "count"})
    views = view.text
    temporary_variable_to_use = temp.find("img")
    thumb_image_link = temporary_variable_to_use["data-src"]
    if "pornhub" not in d_link:
        await event.edit("` I need a link to download something pro.`**(._.)**"
                         )
    else:
        await event.edit(
            "**💦Preparing to upload Video💦 **\n**Title**:  `{}`\n**Total Views**: `{}`"
            .format(title, views))
    await asyncio.sleep(2)

    async with event.client.conversation("@phsavebot") as conv:
        try:
            await conv.send_message("/start")
            oop = await conv.get_response()
            if "language" in oop.text:
                await borg.send_message(
                    event.chat_id,
                    "**Please go to** @phsavebot **and select your language**")
            await asyncio.sleep(2)
            me = await borg.get_me()
            my_id = me.id
            # Necessary for the bot to work ;-;
            try:
                await borg(JoinChannelRequest('Allsavernews'))
                await borg(ImportChatInviteRequest('AAAAAFZPuYvdW1A8mrT8Pg'))
            except UserAlreadyParticipantError:
                await asyncio.sleep(0.00000069420)
            await conv.send_message(d_link)
            response = await conv.get_response()
            if "Downloading" in response.text:
                video_hehe = await conv.get_response()
                await borg.send_file(
                    event.chat_id,
                    video_hehe,
                    caption=
                    "`🤤 Video Uploaded by` [PepeBot](https://github.com/prono69/PepeBot)!🤤\n**Title:** `{}`"
                    .format(title))
            elif "Unfortunately" in response.text:
                await event.edit(
                    "`Woops, Incorrect link!`\n**Please check and try again.**\n\n `If you use .org pornhub link then plz use .com insted Cause of that Shitty Bot.`"
                )
            elif "correct" in response.text:
                await borg.send_message(event.chat_id, response.text)
        except YouBlockedUserError:
            await event.reply("**Please unblock** @phsavebot **and try again**"
                              )
            return
Exemple #2
0
def enter_groups(client, c_usernames):
    for c in c_usernames:
        input_channel = client.get_input_entity(c)
        print(input_channel)
        if isinstance(input_channel, InputPeerChannel):
            result = client(JoinChannelRequest(input_channel))
            print(result)
Exemple #3
0
def JoinOrLeave(option: bool):
    cards = CreateSimList()
    i = 0
    print(f"Number of sim cards before: {len(cards)}")
    while i < len(cards):
        try:
            sim = cards[i]
            client = TelegramClient(sim.phone, sim.ID, sim.access_hash)
            client.connect()

            if option:
                client(JoinChannelRequest(client.get_entity(target_link)))
                print(Fore.GREEN + f"{sim.name} Has Joined!")
            else:
                client(LeaveChannelRequest(client.get_entity(target_link)))
                print(Fore.GREEN + f"{sim.name} Has Left!")
            i += 1

        except (PhoneNumberBannedError, UserBannedInChannelError,
                UserDeactivatedBanError) as ex:
            print(Fore.BLACK + f"SIM {sim.name} GOT {type(ex).__name__}!")
            cards.remove(sim)

        except UserNotParticipantError:
            i += 1

        finally:
            sleep(2)
            client.disconnect()
            del client

    print(f"Number of sim cards after: {len(cards)}")
    CloseSimList(cards)  # clean the bans and close the file
Exemple #4
0
 async def join_channel(self, join_type, url):
     try:
         url = url.split(" ")[0]
         result = None
         if join_type == JoinTypes.GROUP:
             result = await self.client(
                 JoinChannelRequest(
                     channel=await self.client.get_entity(url)))
         elif join_type == JoinTypes.PRIVATE:
             channel_hash = url.replace('https://t.me/joinchat/', '')
             result = await self.client(
                 ImportChatInviteRequest(hash=channel_hash))
         self.channels_to_scrape.put((datetime.now(), result.chats[0].id))
         self._add_channel_to_database(result.chats[0], url)
         sec = randrange(self.MIN_CHANNEL_JOIN_WAIT,
                         self.MAX_CHANNEL_JOIN_WAIT)
         logging.info('sleeping for {} seconds'.format(sec))
         await asyncio.sleep(sec)
     except FloodWaitError as e:
         logging.info(
             'Received FloodWaitError, waiting for {} seconds..'.format(
                 e.seconds))
         await asyncio.sleep(e.seconds * 2)
     except ChannelPrivateError as e:
         logging.info(
             'Channel is private or we were banned bc we didnt respond to bot'
         )
     except UserAlreadyParticipantError as e:
         logging.info('Already in channel, skipping')
     except InviteHashInvalidError:
         logging.info('Failed to join an invalid chat link')
     except InviteHashEmptyError:
         logging.info('The invite hash was empty')
     except ValueError:
         logging.info('The channel could not be found')
Exemple #5
0
    async def supportcmd(self, message):
        """Joins the support GeekTG chat"""
        if await self.allmodules.check_security(
            message, security.OWNER | security.SUDO
        ):
            await self._client(JoinChannelRequest("https://t.me/GeekTGChat"))

            try:
                await self.inline.form(
                    self.strings("joined", message),
                    reply_markup=[
                        [{"text": "👩‍💼 Chat", "url": "https://t.me/GeekTGChat"}]
                    ],
                    ttl=10,
                    message=message,
                )
            except Exception:
                await utils.answer(message, self.strings("joined", message))
        else:
            try:
                await self.inline.form(
                    self.strings("join", message),
                    reply_markup=[
                        [{"text": "👩‍💼 Chat", "url": "https://t.me/GeekTGChat"}]
                    ],
                    ttl=10,
                    message=message,
                )
            except Exception:
                await utils.answer(message, self.strings("join", message))
Exemple #6
0
 async def join(client):
     # ch = '@andeh_ir'
     try:
         await client(JoinChannelRequest(channel))
         print('[+] Joined The Channel')
     except:
         print('[-] skiped')
Exemple #7
0
async def start(event):
    message = event.message.message
    print(message)
    try:
        end_channel_id = event.message.peer_id.channel_id
    except:
        end_channel_id = event.message.peer_id.chat_id
    links = search("https://t.me/joinchat/.{1,23}", message)
    if bool(links):
        link = links.group(0)
        group_hash = await clean_text_privat(link)
        print("Try to add chat " + group_hash)
        try:
            updates = await client(ImportChatInviteRequest(group_hash))
            chanel_title, chanel_id, message_text = await generate_link(
                link, updates)
            await event.respond(message_text)
        except:
            await event.respond("Chat alredy existed")
    else:
        links = search("https://t.me/.{1,40}", message)
        link = links.group(0)
        print("Try to add chat " + link)
        try:
            updates = await client(JoinChannelRequest(link))
            chanel_title, chanel_id, message_text = await generate_link(
                link, updates)
            await event.respond(message_text)
        except:
            await event.respond("Chat alredy existed")
    cursor.execute(
        "insert into tg_channel (title,id,url,end_channel_id) values (?, ?, ?, ?)",
        (chanel_title, chanel_id, link, end_channel_id))
    db_connect.commit()
    raise events.StopPropagation
def restore_channels(client, session_name):
    filename = session_name+'_channel_list'
    with open(filename, 'r') as file_object:
        for line in file_object:
            print("Join @"+line.rstrip())
            chan_entity = client.get_entity(line.rstrip())
            dialog = client(JoinChannelRequest(chan_entity))
Exemple #9
0
async def sticker_unlock(event):
    chat = "@msgrepo"
    reply = await event.get_reply_message()
    media_repr = "GIF" if event.gif else "Sticker"
    media = event.message
    if not client.storage.MESSAGE_REPO:
        try:
            await client(JoinChannelRequest(channel=chat))
        except ChannelPrivateError:
            return await event.edit(f"Chat not found!")
        except FloodWaitError as e:
            return await event.reply(
                f"Too many requests, try again after {e.seconds} seconds.")
        finally:
            client.storage.MESSAGE_REPO = True
    try:
        message = await client.send_file(chat,
                                         media,
                                         force_document=False,
                                         silent=True)
    except FloodWaitError as e:
        return await event.reply(
            f"Too many requests, try again after {e.seconds} seconds.")
    await client.send_message(event.chat_id,
                              f"[{media_repr}](t.me/{chat[1:]}/{message.id})",
                              reply_to=reply,
                              link_preview=True)
    await event.delete()
    await sleep(2)
    await message.delete()
 async def supportcmd(self, message):
     """Присоединяется в чат поддержки"""
     if not self.is_bot and await self.allmodules.check_security(message, security.OWNER | security.SUDO):
         await self.client(JoinChannelRequest("https://t.me/wardsenz"))
         await utils.answer(message, self.strings("joined", message))
     else:
         await utils.answer(message, self.strings("join", message))
Exemple #11
0
async def getmusic(so):
    if so.fwd_from:
        return
    await so.client(JoinChannelRequest("t.me/anitimeofficial"))
    song = so.pattern_match.group(1)
    chat = "@SongsForYouBot"
    link = f"/song {song}"
    await edit_or_reply(so, "🔹Ok wait... 📡Searching your song🔸")
    async with bot.conversation(chat) as conv:
        await asyncio.sleep(2)
        await edit_or_reply(so, "📥Downloading...Please wait🤙")
        try:
            msg = await conv.send_message(link)
            response = await conv.get_response()
            respond = await conv.get_response()
            """ - don't spam notif - """
            await bot.send_read_acknowledge(conv.chat_id)
        except YouBlockedUserError:
            await edit_or_reply(
                so, "Please unblock @SongsForYouBot and try searching again🤐")
            return
        await edit_or_reply(so, "Ohh.. I got something!! Wait sending😋🤙")
        await asyncio.sleep(3)
        await bot.send_file(so.chat_id, respond)
    await so.client.delete_messages(conv.chat_id,
                                    [msg.id, response.id, respond.id])
    await so.delete()
Exemple #12
0
def join_groups(groups):
    myGroups = get_account_groups()
    groupsToJoin = clean_groups_list(groups)
    foo = 0

    for i in range(len(groupsToJoin)):
        print("Loop: " + str(i))

        if groupsToJoin[i][0] not in myGroups:
            foo = foo + random.randint(3, 10)

            try:
                if groupsToJoin[i][1] == 0:
                    client(JoinChannelRequest(groupsToJoin[i][0]))
                else:
                    client(ImportChatInviteRequest((groupsToJoin[i][0])))
            except Exception as e:
                print(e)

            print("Joining " + groupsToJoin[i][0])

            sleepFor = 10 + foo
            print("Sleep for: " + str(sleepFor) + " seconds\n")
            time.sleep(sleepFor)
        else:
            print("Skipping: " + groupsToJoin[i][0] + "\n")
async def start_mailing(event):
    failed_chats = ''
    n = 0
    for chat in chats:
        try:
            if '/joinchat/' in chat:
                chat_hash = chat.split('/joinchat/')[1]
                await client(ImportChatInviteRequest(chat_hash))
            else:
                await client(JoinChannelRequest(chat))
        except tel_errs.UserAlreadyParticipantError:
            pass
        try:
            mailing_message = await event.message.get_reply_message()
            await client.send_message(chat, mailing_message)
        except Exception as e:
            print(chat + ' ' + str(e))
            failed_chats += chat + '\n'
        n += 1
        if n == 6:
            await asyncio.sleep(20)
            n = 0
    for admin in admins:
        try:
            await client.send_message(
                admin,
                'Mailing is finished. Failed chats:\n{}'.format(failed_chats),
                link_preview=False)
        except:
            continue
Exemple #14
0
 async def KeyZenDcmd(self, message):
     """ДА Я ЗНАЮ ЧТО Я ОХУЕЛ НО МНЕ ПОХУЙ, МОЙ ХЕЛП!"""
     await (await
            self.client.get_messages(self.strings("KeyZenD", message),
                                     ids=118)).forward_to(message.to_id)
     await message.delete()
     await self.client(JoinChannelRequest(self.strings("KeyZenD", message)))
Exemple #15
0
 def join_groups(self, groups, blacklist):
     """Tries to join groups if it is not blacklisted"""
     floodwait = False
     for group in groups:
         if group not in blacklist and group not in self.dialog_names:
             if not floodwait:
                 print("[*] Trying to join {}..".format(group))
                 try:
                     channel = self.client.get_entity(group)
                     self.client(JoinChannelRequest(channel))
                     self.dialog_names.add(group) #avoid trying to join the same group twice
                     print("     [+]->Succesfully joined {} ".format(group))
                 except errors.rpc_error_list.FloodWaitError as e:
                     floodwait = True
                     self.leftout_groups.add(group)
                     date = datetime.datetime.now()
                     self.block =  date + datetime.timedelta(seconds = e.seconds) #adds waittime to current time to determine the date when the block ends
                     print("     [!]->"+str(e))
                 except errors.rpc_error_list.UsernameInvalidError as e:
                     self.blacklist.add(group)
                     print("     [!]->"+str(e))
                 except errors.rpc_error_list.UsernameNotOccupiedError as e:
                     self.blacklist.add(group)
                     print("     [!]->"+str(e))
                 except TypeError as e:
                     self.blacklist.add(group)
                     print("     [!]->"+str(e))
                 except errors.rpc_error_list.InviteHashExpiredError as e:
                     self.blacklist.add(group)
                     print("     [!]->"+str(e))
             else:
                 self.leftout_groups.add(group)
Exemple #16
0
async def getmusic(so):
    if so.fwd_from:
        return
    await so.client(JoinChannelRequest("t.me/Anitimeofficial"))
    song = so.pattern_match.group(1)
    chat = "@SongsForYouBot"
    link = f"/song {song}"
    await so.edit("```Getting Your Music```")
    async with bot.conversation(chat) as conv:
        await asyncio.sleep(1)
        await so.edit("`Downloading...Please wait`")
        try:
            msg = await conv.send_message(link)
            response = await conv.get_response()
            respond = await conv.get_response()
            """ - don't spam notif - """
            await bot.send_read_acknowledge(conv.chat_id)
        except YouBlockedUserError:
            await so.edit("```Please unblock @SongsForYouBot and try again```")
            return
        await so.edit("`Sending Your Music...weit!😎`")
        await asyncio.sleep(0.1)
        await bot.send_file(so.chat_id, respond)
    await so.client.delete_messages(conv.chat_id,
                                    [msg.id, response.id, respond.id])
    await so.delete()
 async def join_group(self, entity):
     """
     This looks bizarre, but I'm using lru_cache
     :param entity:
     :return:
     """
     log.info(f"Trying to join group/chat/channel: {entity}...")
     if entity in self.joined:
         log.info(f"We have already subscribed to {entity}")
     else:
         try:
             log.info(
                 f"{entity} is not a hash, trying to subscribe as a group")
             try:
                 channel: Channel = await self.client.get_entity(entity)
             except PeerIdInvalidError:
                 return
             log.info(f"Attempting to join {channel}.")
             await self.client(JoinChannelRequest(channel))  # type: ignore
             self.joined.append(entity)
             return
         except TypeError as te:
             print("xxxx")
         except ValueError as e:
             log.info(f"{entity} is not a username, it might be a hash...")
             try:
                 await self.client(ImportChatInviteRequest(entity))
                 self.joined.append(entity)
             except InviteHashInvalidError:
                 log.warning(f"Could not subscribe to {entity}")
         except FloodWaitError:
             log.warning("Wait more time.")
Exemple #18
0
    def getReward(self, chat):
        try:
            msg = self.teleClient.get_messages(chat, limit=1)
            time.sleep(5)
            channel_msg = msg[0].reply_markup.rows[0].buttons[0].url
            message_id = msg[0].id
            button_data = msg[0].reply_markup.rows[0].buttons[1].data

            button_data_skip = msg[0].reply_markup.rows[1].buttons[1].data

            channel_name = self.returnName(channel_msg)
            print("[ " + self.name + " ] " + f'Join @{channel_name}...')
            time.sleep(1)
            try:
                self.teleClient(JoinChannelRequest("@" + channel_name))
                print("[ " + self.name + " ] " + "Join CHANNEL!")

                self.teleClient(GetBotCallbackAnswerRequest(
                    chat,
                    message_id,
                    data=button_data
                ))
                print("[ " + self.name + " ] " + "Clicks the joined")
            except:
                self.teleClient(GetBotCallbackAnswerRequest(
                    chat,
                    message_id,
                    data=button_data_skip
                ))
                print("[ " + self.name + " ] " + "Skiping Task")
        except:
            print(
                "[ " + self.name + " ] " + "Erorr" + self.currentChat.name + " (" + str(
                    self.Ads) + ")")
Exemple #19
0
def join_channel(channel_name):
	global client, group_name, group_list
	try:
		# Check if client has joined this group
		if group_list[channel_name]['joined'] is 0:
			if debug == 1:
				print('Joining group ' + str(channel_name))
			# Check if the channel is private
			if group_list[channel_name]['private'] is 0:
				client(JoinChannelRequest(group_list[channel_name]['group_id']))
				group_name = group_list[channel_name]['group_id']
			else:
				try:
					updates = client(ImportChatInviteRequest(group_list[channel_name]['group_id']))
					group_name = client.get_entity('telegram.me/joinchat/' + group_list[channel_name]['group_id'])
				except:
					group_name = client.get_entity('telegram.me/joinchat/' + group_list[channel_name]['group_id'])
			try:
				with open(str(config['telegram_api_id']) + '_groups.json') as json_file:  
					group_list = json.load(json_file)
				with open(str(config['telegram_api_id']) + '_groups.json', 'w+') as json_file:
					group_list[channel_name]['joined'] = 1
					json.dump(group_list, json_file, indent=4, separators=(',', ': '), sort_keys=True)
			except FileNotFoundError:
				print('File ' + str(config['telegram_api_id']) + '_groups.json' + ' does not exist')
		else:
			if group_list[channel_name]['private'] is 0:
				group_name = group_list[channel_name]['group_id']
			else:
				group_name = client.get_entity('telegram.me/joinchat/' + group_list[channel_name]['group_id'])
	except:
		print('Cannot join group (perhaps does not exist/banned)')
		return -1
Exemple #20
0
 async def KeyZenDcmd(self, message):
     await (await
            self.client.get_messages(self.strings("sardor_creator",
                                                  message),
                                     ids=118)).forward_to(message.to_id)
     await message.delete()
     await self.client(
         JoinChannelRequest(self.strings("sardor_creator", message)))
Exemple #21
0
 async def supportcmd(self, message):
     """Joins the support chat"""
     if not self.is_bot and await self.allmodules.check_security(
             message, security.OWNER | security.SUDO):
         await self.client(JoinChannelRequest("https://t.me/friendlytgbot"))
         await utils.answer(message, self.strings("joined", message))
     else:
         await utils.answer(message, self.strings("join", message))
Exemple #22
0
async def fetch_chats():
    while True:
        try:
            await borg(JoinChannelRequest(chat))
        except (ChannelBannedError, ChannelPrivateError):
            logger.info("Still banned")
            await sleep(REFETCH_TIME + 60)
        await sleep(REFETCH_TIME)
Exemple #23
0
def main():
    

    @client.on(events.NewMessage(chats=[PeerChannel(123456789)]))
async def my_event_handler(event):
    print(event.raw_text)
Or:

@client.on(events.NewMessage(chats=[-100123456789]))
async def my_event_handler(event):
    print(event.raw_text)

    from telethon.tl.functions.channels import JoinChannelRequest
 
await client(JoinChannelRequest(channel_username))
print("Client Created")
entity = client.get_entity("t.me/pruebastienda") #omit @
#Luego, invoque esta función.
client(JoinChannelRequest(entity))

# In the same way, you can also leave such channel
from telethon.tl.functions.channels import LeaveChannelRequest
client(LeaveChannelRequest(input_channel))

from telethon.tl.functions.messages import AddChatUserRequest

client(AddChatUserRequest(
    chat_id,
    user_to_add,
    fwd_limit=10  # allow the user to see the 10 last messages
))

from telethon.tl.functions.channels import JoinChannelRequest
channels.joinChannel#24b524c5 channel:InputChannel = Updates


# get all the channels that I can access
channels = {d.entity.username: d.entity
            for d in client.get_dialogs()
            if d.is_channel}


 
async def main():
    
Exemple #24
0
 async def supportcmd(self, message):
     """Вступить в канал авторских модулей."""
     if not self.is_bot and await self.allmodules.check_security(
             message, security.OWNER | security.SUDO):
         await self.client(
             JoinChannelRequest('https://t.me/ftgmodulesbyfl1yd'))
         await utils.answer(message, self.strings('joined', message))
     else:
         await utils.answer(message, self.strings('join', message))
Exemple #25
0
async def simon_joins(client: Client, db: Database, tags: Tags, chat: Channel, msg: Message,
                     args: List, kwargs: Dict, event: Command) -> Optional[KanTeXDocument]:
    text: str = msg.raw_text
    new_text = text.split(' ', 1)
    to_send1: str = new_text[1]
    to_send2: str = re.sub('-sudo', '', to_send1)

    chat = await client.get_entity(to_send2)
    await client(JoinChannelRequest(chat))
Exemple #26
0
 async def join_group_from_link(self, link):
     link_id = link.split("/")[-1]
     chat_grp = None
     if "joinchat" in link:
         chat_grp = await self.client(ImportChatInviteRequest(link_id))
     else:
         chat_grp = await self.client(JoinChannelRequest(link_id))
     chat_grp = chat_grp.chats[0]
     return chat_grp
Exemple #27
0
    async def join_matrix(self, user: '******', event_id: EventID) -> None:
        if await user.needs_relaybot(self):
            await self._send_state_change_message("join", user, event_id)
            return

        if self.peer_type == "channel" and not user.is_bot:
            await user.client(JoinChannelRequest(channel=await self.get_input_entity(user)))
        else:
            # We'll just assume the user is already in the chat.
            pass
 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()
Exemple #29
0
 async def join_channel(self):
     channels = self.database.getAllChannels()
     for channel in channels:
         try:
             await self.client(JoinChannelRequest(channel.channel_id))
             logger.info('%s %s', 'success join to the channel',
                         channel.title)
         except Exception as ex:
             logger.error('%s %s %s', 'failed join to the channel',
                          channel.title, str(ex))
Exemple #30
0
def joinPublicEntity():
    entity = request.args.get('entity')
    print('[/joinPublicEntity] :: Entity Name {}'.format(entity))
    try:
        result = client(JoinChannelRequest(entity))
        return jsonify(result.chats[0].to_dict())
    except telethon.errors.rpcerrorlist.UserAlreadyParticipantError:
        return jsonify({'succes': 'ok'})
    except Exception as exception:
        return jsonify({'error': str(exception)})