Esempio n. 1
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    if event.reply_to_msg_id and not chat:
        replied_msg = await event.get_reply_message()
        if replied_msg.from_id and isinstance(replied_msg.from_id,
                                              PeerChannel):
            chat = replied_msg.from_id.channel_id
        elif (replied_msg.fwd_from and replied_msg.fwd_from.from_id
              and isinstance(replied_msg.fwd_from.from_id, PeerChannel)):
            chat = replied_msg.fwd_from.from_id.channel_id
        else:
            await event.edit(msgRep.REPLY_NOT_CHANNEL)
            return None
    else:
        try:
            chat = int(chat)
        except:
            pass

    if not chat:
        chat = event.chat_id

    try:
        chat_info = await event.client(GetFullChatRequest(chat))
        return chat_info
    except:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
            return chat_info
        except ChannelInvalidError:
            await event.edit(msgRep.INVALID_CH_GRP)
        except ChannelPrivateError:
            await event.edit(msgRep.PRV_BAN)
        except ChannelPublicGroupNaError:
            await event.edit(msgRep.NOT_EXISTS)
        except Exception as e:
            log.warning(e)
            await event.edit(msgRep.CANNOT_GET_CHATINFO.format(chat))

    return None
Esempio n. 2
0
async def sync_full(evt: CommandEvent) -> EventID:
    portal = po.Portal.get_by_mxid(evt.room_id)
    if not portal:
        return await evt.reply("This is not a portal room.")

    if len(evt.args) > 0 and evt.args[0] == "--usebot" and evt.sender.is_admin:
        src = evt.tgbot
    else:
        src = evt.tgbot if await evt.sender.needs_relaybot(portal) else evt.sender

    try:
        if portal.peer_type == "channel":
            res = await src.client(GetFullChannelRequest(portal.peer))
        elif portal.peer_type == "chat":
            res = await src.client(GetFullChatRequest(portal.tgid))
        else:
            return await evt.reply("This is not a channel or chat portal.")
    except (ValueError, RPCError):
        return await evt.reply("Failed to get portal info from Telegram.")

    await portal.update_matrix_room(src, res.full_chat)
    return await evt.reply("Portal synced successfully.")
Esempio n. 3
0
async def add_tg_channels(url):

    try:
        channel = await client.get_entity(url)
        ch_full = await client(GetFullChannelRequest(channel))
        print("\n-----\nTelegam channel", url)
        print(ch_full.full_chat.about)
        lnks = await collect_urls(channel)
        print('lnks', lnks)
        # urls.update(lnks)
        # print("urls",urls)
        for u in lnks:
            print(u)
            if u in G.nodes:
                print(u, " in ")
                G.add_edge(url, u)
                continue
            G.add_edge(url, u)
            nx.write_gml(G, "./test")
            await add_tg_channels(u)
    except:
        print("Can't connect to channel", url)
Esempio n. 4
0
async def _(e):
    reply = await e.get_reply_message()
    if reply and not isinstance(reply.sender, User):
        chat = await reply.get_sender()
    else:
        chat = await e.get_chat()
    if hasattr(chat, "username") and chat.username:
        return await e.eor(f"Username: @{chat.username}")
    if isinstance(chat, types.Chat):
        FC = await e.client(GetFullChatRequest(chat.id))
    elif isinstance(chat, types.Channel):
        FC = await e.client(GetFullChannelRequest(chat.id))
    Inv = FC.full_chat.exported_invite
    if Inv and not Inv.revoked:
        link = Inv.link
    else:
        try:
            r = await e.client(ExportChatInviteRequest(e.chat_id), )
        except no_admin:
            return await e.eor(get_string("chats_2"), time=10)
        link = r.link
    await e.eor(f"Link:- {link}")
Esempio n. 5
0
def get_pinned_message(username, api_id, api_hash, name):
    # (2) Create the client and connect
    client = TelegramClient(username,
                            api_id,
                            api_hash,
                            update_workers=1,
                            spawn_read_thread=False)
    client.connect()

    # Ensure you're authorized
    if not client.is_user_authorized():
        client.send_code_request(phone)
        try:
            client.sign_in(phone, input('Enter the code: '))
        except SessionPasswordNeededError:
            client.sign_in(password=input('Password: '******'1297947823'
    channel_entity = client.get_entity(PeerChannel(cid))
    channel_info = client(GetFullChannelRequest(channel_entity))
    # print(channel_info)
    pinned_msg_id = channel_info.full_chat.pinned_msg_id

    pinned_msg = None
    if pinned_msg_id is not None:
        pinned_msg = client(
            GetHistoryRequest(channel_entity,
                              limit=1,
                              offset_date=None,
                              offset_id=pinned_msg_id + 1,
                              max_id=0,
                              min_id=0,
                              add_offset=0,
                              hash=0))
    return pinned_msg
Esempio n. 6
0
async def join_call(data):
    chat = await get_entity(data['chat'])
    full_chat = await client(GetFullChannelRequest(chat))
    call = await client(GetGroupCallRequest(full_chat.full_chat.call))

    result = await client(
        JoinGroupCallRequest(
            call=call.call,
            muted=False,
            params=DataJSON(data=json.dumps({
                'ufrag':
                data['ufrag'],
                'pwd':
                data['pwd'],
                'fingerprints': [{
                    'hash': data['hash'],
                    'setup': data['setup'],
                    'fingerprint': data['fingerprint'],
                }],
                'ssrc':
                data['source'],
            }), ),
        ), )

    transport = json.loads(result.updates[0].call.params.data)['transport']

    return {
        '_': 'get_join',
        'data': {
            'chat_id': data['chat']['id'],
            'transport': {
                'ufrag': transport['ufrag'],
                'pwd': transport['pwd'],
                'fingerprints': transport['fingerprints'],
                'candidates': transport['candidates'],
            },
        },
    }
Esempio n. 7
0
async def run_every_30_minute():
    if not need_update_check:
        return
    result = await bot(GetFullChannelRequest("UGFnZXJNYWlk"))  # noqa
    async for msg in bot.iter_messages("UGFnZXJNYWlk"):
        if msg.text:
            try:
                data_ = loads(msg.text.strip("`"))
            except JSONDecodeError:
                continue
            need_restart = False
            for data in data_["data"]:
                if data["mode"] == "master":
                    if version < data["version"]:
                        logs.info(lang('update_master'))
                        await execute("git reset --hard")
                        await execute("git pull")
                        await execute(f"{executable} -m pip install -r requirements.txt --upgrade")
                        await execute(f"{executable} -m pip install -r requirements.txt")
                        need_restart = True
                elif data["mode"] == "plugins":
                    if not exists(f"{working_dir}/plugins/version.json"):
                        return
                    with open(f"{working_dir}/plugins/version.json", 'r', encoding="utf-8") as f:
                        version_json = load(f)
                    try:
                        plugin_version = version_json[data["name"]]
                    except KeyError:
                        return
                    if (float(data["version"]) - float(plugin_version)) > 0:
                        logs.info(lang('update_plugins'))
                        remove_plugin(data["name"])
                        await download(data["name"])
                        update_version(data["name"], data["version"])
                        need_restart = True
            if need_restart:
                await bot.disconnect()
Esempio n. 8
0
async def fs(event):
    if not await is_admin(event, event.sender_id):
        return await event.reply("You need to be an admin to do this!")
    permissions = await tbot.get_permissions(event.chat_id, event.sender_id)
    if not permissions.is_creator:
        return await event.reply(
            "❗**Group Creator Required**\nYou have to be the group creator to do that."
        )
    if not await is_admin(event, BOT_ID):
        return await event.reply("I'm not an admin Mind Promoting Me?!")
    args = event.pattern_match.group(2)
    channel = args.replace("@", "")
    if not args:
        chat_db = sql.fs_settings(event.chat_id)
        if chat_db:
            return await event.reply(
                f"Currently Forsubscribe is ✅Enabled.\nSubscribed to @{chat_db.channel}"
            )
        else:
            return await event.reply("Forcesubscribe is currently ❌Disabled.")
    if args == "on" or args == "On":
        return await event.reply("❗Please Specify the Channel Username")
    elif args in ("off", "no", "disable"):
        sql.disapprove(event.chat_id)
        await event.reply("❌ **Force Subscribe is Disabled Successfully.**")
    else:
        try:
            ch_full = await tbot(GetFullChannelRequest(channel=channel))
        except:
            return await event.reply("❗**Invalid Channel Username.**")
        rip = await check_him(channel, BOT_ID)
        if rip is False:
            return await event.reply(
                f"❗**Not an Admin in the Channel**\nI am not an admin in the [channel](https://t.me/{args}). Add me as a admin in order to enable ForceSubscribe.",
                link_preview=False)
        sql.add_channel(event.chat_id, str(channel))
        await event.reply(f"✅ **Force Subscribe is Enabled** to @{channel}.")
Esempio n. 9
0
async def get_chatinfo(event, catevent):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except BaseException:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await catevent.edit("`Invalid channel/group`")
            return None
        except ChannelPrivateError:
            await catevent.edit(
                "`This is a private channel/group or I am banned from there`"
            )
            return None
        except ChannelPublicGroupNaError:
            await catevent.edit("`Channel or supergroup doesn't exist`")
            return None
        except (TypeError, ValueError) as err:
            LOGS.info(err)
            await edit_delete(catevent, "**Error:**\n__Can't fetch the chat__")
            return None
    return chat_info
Esempio n. 10
0
async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await king_bot(GetFullChatRequest(chat))
    except BaseException:
        try:
            chat_info = await king_bot(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await eor(event, "`Grup atau channel invalid.`")
            return None
        except ChannelPrivateError:
            await eor(
                event,
                "`Ini adalah grup/channel privat atau mungkin saya di ban disana.`"
            )
            return None
        except ChannelPublicGroupNaError:
            await eor(event, "`Channel atau supergroup tidak ditemukan.`")
            return None
        except (TypeError, ValueError) as err:
            await eor(event, str(err))
            return None
    return chat_info
Esempio n. 11
0
async def fs(event):
  permissions = await bot.get_permissions(event.chat_id, event.sender_id)
  if not permissions.is_admin:
          return await event.reply("❗**Group admin Required**\nYou have to be the group creator or admin to do that.")
  if not await is_admin(event, LEGENDX):
   return await event.reply("I'm not an admin Mind Promoting Me?!")
  args = event.pattern_match.group(2)
  channel = args.replace("@", "")
  if args == "on" or args == "On":
     return await event.reply("❗Please Specify the Channel Username")
  if args in ("off", "no", "disable"):
    sql.disapprove(event.chat_id)
    await event.reply("❌ **Force Subscribe is Disabled Successfully.**")
  else:
    try:
      ch_full = await bot(GetFullChannelRequest(channel=channel))
    except Exception as e:
      await event.reply(f"{e}")
      return await event.reply("❗**Invalid Channel Username.**")
    rip = await check_him(channel, LEGENDX)
    if rip is False:
      return await event.reply(f"❗**Not an Admin in the Channel**\nI am not an admin in the [channel](https://t.me/{args}). Add me as a admin in order to enable ForceSubscribe.", link_preview=False)
    sql.add_channel(event.chat_id, str(channel))
    await event.reply(f"✅ **Force Subscribe is Enabled** to @{channel}.")
Esempio n. 12
0
async def anti_channel_msg(context):
    if not redis_status():
        await context.edit(f"{lang('error_prefix')}{lang('redis_dis')}")
        return
    if context.chat_id == user_id or not context.is_group:
        await context.edit(lang('ghost_e_mark'))
        return
    if len(context.parameter) == 0:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    if context.parameter[0] == "true":
        data = await bot(GetFullChannelRequest(context.chat_id))
        if not data.full_chat.linked_chat_id:
            return await context.edit("当前群组未链接到频道,无法开启此功能。")
        redis.set("antichannelmsg." + str(context.chat_id),
                  f"{data.full_chat.linked_chat_id}")
        await context.edit(f"已成功开启群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。"
                           )
        await log(f"已成功开启群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
    elif context.parameter[0] == "false":
        try:
            redis.delete("antichannelmsg." + str(context.chat_id))
        except:
            await context.edit('emm...当前对话不存在于自动删除频道消息并且封禁频道功能列表中。')
            return
        await context.edit(f"已成功关闭群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。"
                           )
        await log(f"已成功关闭群组 {str(context.chat_id)} 的自动删除频道消息并且封禁频道功能。")
    elif context.parameter[0] == "add":
        data = redis.get("antichannelmsg." + str(context.chat_id))
        if not data:
            return await context.edit("emm...当前对话不存在于自动删除频道消息并且封禁频道功能列表中。")
        data = data.decode().split(" ")
        try:
            chat_id = context.parameter[1]
            channel_data = await bot(GetFullChannelRequest(int(chat_id))
                                     )  # noqa
        except TypeError:
            return await context.edit("频道 id 错误")
        except ValueError:
            return await context.edit("频道 id 不是 -100 开头的数字")
        except IndexError:
            return await context.edit("没有指定频道 id")
        data.append(str(channel_data.full_chat.id))
        redis.set("antichannelmsg." + str(context.chat_id), " ".join(data))
        await context.edit("添加频道到白名单成功。")
    elif context.parameter[0] == "filter":
        try:
            filter_int = int(context.parameter[1])
        except (IndexError, ValueError):
            return await context.edit("输入错误。")
        redis.set("antichannelmsg.filter:" + str(context.chat_id),
                  str(filter_int))
        await context.edit(f"添加过滤成功,即群组 {str(context.chat_id)} 需要大于"
                           f" {str(filter_int)} 订阅人数的频道才能发言,否则会遭到删除并封禁。")
    elif context.parameter[0] == "status":
        if redis.get("antichannelmsg." + str(context.chat_id)):
            await context.edit('当前对话存在于自动删除频道消息并且封禁频道功能列表中。')
        else:
            await context.edit('当前对话不存在于自动删除频道消息并且封禁频道功能列表中。')
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
Esempio n. 13
0
def isFull(c, group):
    return c(GetFullChannelRequest(group)).full_chat.participants_count >= 5300
Esempio n. 14
0
async def fetch_entity(event=None,
                       full_obj=False,
                       get_chat=False,
                       org_author=False):
    """
    Fetch an user or channel (and a target chat) information from event

    Args:
        event (Event): any event e.g. NewMessage
        full_obj (bool): fetch ChatFull/UserFull object instead.
                         Does not work with groups.
        get_chat (bool): fetches Chat/Channel object too.
                         This changes the return to a tuple
        org_author (bool): focus to original author of a replied message

    Example:
        @ehandler.on(command="example", outgoing=True)
        async def example_handler(event):
            user, chat = fetch_entity(event, get_chat=True)
            await event.edit(f"hi {user.first_name}, welcome in {chat.title}!")

    Returns:
        - Channel/User object (default) or
        - ChatFull/UserFull object if full_obj is set to True or
        - A tuple ((Channel/User, Chat/Channel) or
          (ChatFull/UserFull, Chat/Channel)) if get_chat is set to True
    """
    if not event:
        return (None, None) if get_chat else None
    if event.reply_to_msg_id:
        message = await event.get_reply_message()
        if message.fwd_from and message.fwd_from.from_id and org_author:
            # focus to original author from forwarded messages
            if isinstance(message.fwd_from.from_id, PeerChannel):
                entity = f"-100{message.fwd_from.from_id.channel_id}"
                entity = int(entity)
            else:
                entity = message.fwd_from.from_id.user_id
        elif isinstance(message.from_id, PeerChannel):
            entity = f"-100{message.from_id.channel_id}"
            entity = int(entity)
        else:
            entity = (message.from_id.user_id
                      if message.from_id else message.sender_id)
        chat_obj = await event.get_chat() if get_chat else None  # current chat
        if not entity:
            await event.edit(msgsLang.PERSON_ANONYMOUS)
            return (None, None) if get_chat else None
    else:
        try:
            # args_from_event becomes a list. it takes maximum of 2 arguments,
            # more than 2 will be appended to second element.
            args_from_event = event.pattern_match.group(1).split(" ", 1)
            if len(args_from_event) == 2:
                entity, chat = args_from_event
                try:
                    chat = int(chat)  # chat ID given
                except ValueError:
                    pass

                try:
                    chat_obj = (await event.client.get_entity(chat)
                                if get_chat else None)
                    # entity is not a chat or channel object
                    if isinstance(chat_obj, User):
                        chat_obj = None
                except Exception as e:
                    log.warning(e)
                    chat_obj = None
            else:
                entity = args_from_event[0]
                chat_obj = await event.get_chat() if get_chat else None
        except Exception as e:
            log.warning(e)
            await event.edit(msgsLang.FAIL_FETCH_ENTITY)
            return (None, None) if get_chat else None

        try:
            entity = int(entity)
        except ValueError:
            pass

        if not entity:
            oh_look_its_me = await event.client.get_me()
            entity = oh_look_its_me.id

    try:
        if full_obj:
            try:
                if str(entity).startswith("-100"):
                    raise Exception("Forcefully triggered channel check")
                entity_obj = await event.client(GetFullUserRequest(entity))
            except Exception:
                entity_obj = await event.client(GetFullChannelRequest(entity))
                for c in entity_obj.chats:
                    if (entity_obj.full_chat.id == c.id) and not c.broadcast:
                        raise Exception(f"Entity '{entity}' is not a channel")
        else:
            entity_obj = await event.client.get_entity(entity)
            if not isinstance(entity_obj, (Channel, User)) or \
               (isinstance(entity_obj, Channel) and not entity_obj.broadcast):
                await event.edit(msgsLang.UNSUPPORTED_ENTITY)
                entity_obj = None
        return (entity_obj, chat_obj) if get_chat else entity_obj
    except Exception as e:
        log.warning(e)
        await event.edit(msgsLang.CANT_FETCH_REQ.format(entity))
    return (None, chat_obj) if get_chat else None
Esempio n. 15
0
async def GetStats():
    global FirstRun

    TotalDialogs = 0
    UserCount = 0
    ChannelCount = 0
    SupCount = 0
    ConvertedGroupsIDs = []
    NewGroupsIDs = []
    NumChannel = 0
    NumUser = 0
    NumBot = 0
    NumDeleted = 0
    NumChat = 0
    NumSuper = 0

    FirstTimeRunning = None

    UpdateTime = time.strftime("%c")

    connection = engine.connect()
    if not engine.dialect.has_table(engine, stats_tbl):
        metadata.create_all(bind=engine, tables=[stats_tbl, GroupsInfo_tbl])
    connection.close()

    connection = engine.connect()
    query = db.select([stats_tbl])
    if not connection.execute(query).fetchall():
        FirstTimeRunning = True

    if FirstRun:
        LOGGER.info(
            "Gathering Stats. You'll be able to use this app during this process without problems"
        )
        LOGGER.info(
            "The companion may not respond to your command for 5 second. Don't panic and try again if your command didn't worked"
        )

        LOGGER.info("You can disable this in the config.env file")

        if FirstTimeRunning:
            LOGGER.info(
                "Because this is your first time running this, the .stats command won't work until this process isn't over"
            )

    else:
        LOGGER.info("Updating Stats...")
        LOGGER.info(
            "The companion may not respond to your command for 5 second. Don't panic and try again if your command didn't worked"
        )

    CachedSupergroups = []

    if not FirstTimeRunning:
        connection = engine.connect()
        query = db.select([GroupsInfo_tbl.columns.supergroupid])
        result = connection.execute(query).fetchall()
        for row in result:
            CachedSupergroups.append(row[0])
        connection.close()

    UserId = await client.get_me()
    UserId = UserId.id

    dialogs = await client.get_dialogs(limit=None)
    for dialog in dialogs:
        if dialog.is_group:
            NumChat = NumChat + 1
        if dialog.is_user:
            if dialog.entity.bot:
                NumBot = NumBot + 1
            else:
                NumUser = NumUser + 1
        if dialog.is_channel:
            if dialog.is_group:
                NumSuper = NumSuper + 1
            else:
                NumChannel = NumChannel + 1
    completed = 0
    bar = progressbar.ProgressBar(max_value=NumSuper,
                                  widget=None,
                                  poll_interval=1)
    bar.update(completed)
    for dialog in dialogs:
        if dialog.is_channel:
            if dialog.is_group:
                ID1 = utils.get_peer_id(
                    utils.get_input_peer(dialog, allow_self=False))
                strid = str(ID1).replace("-100", "")
                ID = int(strid)
                if ID not in CachedSupergroups:
                    ent = await client.get_input_entity(ID1)
                    gotChatFull = await client(GetFullChannelRequest(ent))

                    connection = engine.connect()

                    query = db.insert(GroupsInfo_tbl).values(
                        supergroupid=gotChatFull.full_chat.id,
                        oldgroupid=gotChatFull.full_chat.migrated_from_chat_id)

                    connection.execute(query)
                    connection.close()

    LookIds = []

    for dialog in dialogs:
        ID = None
        try:
            ID = utils.get_peer_id(
                utils.get_input_peer(dialog, allow_self=False))
        except Exception:
            ID = UserId
        if dialog.is_channel:
            strid = str(ID).replace("-100", "")
            ID = int(strid)
        elif dialog.is_group:
            strid = str(ID).replace("-", "")
            ID = int(strid)
        LookIds.append(ID)

    for dialog in dialogs:
        if dialog.is_group:
            ID = utils.get_peer_id(
                utils.get_input_peer(dialog, allow_self=False))
            strid = str(ID).replace("-100", "")
            ID = int(strid)

            connection = engine.connect()
            query = db.select([
                GroupsInfo_tbl
            ]).where(GroupsInfo_tbl.columns.supergroupid == ID)
            exec = connection.execute(query)
            result = exec.fetchall()
            connection.close()
            for row in result:
                if row[1] is not None:
                    NewGroupsIDs.append(row[0])
                    ConvertedGroupsIDs.append(row[1])
    bar.finish()

    print("Counting your chats...")

    for dialog in dialogs:
        try:
            ID = utils.get_peer_id(
                utils.get_input_peer(dialog, allow_self=False))
        except Exception:
            ID = UserId
        if dialog.is_channel:
            strid = str(ID).replace("-100", "")
            ID = int(strid)
        elif dialog.is_group:
            strid = str(ID).replace("-", "")
            ID = int(strid)
        if utils.get_display_name(dialog.entity) == "":
            NumDeleted = NumDeleted + 1
        elif ID == UserId:
            pass
        if ID not in ConvertedGroupsIDs:
            ent = await client.get_input_entity(dialog)
            msgs = await client.get_messages(ent, limit=0)
            count = msgs.total
            if dialog.is_channel:
                if dialog.entity.megagroup:
                    SupCount = SupCount + count
                else:
                    ChannelCount = ChannelCount + count
            elif dialog.is_group and dialog.is_user:
                UserCount = UserCount + count
        if ID in NewGroupsIDs:
            if ID in LookIds and ID not in ConvertedGroupsIDs:
                index = NewGroupsIDs.index(ID)
                ent = await client.get_input_entity(
                    int("-" + str(ConvertedGroupsIDs[index])))
                msgs = await client.get_messages(ent)
                OldChatCount = msgs.total
                UserCount = UserCount + OldChatCount

    ConvertedCount = len(NewGroupsIDs)
    NumChat = NumChat - ConvertedCount
    TotalDialogs = UserCount + ChannelCount + SupCount

    connection = engine.connect()
    query = db.select([stats_tbl.columns.updatetime])

    if not connection.execute(query).fetchall():
        query = db.insert(stats_tbl).values(
            updatetime=UpdateTime,
            totaldialogs=TotalDialogs,
            usercount=UserCount,
            channelcount=ChannelCount,
            supcount=SupCount,
            convertedgroups=ConvertedCount,
            numchannel=NumChannel,
            numuser=NumUser,
            numdeleted=NumDeleted,
            numbot=NumBot,
            numchat=NumChat,
            numsuper=NumSuper,
        )
    else:
        query = db.update(stats_tbl).values(
            updatetime=UpdateTime,
            totaldialogs=TotalDialogs,
            usercount=UserCount,
            channelcount=ChannelCount,
            supcount=SupCount,
            convertedgroups=ConvertedCount,
            numchannel=NumChannel,
            numuser=NumUser,
            numdeleted=NumDeleted,
            numbot=NumBot,
            numchat=NumChat,
            numsuper=NumSuper,
        )
    connection.execute(query)
    connection.close()

    LOGGER.info("DONE!! You can see your stats by sending .stats in any chat")
Esempio n. 16
0
    async def join_call(data):
        try:
            chat = await get_entity(data["chat"])
        except ValueError:
            stree = (await vcbot.get_me()).first_name
            return await bot.send_message(
                data["chat"]["id"], f"`Please add {stree} in this group.`"
            )
        except Exception as ex:
            return await bot.send_message(data["chat"]["id"], "`" + str(ex) + "`")
        try:
            full_chat = await vcbot(GetFullChannelRequest(chat))
        except ValueError:
            stree = (await vcbot.get_me()).first_name
            return await bot.send_message(
                data["chat"]["id"], f"`Please add {stree} in this group.`"
            )
        except Exception as ex:
            return await bot.send_message(data["chat"]["id"], "`" + str(ex) + "`")
        try:
            call = await vcbot(GetGroupCallRequest(full_chat.full_chat.call))
        except:
            call = None
        if not call:
            return await bot.send_message(
                data["chat"]["id"],
                "`I can't access voice chat.`",
            )

        try:
            result = await vcbot(
                JoinGroupCallRequest(
                    call=call.call,
                    muted=False,
                    join_as="me",
                    params=DataJSON(
                        data=json.dumps(
                            {
                                "ufrag": data["ufrag"],
                                "pwd": data["pwd"],
                                "fingerprints": [
                                    {
                                        "hash": data["hash"],
                                        "setup": data["setup"],
                                        "fingerprint": data["fingerprint"],
                                    },
                                ],
                                "ssrc": data["source"],
                            },
                        ),
                    ),
                ),
            )
            await bot.send_message(
                Var.LOG_CHANNEL,
                f"`Joined Voice Chat in {(await bot.get_entity(data['chat']['id'])).title}`",
            )
        except Exception as ex:
            return await bot.send_message(data["chat"]["id"], "`" + str(ex) + "`")

        transport = json.loads(result.updates[0].call.params.data)["transport"]

        return {
            "_": "get_join",
            "data": {
                "chat_id": data["chat"]["id"],
                "transport": {
                    "ufrag": transport["ufrag"],
                    "pwd": transport["pwd"],
                    "fingerprints": transport["fingerprints"],
                    "candidates": transport["candidates"],
                },
            },
        }
Esempio n. 17
0
def StartCount(dialogs):
    global TotalDialogs, UserCount, ChannelCount, UserId, ConvertedGroupsIDs, NewGroupsIDs, NumChannel, NumUser, NumChat, \
        NumSuper, SupCount, __version__
    CachedSupergroups = []
    FirstRun = None
    database = DBConnection(False, False)
    db1 = database.cursor()
    db1.execute('SELECT * FROM Version')
    for row in db1:
        if row[3] is None:
            FirstRun = True
        else:
            FirstRun = False
    if FirstRun is True:
        cursor = database.cursor()
        cursor.execute(
            '''CREATE TABLE GroupsInfo(SuperGroupID INTEGER PRIMARY KEY, OldGroupID INTEGER)'''
        )
        date = str(datetime.today())
        reg5 = (date, )
        database.execute("UPDATE Version SET LastUpdated=?", reg5)
        database.commit()
    else:
        date = str(datetime.today())
        reg5 = (date, __version__)
        database.execute("UPDATE Version SET LastUpdated=?, AppVersion=?",
                         reg5)
        database.commit()
        db3 = database.cursor()
        db3.execute('SELECT * FROM GroupsInfo')
        for row in db3:
            CachedSupergroups.append(row[0])
    print("\nChecking and processing each chat's data before counting...")
    UserId = client.get_me().id
    for dialog in dialogs:
        client.get_input_entity(dialog)
        if isinstance(dialog.entity, Chat):
            NumChat = NumChat + 1
        if isinstance(dialog.entity, User):
            NumUser = NumUser + 1
        if isinstance(dialog.entity, Channel):
            if dialog.entity.megagroup == True:
                NumSuper = NumSuper + 1
            else:
                NumChannel = NumChannel + 1

    completed = 0
    bar = progressbar.ProgressBar(max_value=NumSuper,
                                  widget=None,
                                  poll_interval=1)
    bar.update(completed)
    for dialog in dialogs:
        if isinstance(dialog.entity, Channel):
            if dialog.entity.megagroup == True:
                ID1 = get_peer_id(get_input_peer(dialog, allow_self=False))
                strid = str(ID1).replace("-100", "")
                ID = int(strid)
                if ID not in CachedSupergroups:
                    gotChatFull = SendRequest(
                        GetFullChannelRequest(client.get_input_entity(ID1)))
                    reg = (gotChatFull.full_chat.id,
                           gotChatFull.full_chat.migrated_from_chat_id)
                    database.execute("INSERT INTO GroupsInfo VALUES(?,?)", reg)
                completed = completed + 1
                bar.update(completed)
    try:
        database.commit()
    except:
        pass
    LookIds = []
    for dialog in dialogs:
        ID = None
        try:
            ID = get_peer_id(get_input_peer(dialog, allow_self=False))
        except:
            ID = UserId
        if isinstance(dialog.entity, Channel):
            strid = str(ID).replace("-100", "")
            ID = int(strid)
        elif isinstance(dialog.entity, Chat):
            strid = str(ID).replace("-", "")
            ID = int(strid)
        LookIds.append(ID)
    for dialog in dialogs:
        if isinstance(dialog.entity, Channel):
            if dialog.entity.megagroup == True:
                ID1 = get_peer_id(get_input_peer(dialog, allow_self=False))
                strid = str(ID1).replace("-100", "")
                ID = int(strid)
                db3 = database.cursor()
                db3.execute('SELECT * FROM GroupsInfo WHERE SuperGroupID={id}'.\
                    format(id=ID))
                for row in db3:
                    if row[1] is not None:
                        NewGroupsIDs.append(row[0])
                        ConvertedGroupsIDs.append(row[1])
    bar.finish()
    DBConnection(False, True)
    print("\nAll is ready. Counting your chats: ")
    print()
    for dialog in dialogs:
        ID = None
        try:
            ID = get_peer_id(get_input_peer(dialog, allow_self=False))
        except:
            ID = UserId
        if isinstance(dialog.entity, Channel):
            strid = str(ID).replace("-100", "")
            ID = int(strid)
        elif isinstance(dialog.entity, Chat):
            strid = str(ID).replace("-", "")
            ID = int(strid)
        if get_display_name(dialog.entity) == "":
            name = "Deleted Account"
        elif ID == UserId:
            name = "***--Chat with yourself (Saved Messages)--***"
        else:
            name = get_display_name(dialog.entity)
        if ID not in ConvertedGroupsIDs:
            count = GatherHistory(client.get_input_entity(dialog))
            if isinstance(dialog.entity, Channel):
                sprint(' {}: {}'.format(name, count) + " *")
                if dialog.entity.megagroup == True:
                    SupCount = SupCount + count
                else:
                    ChannelCount = ChannelCount + count
            elif isinstance(dialog.entity, (Chat, User)):
                sprint(' {}: {}'.format(name, count))
                UserCount = UserCount + count
        if ID in NewGroupsIDs:
            if (ID not in LookIds) and (ID in ConvertedGroupsIDs):
                continue
            else:
                index = NewGroupsIDs.index(ID)
                OldChatCount = GatherHistory(
                    client.get_input_entity(
                        int("-" + str(ConvertedGroupsIDs[index]))))
                print(
                    "· !--> You also have ", OldChatCount,
                    " messages before '" + name +
                    "' was converted into a supergroup.")
                UserCount = UserCount + OldChatCount
Esempio n. 18
0
def get_channel(channel, limit=settings.LIMIT_POST):
    """ geting date from telegram """
    try:
        bio = client(JoinChannelRequest(channel))
    except ValueError:
        return None

    full = client(GetFullChannelRequest(channel))
    bio_channel = full
    response = {"msg": []}
    response['username'] = bio.chats[0].username
    response['date'] = bio.chats[0].date
    response['title'] = bio.chats[0].title
    if bio.chats[0].photo:
        response['photo'] = client.download_profile_photo(
            bio.chats[0].username, file=settings.TMP_FILE)
    else:
        response['photo'] = None
    response['members'] = bio_channel.full_chat.participants_count
    response['bio'] = bio_channel.full_chat.about
    response['access_hash'] = bio.chats[0].access_hash
    response['id'] = bio.chats[0].id
    response['update'] = False if (bio.updates == []) else True

    messages = client.get_messages(channel, limit=limit)
    response['count'] = len(messages)
    for msg in messages:
        res = {}
        try:
            res['post_author'] = msg.post_author
        except AttributeError:
            pass

        res["id"] = str(msg.id)
        res["author"] = get_display_name(msg.sender)
        res["message"] = msg.message

        try:
            if getattr(msg.media, "document", None):
                mime_type = msg.media.document.mime_type
            elif getattr(msg.media, "photo", None):
                mime_type = "photo"
            else:
                mime_type = ""

            if "audio" in mime_type:
                is_audio = client.download_media(msg, file=settings.TMP_FILE)
                if is_audio and is_audio.split(".")[-1] in [
                        "mp3", "wav", "amr", "acc"
                ]:
                    res["audio"] = is_audio

            if "video" in mime_type:
                is_video = client.download_media(msg, file=settings.TMP_FILE)
                if is_video and is_video.split(".")[-1] in ['mp4']:
                    res["video"] = is_video

            if "photo" in mime_type:
                is_photo = client.download_media(msg, file=settings.TMP_FILE)
                if is_photo and is_photo.split(".")[-1] in [
                        'jpg', 'jpeg', 'png', 'gif'
                ]:
                    res["photo"] = is_photo

        except AttributeError:
            # ToDo: add deleted file
            pass

        try:
            res["views"] = msg.views
        except AttributeError:
            res["views"] = 0

        try:
            res["date"] = msg.date
        except AttributeError:
            res["date"] = None

        try:
            res["edit_date"] = msg.edit_date
        except AttributeError:
            res["edit_date"] = None

        try:
            res["via_bot"] = msg.via_bot_id
        except AttributeError:
            res["via_bot"] = None

        response['msg'].append(res)
    return response
Esempio n. 19
0
def add_users_to_group():
    global ve
    input_file = f'data/data{ve}.csv'
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['srno'] = row[0]
            user['username'] = row[1]
            try:
                user['id'] = int(row[2])
                user['access_hash'] = int(row[3])
                user['name'] = row[4]
            except IndexError:
                print('users without id or access_hash')
            users.append(user)
    #random.shuffle(users)
    chats = []
    last_date = None
    chunk_size = 10
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:  # CONDITION TO ONLY LIST MEGA GROUPS.
                groups.append(chat)

        except:
            continue

    print('Choose a group to add members:')
    i = 0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]
    print('\n\nGroup Selected:\t' + groups[int(g_index)].title)

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
    startfrom = int(input("Start From = "))
    endto = int(input("End To = "))
    delta_xd = False
    error_count = 0

    for user in users:
        global status

        status = 'do'
        countt = 6
        if (int(startfrom) <= int(user['srno'])) and (int(user['srno']) <=
                                                      int(endto)):

            try:

                if mode == 1:
                    if user['username'] == "":
                        print('no username, moving to next')
                        continue
                    user_to_add = client.get_input_entity(user['username'])
                elif mode == 2:
                    user_to_add = InputPeerUser(user['id'],
                                                user['access_hash'])
                else:
                    sys.exit("Invalid Mode Selected. Please Try Again.")
                client(
                    InviteToChannelRequest(target_group_entity, [user_to_add]))
                #print("Waiting 60 Seconds...")
                status = 'DONE'
                time.sleep(5)
            except PeerFloodError:
                status = 'PeerFloodError'
                print('Script Is Stopping Now For 24 Hours')
                time.sleep(86400)
                #print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
            except UserPrivacyRestrictedError:
                status = 'PrivacyError'
                #print("The user's privacy settings do not allow you to do this. Skipping.")
            except errors.RPCError as e:
                status = e.__class__.__name__

            except Exception as d:
                status = d
            except:
                traceback.print_exc()
                print("Unexpected Error")
                error_count += 1
                if error_count > 10:
                    sys.exit('too many errors')
                continue
            channel_full_info = client(
                GetFullChannelRequest(channel=target_group_entity))

            countt = int(channel_full_info.full_chat.participants_count)

            print(
                f"ADDING {user['name']} TO {target_group.title} TOTAL: {countt} - {status}"
            )
        elif int(user['srno']) > int(endto):
            #print("Members Added Successfully!")
            delta_xd = True
    print("Done!" if delta_xd else "Error!")
Esempio n. 20
0
    # Create Graph object
    graph = nx.Graph()

    client.start(config['telegram']['phone_id'])
    client_name = client.get_me().first_name

    # Add Client as root node
    graph.add_node(client_name, color=config['graph']['color']['client'])

    # For each not ignored channel in list of dialogs
    for channel in [dialog.entity for dialog in client.get_dialogs()
                        if isinstance(dialog.entity, Channel) and 
                           dialog.entity.id not in config['graph']['channels_ignore']]:

        # Get full information for a channel and word wrap its name
        channel_full_info = client(GetFullChannelRequest(channel=channel))
        channel_name = '\\n'.join(wrap(channel.title, config['graph']['wordwrap_length']))

        # Add channel ID as node with attributes 'title' and 'color', link it to the root node
        graph.add_node(channel.id, title=channel_name, color=config['graph']['color']['channel'])
        graph.add_edge(client_name, channel.id)

        # For each contact in full information 
        for contact_name in re.findall("@([A-z0-9_]{1,100})", channel_full_info.full_chat.about):

            # Add contact as node with attribute and link to the channel node
            graph.add_node(contact_name, color=config['graph']['color']['user'])
            graph.add_edge(contact_name, channel.id) 

    # Create Planutml file object
    plantumlFile = open("{}_telegram_graph.plantuml".format(client_name), 'w')
Esempio n. 21
0
async def process_group(group_entity):
    # The user passed a channel dict
    if isinstance(group_entity, dict):
        try:
            group = InputChannel(group_entity['group_id'],
                                 group_entity['group_hash'])
        except KeyError:
            group = await client.get_input_entity(group_entity['url'])
    else:
        group = await client.get_input_entity(group_entity)

    group_full = await client(GetFullChannelRequest(channel=group))

    # If it is a channel we get the attached group chat
    try:
        chat = group_full.chats[1] \
                if group_full.chats[0].broadcast else group_full.chats[0]
    except IndexError:
        logger.warning(
            f'{group_entity} is a channel without a discussion group, skipped')
        return 0

    target_group_dict = {
        'last_update': datetime.now(),
        'id': chat.id,
        'access_hash': chat.access_hash,
        'title': filter_emojis(chat.title),
        'tags': [],
        'members': []
    }
    try:
        target_group_dict['tags'] = group_entity['tags']
    except (KeyError, TypeError):
        pass

    try:
        with open(f'{data_path}/{target_group_dict["id"]}.json', 'r') as\
                target_group_file:
            target_group_dict['members'] = \
                json.load(target_group_file)['members']
    except FileNotFoundError:
        pass

    # Must be done twice because aggressive doesn't get users with
    # non latin names, and normal one doesn't get all users
    participants_non_aggressive = await client.get_participants(chat, )
    participants_non_aggressive = [
        *map(
            lambda x: {
                'id': x.id,
                'access_hash': x.access_hash,
                'first_name': filter_emojis(x.first_name),
                'last_name': filter_emojis(x.last_name),
                'username': x.username,
                'phone': x.phone
            },
            filter(
                lambda x: x.id not in settings['user_exceptions'] and not x.
                bot, participants_non_aggressive))
    ]

    participants = await client.get_participants(chat, aggressive=True)

    participants = [
        *map(
            lambda x: {
                'id': x.id,
                'access_hash': x.access_hash,
                'first_name': filter_emojis(x.first_name),
                'last_name': filter_emojis(x.last_name),
                'username': x.username,
                'phone': x.phone
            },
            filter(
                lambda x: x.id not in settings['user_exceptions'] and not x.
                bot, participants))
    ]

    participants = dedupe_members_and_merge(participants,
                                            participants_non_aggressive)

    target_group_dict['members'] = dedupe_members_and_merge(
        target_group_dict['members'], participants)

    with open(f'{data_path}/{target_group_dict["id"]}.json', 'w') as\
            target_group_file:
        json.dump(target_group_dict,
                  target_group_file,
                  indent=4,
                  default=str,
                  ensure_ascii=False)

    logger.info('Data successfully collected from'
                f' {target_group_dict["title"]}'
                f'({target_group_dict["id"]})')
    for chat in group_full.chats:
        logger.info(f"\tAssociated chat: {chat.title}({chat.username})")

    return len(participants)
Esempio n. 22
0
async def eat(context: NewMessage.Event):
    assert isinstance(context.message, Message)
    if len(context.parameter) > 2:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    diu_round = False
    from_user = user_object = context.sender
    from_user_id = await get_full_id(from_user)
    if context.reply_to_msg_id:
        reply_message = await context.get_reply_message()
        try:
            user_id = reply_message.sender_id
        except AttributeError:
            await context.edit("出错了呜呜呜 ~ 无效的参数。")
            return
        if user_id > 0:
            target_user = await context.client(GetFullUserRequest(user_id))
            target_user_id = target_user.user.id
        else:
            target_user = await context.client(GetFullChannelRequest(user_id))
            target_user_id = target_user.full_chat.id
    else:
        user_raw = ""
        if len(context.parameter) == 1 or len(context.parameter) == 2:
            user_raw = user = context.parameter[0]
            if user.isnumeric():
                user = int(user)
        else:
            user = from_user_id
        if context.message.entities is not None:
            if isinstance(context.message.entities[0], MessageEntityMentionName):
                target_user = await context.client(GetFullUserRequest(context.message.entities[0].user_id))
                target_user_id = target_user.user.id
            elif isinstance(context.message.entities[0], MessageEntityPhone):
                if user > 0:
                    target_user = await context.client(GetFullUserRequest(user))
                    target_user_id = target_user.user.id
                else:
                    target_user = await context.client(GetFullChannelRequest(user))
                    target_user_id = target_user.full_chat.id
            elif isinstance(context.message.entities[0], MessageEntityBotCommand):
                target_user = await context.client(GetFullUserRequest(user_object.id))
                target_user_id = target_user.user.id
            else:
                return await context.edit("出错了呜呜呜 ~ 参数错误。")
        elif user_raw[:1] in [".", "/", "-", "!"]:
            target_user_id = await get_full_id(from_user)
        else:
            try:
                user_object = await context.client.get_entity(user)
                target_user_id = await get_full_id(user_object)
            except (TypeError, ValueError, OverflowError, StructError) as exception:
                if str(exception).startswith("Cannot find any entity corresponding to"):
                    await context.edit("出错了呜呜呜 ~ 指定的用户不存在。")
                    return
                if str(exception).startswith("No user has"):
                    await context.edit("出错了呜呜呜 ~ 指定的道纹不存在。")
                    return
                if str(exception).startswith("Could not find the input entity for") or isinstance(exception,
                                                                                                  StructError):
                    await context.edit("出错了呜呜呜 ~ 无法通过此 UserID 找到对应的用户。")
                    return
                if isinstance(exception, OverflowError):
                    await context.edit("出错了呜呜呜 ~ 指定的 UserID 已超出长度限制,您确定输对了?")
                    return
                raise exception
    photo = await context.client.download_profile_photo(
        target_user_id,
        "plugins/eat/" + str(target_user_id) + ".jpg",
        download_big=True
    )

    reply_to = context.message.reply_to_msg_id
    if exists("plugins/eat/" + str(target_user_id) + ".jpg"):
        for num in range(1, max_number + 1):
            print(num)
            if not exists('plugins/eat/eat' + str(num) + '.png'):
                re = get(f'{git_source}eat/eat' + str(num) + '.png')
                with open('plugins/eat/eat' + str(num) + '.png', 'wb') as bg:
                    bg.write(re.content)
            if not exists('plugins/eat/mask' + str(num) + '.png'):
                re = get(f'{git_source}eat/mask' + str(num) + '.png')
                with open('plugins/eat/mask' + str(num) + '.png', 'wb') as ms:
                    ms.write(re.content)
        number = randint(1, max_number)
        try:
            p1 = 0
            p2 = 0
            if len(context.parameter) == 1:
                p1 = context.parameter[0]
                if p1[0] == ".":
                    diu_round = True
                    if len(p1) > 1:
                        try:
                            p2 = int("".join(p1[1:]))
                        except:
                            # 可能也有字母的参数
                            p2 = "".join(p1[1:])
                elif p1[0] == "-":
                    if len(p1) > 1:
                        try:
                            p2 = int("".join(p1[1:]))
                        except:
                            # 可能也有字母的参数
                            p2 = "".join(p1[1:])
                    if p2:
                        redis.set("eat.default-config", p2)
                        await context.edit(f"已经设置默认配置为:{p2}")
                    else:
                        redis.delete("eat.default-config")
                        await context.edit(f"已经清空默认配置")
                    return
                elif p1[0] == "/":
                    await context.edit(f"正在更新远程配置文件")
                    if len(p1) > 1:
                        # 获取参数中的url
                        p2 = "".join(p1[1:])
                        if p2 == "delete":
                            redis.delete(configFileRemoteUrlKey)
                            await context.edit(f"已清空远程配置文件url")
                            return
                        if p2.startswith("http"):
                            # 下载文件
                            if downloadFileFromUrl(p2, configFilePath) != 0:
                                await context.edit(f"下载配置文件异常,请确认url是否正确")
                                return
                            else:
                                # 下载成功,加载配置文件
                                redis.set(configFileRemoteUrlKey, p2)
                                if await loadConfigFile(context, True) != 0:
                                    await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确")
                                    return
                                else:
                                    await context.edit(f"下载并加载配置文件成功")
                        else:
                            # 根据传入模版id更新模版配置,多个用","或者","隔开
                            # 判断redis是否有保存配置url

                            splitStr = ","
                            if "," in p2:
                                splitStr = ","
                            ids = p2.split(splitStr)
                            if len(ids) > 0:
                                # 下载文件
                                configFileRemoteUrl = redis.get(configFileRemoteUrlKey)
                                if configFileRemoteUrl:
                                    if downloadFileFromUrl(configFileRemoteUrl, configFilePath) != 0:
                                        await context.edit(f"下载配置文件异常,请确认url是否正确")
                                        return
                                    else:
                                        # 下载成功,更新对应配置
                                        if await loadConfigFile(context) != 0:
                                            await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确")
                                            return
                                        else:
                                            await downloadFileByIds(ids, context)
                                else:
                                    await context.edit(f"你没有订阅远程配置文件,更新个🔨")
                    else:
                        # 没传url直接更新
                        if await updateConfig(context) != 0:
                            await context.edit(f"更新配置文件异常,请确认是否订阅远程配置文件,或从远程下载的配置文件格式是否正确")
                            return
                        else:
                            await context.edit(f"从远程更新配置文件成功")
                    return
                elif p1[0] == "!" or p1[0] == "!":
                    # 加载配置
                    if exists(configFilePath):
                        if await loadConfigFile(context) != 0:
                            await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确")
                            return
                    txt = ""
                    if len(positions) > 0:
                        noShowList = []
                        for key in positions:
                            txt = f"{txt},{key}"
                            if len(positions[key]) > 2:
                                noShowList.append(positions[key][2])
                        for key in noShowList:
                            txt = txt.replace(f",{key}", "")
                        if txt != "":
                            txt = txt[1:]
                    await context.edit(f"目前已有的模版列表如下:\n{txt}")
                    return
            defaultConfig = redis.get("eat.default-config")
            if isinstance(p2, str):
                number = p2
            elif isinstance(p2, int) and p2 > 0:
                number = int(p2)
            elif not diu_round and ((isinstance(p1, int) and int(p1) > 0) or isinstance(p1, str)):
                try:
                    number = int(p1)
                except:
                    number = p1
            elif defaultConfig:
                try:
                    defaultConfig = defaultConfig.decode()
                    number = int(defaultConfig)
                except:
                    number = str(defaultConfig)
                    # 支持配置默认是倒立的头像
                    if number.startswith("."):
                        diu_round = True
                        number = number[1:]

        except:
            number = randint(1, max_number)

        # 加载配置
        if exists(configFilePath):
            if await loadConfigFile(context) != 0:
                await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确")
                return

        try:
            notifyStr = notifyStrArr[str(number)]
        except:
            notifyStr = "吃头像"
        await context.edit(f"正在生成 {notifyStr} 图片中 . . .")
        markImg = Image.open("plugins/eat/" + str(target_user_id) + ".jpg")
        try:
            eatImg = Image.open("plugins/eat/eat" + str(number) + ".png")
            maskImg = Image.open("plugins/eat/mask" + str(number) + ".png")
        except:
            await context.edit(f"图片模版加载出错,请检查并更新配置:{str(number)}")
            return

        if diu_round:
            markImg = markImg.rotate(180)  # 对图片进行旋转
        try:
            number = str(number)
        except:
            pass
        result = await eat_it(context, from_user_id, eatImg, maskImg, markImg, number)
        result.save('plugins/eat/eat.webp')
        target_file = await context.client.upload_file("plugins/eat/eat.webp")
        try:
            remove("plugins/eat/" + str(target_user_id) + ".jpg")
            remove("plugins/eat/" + str(target_user_id) + ".png")
            remove("plugins/eat/" + str(from_user_id) + ".jpg")
            remove("plugins/eat/" + str(from_user_id) + ".png")
            remove("plugins/eat/eat.webp")
            remove(photo)
        except:
            pass
    else:
        await context.edit("此用户未设置头像或头像对您不可见。")
        return
    if reply_to:
        try:
            await context.client.send_file(
                context.chat_id,
                target_file,
                link_preview=False,
                force_document=False,
                reply_to=reply_to
            )
            await context.delete()
            remove("plugins/eat/eat.webp")
            try:
                remove(photo)
            except:
                pass
            return
        except TypeError:
            await context.edit("此用户未设置头像或头像对您不可见。")
        except ChatSendStickersForbiddenError:
            await context.edit("此群组无法发送贴纸。")
    else:
        try:
            await context.client.send_file(
                context.chat_id,
                target_file,
                link_preview=False,
                force_document=False
            )
            await context.delete()
            remove("plugins/eat/eat.webp")
            try:
                remove(photo)
            except:
                pass
            return
        except TypeError:
            await context.edit("此用户未设置头像或头像对您不可见。")
        except ChatSendStickersForbiddenError:
            await context.edit("此群组无法发送贴纸。")
Esempio n. 23
0
async def get_full_id(object_n):
    if isinstance(object_n, Channel):
        return (await bot(GetFullChannelRequest(object_n.id))).full_chat.id  # noqa
    elif not object_n:
        return user_id
    return (await bot(GetFullUserRequest(object_n.id))).user.id
client = Client.getClient()
config = yaml.safe_load(open("config.yaml"))
input_file = config["input_channel_file"]
channels = getChannelList(input_file)

channel_info_list = list()
i = 1
for channel in channels:
    i = i + 1
    print("Channel: " + channel + " Nr: " + str(i))
    time.sleep(3)
    try:
        channel_entity = client.get_entity(channel)
        channel_full_info = client(
            GetFullChannelRequest(channel=channel_entity))

        if channel_full_info.full_chat.location is not None:
            geo_point = channel_full_info.full_chat.location.geo_point
            address = channel_full_info.full_chat.location.address
        else:
            geo_point = ""
            address = ""
        channel_info_list.append([
            channel_entity.username, channel_entity.id,
            channel_full_info.full_chat.about, channel_entity.broadcast,
            channel_entity.date,
            channel_full_info.full_chat.participants_count, geo_point, address
        ])
    except:
        traceback.print_exc()
Esempio n. 25
0
async def auto_process_channel_msg(context):
    """ Event handler to delete channel messages and ban channel. """
    if not redis_status():
        return
    if not context.is_group:
        return
    # 匿名管理员
    if not context.sender:
        return
    data = redis.get("antichannelmsg." + str(context.chat_id))
    if not data:
        return
    filter_data = redis.get("antichannelmsg.filter:" + str(context.chat_id))
    if filter_data is not None:
        participants_count = redis.get("antichannelmsg.participants_count:" +
                                       str(context.chat_id))
        if participants_count is None:
            expire = 300
            try:
                channel_data = await bot(
                    GetFullChannelRequest(int(context.sender.id)))
                participants_count = channel_data.full_chat.participants_count
                expire = 3600
            except:  # noqa
                participants_count = 0
            redis.set("antichannelmsg.participants_count:" +
                      str(context.chat_id),
                      participants_count,
                      ex=expire)
        else:
            try:
                participants_count = int(participants_count)
            except ValueError:
                participants_count = 0
        try:
            filter_int = int(filter_data)
        except ValueError:
            filter_int = -1
    try:
        if not isinstance(context.sender, Channel):
            return
        data = data.decode().split(" ")
        # 白名单
        if str(context.sender.id) in data:
            return
        # 频道订阅人数检测
        if filter_data is not None and (filter_int != -1
                                        and participants_count >= filter_int):
            return

        # 删除消息,封禁频道
        try:
            await context.delete()
            entity = await context.client.get_input_entity(context.chat_id)
            user = await context.client.get_input_entity(context.sender.id)
            await context.client(
                EditBannedRequest(channel=entity,
                                  participant=user,
                                  banned_rights=ChatBannedRights(
                                      until_date=None, view_messages=True)))
        except ChatAdminRequiredError:
            redis.delete("antichannelmsg." + str(context.chat_id))
    except:
        return
    try:
        await context.unpin()
    except ChatAdminRequiredError:
        redis.delete("antichannelmsg." + str(context.chat_id))
    except:
        pass
Esempio n. 26
0
def isFull(c, group):
    return c(GetFullChannelRequest(group)).full_chat.participants_count >= MAX_USERS_IN_GROUP
Esempio n. 27
0
#---------------------------------------------------------------------------
#Encoding: utf-8							   |
#!/usr/bin/python3							   |
#Channel users parser						   	   |
#Attention: The script will only work if you ARE a channel administrator!  |
#---------------------------------------------------------------------------
#Connect the necessary libraries:			   		   |
#---------------------------------------------------------------------------
from telethon.sync import TelegramClient
from telethon.tl.functions.channels import GetFullChannelRequest

#Get api_id and api_hash on the website: https://my.telegram.org/
api_id = 000000
api_hash = 'hash'
name_channel = 'my_channel'

#If necessary, enter the phone number and code from the SMS message
with TelegramClient('my_session', api_id, api_hash) as client:
    full = client(GetFullChannelRequest(name_channel))
    bio = full.users
    file = open('usernames.txt', 'a')
    for item in bio:
        file.write('@' + item.username)
Esempio n. 28
0
                      hash=0))

# Extracts group 'title' and 'username' from result.chats
# 'title' is the visible group name, 'username' is the internal reference name
# Exception is for empty result.chats
for chat in result.chats:
    try:
        groupTitles.append(chat.title)
        groupUsernames.append(chat.username)
    except AttributeError:
        pass

# Extracts number of members and messages for each group and prints.
# Extracts the most recent message id. Used to stop main while loop below.
for dialog, username in zip(result.dialogs, groupUsernames):
    channel_full_info = client(GetFullChannelRequest(channel=username))
    memberCount = channel_full_info.full_chat.participants_count
    groupMembers.append(memberCount)
    groupTopIDs.append(dialog.top_message)
    print('Messages:',
          str(dialog.top_message).ljust(9), 'Members:',
          str(memberCount).ljust(9), 'Group:', username)

print('URL Validation =', urlValidate)

# Loop through all groups
for title, username, members, topID in zip(groupTitles, groupUsernames,
                                           groupMembers, groupTopIDs):

    # Creates log file and writes group info and header rows
    # 'offset' or offset_id is the starting message id
Esempio n. 29
0
def autos():

    channel_username = to_group
    phone = utils.parse_phone(pphone)

    client = TelegramClient(f"../sessions/{phone}", api_id, api_hash)

    client.connect()
    if not client.is_user_authorized():
        print('some thing has changed')
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))

    input_file = '../data.csv'
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['srno'] = row[0]
            user['username'] = row[1]
            user['id'] = int(row[2])
            #user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    startfrom = int(input("Start From = "))
    endto = int(input("End To = "))

    for user in users:
        if (int(startfrom) <= int(user['srno'])) and (int(user['srno']) <=
                                                      int(endto)):
            try:
                status = 'delta'
                if user['username'] == "":
                    print("no username, moving to next")
                    continue

                client(
                    InviteToChannelRequest(channel_username,
                                           [user['username']]))
                status = 'DONE'

                #print("Waiting for 60-180 Seconds...")
                time.sleep(random.randrange(0, 5))

            except UserPrivacyRestrictedError:
                status = 'PrivacyRestrictedError'

            except UserAlreadyParticipantError:
                status = 'ALREADY'

            except PeerFloodError as g:
                status = 'PeerFloodError :('
                print(
                    'Script Is Stopping Now, Dont Use This Account For The Next 24 Hours'
                )
                time.sleep(86400)

            except ChatWriteForbiddenError as cwfe:

                client(JoinChannelRequest(channel_username))
                continue

            except errors.RPCError as e:
                status = e.__class__.__name__

            except Exception as d:
                status = d

            except:
                traceback.print_exc()
                print("Unexpected Error")
                continue
            channel_connect = client.get_entity(channel_username)
            channel_full_info = client(
                GetFullChannelRequest(channel=channel_connect))
            countt = int(channel_full_info.full_chat.participants_count)

            print(
                f"ADDING {user['name']} TO {channel_username} TOTAL: {countt} - {status}"
            )
        elif int(user['srno']) > int(endto):
            print("Members Added Successfully!")
            stat = input(
                'Done!\nChoose From Below:\n\n1 - Repeat The Script\nOR Just Hit Enter To Quit\n\nEnter: '
            )
            if stat == '1':
                autos()
            else:
                quit()
Esempio n. 30
0
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.types import ChannelParticipantsSearch
from time import sleep
from telethon.tl.types import InputChannel

from telethon.tl.functions.channels import GetMessagesRequest

from telethon.tl.functions.channels import GetFullChannelRequest

offset = 0
limit = 100
all_participants = []
channel = InputChannel(mp3downloads1.id, mp3downloads1.access_hash)

full_chat = client.invoke(GetFullChannelRequest(channel))
print(full_chat)
print(full_chat.stringify())
sys.exit(1)

while True:
    participants = client.invoke(
        GetParticipantsRequest(channel, ChannelParticipantsSearch(''), offset,
                               limit))
    print(participants.stringify())
    sys.exit(1)
    if not participants.users:
        break
    all_participants.extend(participants.users)
    offset += len(participants.users)
    print(participants.users[0].stringify())