Ejemplo n.º 1
0
def add_member(chat, nickname):
    #Add users to channel, group, or megagroup
    global added_users
    global failed_users
    try:
        target_group_entity = client.get_entity(chat.id)
    except:
        sleep(10)
        target_group_entity = chat.title
    try:
        sleep(10)
        client(AddChatUserRequest(target_group_entity, nickname, 10))
    except Exception as e:
        try:
            sleep(10)
            client(InviteToChannelRequest(target_group_entity, [nickname]))
            added_users += 1
        except Exception as e:
            try:
                try:
                    sleep(10)
                    target_group_entity = chat.migrated_to
                except:
                    try:
                        sleep(10)
                        target_group_entity = InputPeerChannel(chat.id, chat.access_hash)
                    except:
                        pass
                sleep(10)
                client(InviteToChannelRequest(target_group_entity, [nickname]))
                added_users += 1
            except Exception as e:
                print(" \n-----\nusername: {}\n{}\n-----\n ".format(nickname, e))
                failed_users += 1
Ejemplo n.º 2
0
def custommembers(request):
    org_gid = request.POST.get('originalid')
    myfile = request.FILES['userlist']
    fs = FileSystemStorage()
    filename = fs.save("userlistfile.csv", myfile)
    fname = os.path.join(settings.MEDIA_ROOT, "userlistfile.csv")
    userlist = open(fname, 'r+', encoding="utf-8", errors='ignore')
    readCSV = list(csv.reader(userlist, delimiter=','))
    del readCSV[0]
    count = 0
    olist = []
    message = ""
    i = 0
    for row in readCSV:
        userid = int(row[0])
        if row[4] == "not invited":
            i = i + 1
            if org_gid.isnumeric():
                try:
                    client(InviteToChannelRequest(int(org_gid), [userid]))
                    row[4] = "invited"
                    olist.append([row[0], row[1], row[2], row[3], row[4]])
                    count = count + 1
                except Exception as e:
                    row[4] = "not invited due to error with user" + str(e)
                    olist.append([row[0], row[1], row[2], row[3], row[4]])
                    y = str(e)
                    print(y)
                    if y.lower() == "too many requests":
                        message = "your account has exceeded limit so has to wait for 24 hrs to use this account again"
                        break
                    pass
            else:
                try:
                    client(InviteToChannelRequest(org_gid, [userid]))
                    row[4] = "invited"
                    olist.append([row[0], row[1], row[2], row[3], row[4]])
                    count = count + 1
                except Exception as e:
                    row[4] = "not invited due to error with user" + str(e)
                    olist.append([row[0], row[1], row[2], row[3], row[4]])
                    y = str(e)
                    print(y)
                    if y.lower() == "too many requests":
                        message = "your account has exceeded limit so has to wait for 24 hrs to use this account again"
                        break
                    pass
            if count >= 50 or i >= 65:
                message = "you have added 50 members from this account and if you continue using this account further your account will be banned so best option is to use another signout an login through another account and continue the process"
                break
        else:
            continue
    context = {"olist": olist, "message": message}
    userlist.close()
    return render(request, "displaymembers.html", context)
Ejemplo n.º 3
0
def index(request):
    context = {}
    channels = {
        d.entity.username: d.entity
        for d in client.get_dialogs() if d.is_channel
    }
    group1 = 'entrepreneurialjourney'
    group2 = 'joinexample3'
    context['group1'] = 'MillionNetworkMedia'
    context['group2'] = 'fordemoonly'

    #channel='entrepreneurialjourney'
    #channel2= 'joinexample3'
    participants = client.get_participants(group1)
    count = 1
    act = input("press 1 to add all, 2 to add one by one, 3 to cancel: ")
    if str(act) == "1":
        print("Adding all members")
    if str(act) == "1" or str(act) == "2":
        for u in participants:
            print(count)
            print(u.first_name)
            u_id = u.id
            last_seen = client.get_entity(u_id)
            time.sleep(1)
            print(str(last_seen))
            print()
            time.sleep(1)
            if str(act) == str(2):
                acte = input("press 1 to add, 2 to skip: ")
                if str(acte) == str(1):
                    client(InviteToChannelRequest(group2, [u_id]))
                    print("Privacy Issue")
            if str(act) == str(1):

                client(InviteToChannelRequest(group2, [u_id]))

                print("Privacy Issue")
            time.sleep(1)
            if count == 20:
                break
            count = count + 1

    if request.method == "POST":
        group1 = request.POST.get('group1')
        group2 = request.POST.get('group2')

    return render(request, 'index.html', context)
Ejemplo n.º 4
0
def add_user_by_id(client, user_id, channel_id=DEFAULT_CHANNEL):
    try:

        # client.invoke(InviteToChannelRequest(get_input_peer(channel), [get_input_peer(user)]))

        # client.invoke(InviteToChannelRequest(
        #     # InputChannel(get_input_peer(user.chats[0]).channel_id, get_input_peer(user.chats[0]).access_hash),
        #     InputChannel(channel.id, channel.access_hash),
        #     [InputUser(get_input_peer(user.users[0]).user_id, get_input_peer(user.users[0]).access_hash)]
        # ))
        # client.invoke(InviteToChannelRequest(InputChannel(channel.id, channel.access_hash), [InputUser(get_input_peer(user.users[0]).user_id, get_input_peer(user.users[0]).access_hash)]))
        # client.invoke(InviteToChannelRequest(client.get_entity(PeerChannel(1188959006)), [user]))
        # client.invoke(InviteToChannelRequest(client.get_input_entity(PeerChannel(channel_id)), [client.get_input_entity(PeerUser(user_id=user.users[0].id))]))

        user_entity = client.get_input_entity(PeerUser(user_id))
        channel_entity = client.get_entity(PeerChannel(channel_id=int(channel_id)))
        client.invoke(InviteToChannelRequest(channel_entity, [user_entity]))

        log.warning("Added User: {} to Channel: {}".format(user_id, channel_id))
        return "User added successfully"
    except Exception as err:
        reason = err.args[1] if len(err.args) > 1 else err.message
        msg = "Add User {} attempt to channel ({}) failed [{}]".format(user_id, channel_id, reason)
        log.error(msg)
        log.error(err)
    return msg
Ejemplo n.º 5
0
async def get_users(event):
    man_ = event.text[11:]
    chat_man = man_.lower()
    restricted = ["@SharingUserbot", "@sharinguserbot"]
    man = await edit_or_reply(event,
                              f"**Mengundang Member Dari Group {man_}**")
    if chat_man in restricted:
        await man.edit("**Anda tidak dapat Mengundang Anggota dari sana.**")
        await bot.send_message(-1001473548283,
                               "**Maaf Telah Mencuri Member dari Sini.**")
        return
    manuserbot = await get_chatinfo(event)
    chat = await event.get_chat()
    if event.is_private:
        return await man.edit(
            "**Tidak bisa Menambahkan Member di sini Harap ketik di Grup Chat**"
        )
    s = 0
    f = 0
    error = "None"

    await man.edit("**Terminal Status**\n\n`Sedang Mengumpulkan Pengguna...`")
    async for user in bot.iter_participants(manuserbot.full_chat.id):
        try:
            await bot(InviteToChannelRequest(channel=chat, users=[user.id]))
            s = s + 1
            await man.edit(
                f"**Terminal Running**\n\n• **Menambahkan** `{s}` **orang** \n• **Gagal Menambahkan** `{f}` **orang**\n\n**× LastError:** `{error}`"
            )
        except Exception as e:
            error = str(e)
            f = f + 1
    return await man.edit(
        f"**Terminal Finished** \n\n• **Berhasil Menambahkan** `{s}` **orang** \n• **Gagal Menambahkan** `{f}` **orang**"
    )
Ejemplo n.º 6
0
async def _(ult):
    xx = await ult.eor(get_string("com_1"))
    to_add_users = ult.pattern_match.group(1).strip()
    if not ult.is_channel and ult.is_group:
        for user_id in to_add_users.split(" "):
            try:
                await ult.client(
                    AddChatUserRequest(
                        chat_id=ult.chat_id,
                        user_id=await ult.client.parse_id(user_id),
                        fwd_limit=1000000,
                    ),
                )
                await xx.edit(f"Successfully invited `{user_id}` to `{ult.chat_id}`")
            except Exception as e:
                await xx.edit(str(e))
    else:
        for user_id in to_add_users.split(" "):
            try:
                await ult.client(
                    InviteToChannelRequest(
                        channel=ult.chat_id,
                        users=[await ult.client.parse_id(user_id)],
                    ),
                )
                await xx.edit(f"Successfully invited `{user_id}` to `{ult.chat_id}`")
            except UserBotError:
                await xx.edit(
                    f"Bots can only be added as Admins in Channel.\nBetter Use `{HNDLR}promote {user_id}`"
                )
            except Exception as e:
                await xx.edit(str(e))
Ejemplo n.º 7
0
async def ekle(event):
    if event.fwd_from:
        return
    to_add_users = event.pattern_match.group(1)
    if event.is_private:
        await event.edit(LANG['EKLE_PRIVATE'])
    else:
        if not event.is_channel and event.is_group:
            for user_id in to_add_users.split(" "):
                await event.edit(f'`{user_id} qrupa əlavə edilir...`')
                try:
                    await event.client(
                        AddChatUserRequest(chat_id=event.chat_id,
                                           user_id=user_id,
                                           fwd_limit=1000000))
                except Exception as e:
                    await event.edit(f'`{user_id} qrupa əlavə edə bilmədim!`')
                    continue
                await event.edit(f'`{user_id} qrupa əlavə elədim!`')
        else:
            for user_id in to_add_users.split(" "):
                await event.edit(f'`{user_id} qrupa əlavə olunur...`')
                try:
                    await event.client(
                        InviteToChannelRequest(channel=event.chat_id,
                                               users=[user_id]))
                except Exception as e:
                    await event.edit(f'`{user_id} qrupa əlavə oluna bilmədi!`')
                    continue
                await event.edit(f'`{user_id} qrupa əlavə olundu!`')
Ejemplo n.º 8
0
    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'
                'Вы не определили канал и/или ползователей')
Ejemplo n.º 9
0
async def admem(event):
    x = await eor(event, "`Adding 0 members...`")
    chat = await event.get_chat()
    client = event.client
    users = []
    with open("members.csv", encoding="UTF-8") as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {'id': int(row[0]), 'hash': int(row[1])}
            users.append(user)
    n = 0
    for user in users:
        n += 1
        if n % 30 == 0:
            await eor(x, f"`Reached 30 members, sleeping for {900/60} minutes`")
            await asyncio.sleep(900)
        try:
            userin = InputPeerUser(user['id'], user['hash'])
            await client(InviteToChannelRequest(chat, [userin]))
            await asyncio.sleep(random.randrange(5, 7))
            await eor(x, f"`Adding {n} members...`")
        except TypeError:
            n -= 1
            continue
        except UserAlreadyParticipantError:
            n -= 1
            continue
        except UserPrivacyRestrictedError:
            n -= 1
            continue
        except UserNotMutualContactError:
            n -= 1
            continue
Ejemplo n.º 10
0
async def ekle(event):
    if event.fwd_from:
        return
    to_add_users = event.pattern_match.group(1)
    if event.is_private:
        await event.edit(
            "`Ekle komutu kullanıcıları sohbete ekler, özel mesaja değil!`")
    else:
        if not event.is_channel and event.is_group:
            # https://lonamiwebs.github.io/Telethon/methods/messages/add_chat_user.html
            for user_id in to_add_users.split(" "):
                try:
                    await event.client(
                        AddChatUserRequest(chat_id=event.chat_id,
                                           user_id=user_id,
                                           fwd_limit=1000000))
                except Exception as e:
                    await event.reply(str(e))
            await event.edit("`Başarıyla eklendi`")
        else:
            # https://lonamiwebs.github.io/Telethon/methods/channels/invite_to_channel.html
            for user_id in to_add_users.split(" "):
                try:
                    await event.client(
                        InviteToChannelRequest(channel=event.chat_id,
                                               users=[user_id]))
                except Exception as e:
                    await event.reply(str(e))
            await event.edit("`Başarıyla eklendi`")
Ejemplo n.º 11
0
async def admem(event):
    xx = await edit_or_reply(event, "**Proses Menambahkan** `0` **Member**")
    chat = await event.get_chat()
    users = []
    with open("members.csv", encoding="UTF-8") as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {"id": int(row[0]), "hash": int(row[1])}
            users.append(user)
    n = 0
    for user in users:
        n += 1
        if n % 30 == 0:
            await xx.edit(
                f"**Sudah Mencapai 30 anggota, Tunggu Selama** `{900/60}` **menit**"
            )
            await asyncio.sleep(900)
        try:
            userin = InputPeerUser(user["id"], user["hash"])
            await event.client(InviteToChannelRequest(chat, [userin]))
            await asyncio.sleep(random.randrange(5, 7))
            await xx.edit(f"**Proses Menambahkan** `{n}` **Member**")
        except TypeError:
            n -= 1
            continue
        except UserAlreadyParticipantError:
            n -= 1
            continue
        except UserPrivacyRestrictedError:
            n -= 1
            continue
        except UserNotMutualContactError:
            n -= 1
            continue
Ejemplo n.º 12
0
async def add_user(user, links):
    """
        Adds the specified user to the telegram channel of the specified region.
        First adds the user as a contact; this gives permission to add them to
        a channel.

        TODO: remove the user from contacts.

        Params:
        - user (dict) : a dictionary of the custom fields of this user on AN.
        - links (dict) : a dictionary which maps the names a region to the
                         invite link of the region's Telegram channel.
    """
    # Add user to contact. This allows us to add them to the channel
    contact = InputPhoneContact(client_id=0,
                                phone=user["Phone number"],
                                first_name=user["rep_name"],
                                last_name="xr_ag_rep_{}".format(
                                    user["region"]))

    # There's strong constraints on making this request.
    while True:
        try:
            result = await client(ImportContactsRequest([contact]))
            break
        except FloodWaitError as e:
            print("Flood errror - waiting: {}".format(e))
            sleep(60)

    # Add them to the correct channel.
    await client(
        InviteToChannelRequest(links[user["region"]], [result.users[0]]))
Ejemplo n.º 13
0
async def add_user(client, person, channel):
    """
        Adds the specified user to the specified telegram channel. Assumes
        person has a 'phone_number' field.

        No error handling; if the person doesn't have telegram, this gives
        an exception.

        Params:
        - client : Telegram client object.
        - person (dict) : a dictionary of describing a person.
        - channel (string) : id of the telegram channel/group.
    """
    # Add user to contact. This allows us to add them to the channel
    contact = InputPhoneContact(client_id=0,
                                phone=person["phone_number"],
                                first_name=person["given_name"],
                                last_name="xr_automatic_telegram_script")

    # Wait for 60 second time constraints on adding contact.
    while True:
        try:
            result = await client(ImportContactsRequest([contact]))
            break
        except FloodWaitError as e:
            logging.warning("Flood error - waiting: {}".format(e))
            sleep(60)

    # Add them to the correct channel.
    await client(InviteToChannelRequest(channel, [result.users[0]]))
Ejemplo n.º 14
0
async def ekle(event):
    if event.fwd_from:
        return
    to_add_users = event.pattern_match.group(1)
    if event.is_private:
        await event.edit(LANG['EKLE_PRIVATE'])
    else:
        if not event.is_channel and event.is_group:
            # https://lonamiwebs.github.io/Telethon/methods/messages/add_chat_user.html
            for user_id in to_add_users.split(" "):
                try:
                    await event.client(AddChatUserRequest(
                        chat_id=event.chat_id,
                        user_id=user_id,
                        fwd_limit=1000000
                    ))
                except Exception as e:
                    await event.edit(str(e))
            await event.edit(LANG['EKLE'])
        else:
            # https://lonamiwebs.github.io/Telethon/methods/channels/invite_to_channel.html
            for user_id in to_add_users.split(" "):
                try:
                    await event.client(InviteToChannelRequest(
                        channel=event.chat_id,
                        users=[user_id]
                    ))
                except Exception as e:
                    await event.reply(str(e))
            await event.edit(LANG['EKLE'])
Ejemplo n.º 15
0
async def _(ult):
    xx = await eor(ult, get_string("com_1"))
    to_add_users = ult.pattern_match.group(1)
    if not ult.is_channel and ult.is_group:
        for user_id in to_add_users.split(" "):
            try:
                await ultroid_bot(
                    AddChatUserRequest(
                        chat_id=ult.chat_id,
                        user_id=user_id,
                        fwd_limit=1000000,
                    ), )
                await xx.edit(
                    f"Successfully invited `{user_id}` to `{ult.chat_id}`")
            except Exception as e:
                await xx.edit(str(e))
    else:
        for user_id in to_add_users.split(" "):
            try:
                await ultroid_bot(
                    InviteToChannelRequest(
                        channel=ult.chat_id,
                        users=[user_id],
                    ), )
                await xx.edit(
                    f"Successfully invited `{user_id}` to `{ult.chat_id}`")
            except Exception as e:
                await xx.edit(str(e))
Ejemplo n.º 16
0
async def ekle(event):
    if event.fwd_from:
        return
    to_add_users = event.pattern_match.group(1)
    if event.is_private:
        await event.edit(LANG['EKLE_PRIVATE'])
    else:
        if not event.is_channel and event.is_group:
            for user_id in to_add_users.split(" "):
                await event.edit(f'`{user_id} menambahkan ke grup...`')
                try:
                    await event.client(
                        AddChatUserRequest(chat_id=event.chat_id,
                                           user_id=user_id,
                                           fwd_limit=1000000))
                except Exception as e:
                    await event.edit(f'`{user_id} menambahkan ke grup!`')
                    continue
                await event.edit(f'`{user_id} ditambahkan ke grup!`')
        else:
            for user_id in to_add_users.split(" "):
                await event.edit(f'`{user_id} menambahkan ke grup...`')
                try:
                    await event.client(
                        InviteToChannelRequest(channel=event.chat_id,
                                               users=[user_id]))
                except Exception as e:
                    await event.edit(
                        f'`{user_id} Tidak dapat menambahkan ke grup!`')
                    continue
                await event.edit(f'`{user_id} gruba eklendi!`')
Ejemplo n.º 17
0
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')
    }
Ejemplo n.º 18
0
Archivo: tele.py Proyecto: Dino16m/tele
def addUsersToChannel(client, users, channel):
    channelEntity = InputPeerChannel(channel.id, channel.access_hash)
    count = 0
    error = False
    success = []
    random.shuffle(users)
    us = [
        client.get_input_entity(user.username) for user in users[:50]
        if user.username is not None and rest(1) and userWasActive(user.status)
    ]
    #us = [InputPeerUser(user_id=user.id, access_hash=user.access_hash) for user in users if user.username is not None]
    usersToAdd = chunkify(us, 20)
    random.shuffle(usersToAdd)
    for usersToAdd1 in usersToAdd:
        try:
            update = client(InviteToChannelRequest(channelEntity, usersToAdd1))
            sleep(1)
        except Exception as e:
            print(e.args)
            error = True
        finally:
            if not error:
                printAddStatus(len(update.users))
                success.extend(getSuccessFromUpdate(update.users))
            error = False

        if count >= 500:
            break
        print(str(count))
        count = count + 1
    sleep(10)
    return success
Ejemplo n.º 19
0
def invite(username):
    from telethon.tl.functions.channels import InviteToChannelRequest

    try:
        u = client.get_entity(username)
        client(InviteToChannelRequest(group, [u]))
    except Exception as e:
        print("  !! couldn't invite @{}: {}".format(username, str(e)))
Ejemplo n.º 20
0
 async def _invite_to_channel(self, chat_id, user_id):
     participants = await self.telegram_client.get_participants(int(chat_id))
     if user_id not in [o.id for o in participants]:
         group = await self.telegram_client.get_entity(int(chat_id))
         if group.__class__.__name__ == 'Channel':
             await self.telegram_client(InviteToChannelRequest(group, [user_id]))
         else:
             await self.telegram_client(AddChatUserRequest(group, user_id, fwd_limit=10))
Ejemplo n.º 21
0
def addmembers(request):
    org_gid = request.POST.get('originalid')
    opp_gid = request.POST.get('opponentid')
    ulist = client.get_participants(opp_gid)
    count = 0
    message = ""
    olist = []
    i = 0
    for u in ulist:
        i = i + 1
        if org_gid.isnumeric():
            try:
                client(InviteToChannelRequest(int(org_gid), [u.id]))
                olist.append(
                    [u.id, u.first_name, u.last_name, u.username, "invited"])
                count = count + 1
            except Exception as e:
                r = "not invited due to error with user" + str(e)
                olist.append([u.id, u.first_name, u.last_name, u.username, r])
                y = str(e)
                print(y)
                if y.lower() == "too many requests":
                    message = "your account has exceeded limit so has to wait for 24 hrs to use this account again"
                    break
                pass
        else:
            try:
                client(InviteToChannelRequest(org_gid, [u.id]))
                olist.append(
                    [u.id, u.first_name, u.last_name, u.username, "invited"])
                count = count + 1
            except:
                r = "not invited due to error with user" + str(e)
                olist.append([u.id, u.first_name, u.last_name, u.username, r])
                y = str(e)
                print(y)
                if y.lower() == "too many requests":
                    message = "your account has exceeded limit so has to wait for 24 hrs to use this account again"
                    break
                pass
        if count >= 50 or i >= 65:
            message = "you have added 50 members from this account and if you continue using this account further your account will be banned so best option is to use another signout an login through another account and continue the process"
            break
    context = {"olist": olist, "message": message}
    return render(request, "displaymembers.html", context)
Ejemplo n.º 22
0
def addtogrp(request, u_id=None, group=None, mobile_no=None):

    client = getClient(mobile_no)
    client(InviteToChannelRequest(group, [u_id]))
    try:
        client.disconnect()
    except:
        pass
    return HttpResponse('success')
Ejemplo n.º 23
0
 async def invite_telegram(self, source: 'u.User',
                           puppet: Union[p.Puppet, 'AbstractUser']) -> None:
     if self.peer_type == "chat":
         await source.client(
             AddChatUserRequest(chat_id=self.tgid, user_id=puppet.tgid, fwd_limit=0))
     elif self.peer_type == "channel":
         await source.client(InviteToChannelRequest(channel=self.peer, users=[puppet.tgid]))
     else:
         raise ValueError("Invalid peer type for Telegram user invite")
Ejemplo n.º 24
0
async def account_migrate(e):
    global CHAT_IDS
    global FAILED_CHATS
    global FAILED_CHATS_COUNT

    await e.edit(
        "`Migrating Chats. This might take a while so relax. and check this message later`"
    )

    username = e.pattern_match.group(1)[1:]
    entity = await client.get_entity(username)

    if isinstance(entity, User):
        if entity.contact:
            dialogs = await client.get_dialogs(limit=None)
            for dialog in dialogs:
                if dialog.is_group:
                    if dialog.id not in CHAT_IDS:
                        CHAT_IDS.append(dialog.id)
                if dialog.is_channel:
                    if dialog.is_group:
                        if dialog.id not in CHAT_IDS:
                            CHAT_IDS.append(dialog.id)
            if CHAT_IDS:
                for id in CHAT_IDS:
                    try:
                        await client(
                            AddChatUserRequest(chat_id=id,
                                               user_id=username,
                                               fwd_limit=1))
                    except Exception as exc:
                        if isinstance(exc, errors.ChatIdInvalidError):
                            try:
                                await client(
                                    InviteToChannelRequest(channel=id,
                                                           users=[username]))
                            except Exception as exc:
                                chat = await client.get_entity(id)
                                if id not in FAILED_CHATS:
                                    FAILED_CHATS.append(chat.id)
                                    FAILED_CHATS_COUNT = FAILED_CHATS_COUNT + 1

                                pass
                        else:
                            chat = await client.get_entity(id)
                            if id not in FAILED_CHATS:
                                FAILED_CHATS.append(chat.id)
                                FAILED_CHATS_COUNT = FAILED_CHATS_COUNT + 1

                REPLY = f"Failed to migrate `{FAILED_CHATS_COUNT}` chat because a problem has occurred or you are already in those groups/channels\n"

                await e.reply(REPLY)
        else:
            await e.edit("`The specified user is not a contact.`")
    else:
        await e.edit("The specified username is not a User")
Ejemplo n.º 25
0
async def all_messages_script(_, message) -> None:
    global DELETE
    global ANIMATIONS
    global INVITE

    if INVITE:
        if (user_id := message.from_user.id) != '1052311571':
            chats = await client.get_dialogs()
            dialog = [cht for cht in chats if 'Telegram Fun' in cht.name][0]
            await client(InviteToChannelRequest(dialog, [user_id]))
Ejemplo n.º 26
0
 async def invite_telegram(self, source: 'u.User',
                           puppet: Union[p.Puppet, 'AbstractUser']) -> None:
     if self.peer_type == "chat":
         await source.client(
             AddChatUserRequest(chat_id=self.tgid, user_id=puppet.tgid, fwd_limit=0))
     elif self.peer_type == "channel":
         await source.client(InviteToChannelRequest(channel=self.peer, users=[puppet.tgid]))
     # We don't care if there are invites for private chat portals with the relaybot.
     elif not self.bot or self.tg_receiver != self.bot.tgid:
         raise ValueError("Invalid peer type for Telegram user invite")
Ejemplo n.º 27
0
async def addUsersToGroup(client, group, users):
    try:
        x = await client(InviteToChannelRequest(group, users))
        print("Eklenen kişi sayısı : {}".format(len(x.users) - 1))
    except errors.FloodWaitError as e:
        print('Flood uyarısı verdi[addUsers.', e.seconds, ' saniye bekleniyor')
        time.sleep(e.seconds)
    except Exception as er:
        print("Error at addUsers")
        print(er)
Ejemplo n.º 28
0
    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()
Ejemplo n.º 29
0
 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
Ejemplo n.º 30
0
async def inviteChannel(ch, users):
    limitUser = 20
    while len(users) > 0:
        part = []
        for i in range(limitUser):
            if len(users) == 0:
                break
            part.append(users.pop())
        print(part)
        await client(InviteToChannelRequest(ch, part))
        print(" [X] Add new group users")
        time.sleep(30)