Пример #1
0
#转发信息
# messages = client.get_messages('china_BiBi')
# print(messages[0])
# mes_id = messages[0].id
# mes_text = messages[0].text
# print(mes_text)
# client.forward_messages(1219921340,mes_id,1182116619)

messages = client.get_messages('china_BiBi')
mes_id_1 = messages[0].id
while True:
    messages = client.get_messages('china_BiBi')
    mes_id = messages[0].id
    if mes_id != mes_id_1:
        client.forward_messages(1219921340, mes_id, 1182116619)
        mes_id_1 = mes_id

# For normal chats
# client(AddChatUserRequest(
#     chat_id = -1001219921340 , #chat_id
#     user_id = 585015279, #被邀请人id
#     fwd_limit=10  # Allow the user to see the 10 last messages
# ))

#获取全部的聊天信息
# for message in client.iter_messages(1182116619):
#     ms_id = message.id
#     print(ms_id)

#变量chat为频道id
Пример #2
0
)
parser.add_argument(
    "--sleep-time",
    help=
    "sleep duration between messages, to avoid rate limit, recommended more than 1 seconds",
    default=None,
    required=False,
)

args = parser.parse_args()

config = dotenv_values(".env")

test_channel_link = "test20210513"
try:
    api_id = config["api_id"]
    api_hash = config["api_hash"]
except KeyError as e:
    print(e)
    raise Exception(
        "you need to create a .env file containing api_id and api_hash, read the readme.md file"
    )
client = TelegramClient("session_name", config["api_id"], config["api_hash"])
client.start()

for message in client.iter_messages(args.source_chat):
    client.forward_messages(entity=args.target_chat, messages=message)
    if args.sleep_time:
        sleep(float(args.sleep_time))
client.send_message(args.target_chat, f"all messages coppied successfully")
                                        'w')).writerow(group_array)
                        client.send_message('olp2olp',
                                            text + ' removed from groups')
                elif '/print' in text:
                    client.send_message(
                        'olp2olp', '\n'.join(group_array) + '\n\n' +
                        '\n'.join(filter_array))

                #else:
                #        client.send_message('juspay', 'invalid format')
            break

        #print(group_array)
        #print(filter_array)
        for group in group_array:
            messages = client.iter_messages(group)
            for message in messages:
                #print(message.id)
                #print(message.text)
                text = message.text
                if text and message.id != last_message[group]:
                    last_message[group] = message.id
                    for elem in filter_array:
                        if elem in text:
                            #client.send_message('olp2olp', group + '\n\n' + text)
                            client.forward_messages("olp2olp", message)
                break
            #print(group)
    except:
        client.send_message('olp2olp',
                            'Error in Scrip\nKindly Check the server')
Пример #4
0
##
fh = open('choiceVideo.mp4', 'rb')
msg = loop.run_until_complete(client.send_file('me', fh, attributes=(DocumentAttributeVideo(0, 0, 0),)))

location = 0
max = 2
for x in range(location, r.length():
    print(x.username + '\n')
    location = location + 1
    if location >= max:
        break

    if x.username != 'WTFMI':

        m1 = loop.run_until_complete(client.send_message(x, 'הודעה זו נשלחה באופן אוטומטי, בוקר טוב מהחלל הקיברנט'))
        loop.run_until_complete(client.forward_messages(x, msg))
        #loop.run_until_complete(client(ForwardMessagesRequest(
        #    from_peer='me',  # who sent these messages?
        #    id=msg.id,  # which are the messages?
        #    to_peer=x  # who are we forwarding them to?
        #    )))
    #print(m1)
    #print(m2)
# this was as a test to see how do I fetch stuff
#result = client(ResolveUsernameRequest('@AlonOz'))
#found_chats = result.chats
#found_users = result.users
# end test
#users = client(GetFullChannel(self, 'id'))
#for id in found_chats:
Пример #5
0
class BaseTelegramClient(AioThing):
    def __init__(
        self,
        app_id: Union[int, str],
        app_hash: str,
        database: dict,
        bot_token: Optional[str] = None,
        mtproxy: Optional[dict] = None,
        flood_sleep_threshold: int = 60,
    ):
        super().__init__()
        if not app_id or not app_hash:
            raise ValueError(
                'Your API ID or Hash cannot be empty or None. Set up telegram.app_id and/or telegram.app_hash'
            )
        self._telegram_client = TelegramClient(
            self._get_session(database),
            app_id,
            app_hash,
            flood_sleep_threshold=flood_sleep_threshold,
            **self._get_proxy(mtproxy=mtproxy),
        )
        self.bot_token = bot_token

    def _get_session(self, database):
        if database.get('drivername') == 'postgresql':
            self.container = AlchemySessionContainer(
                f"{database['drivername']}://"
                f"{database['username']}:"
                f"{database['password']}@"
                f"{database['host']}:"
                f"{database['port']}/"
                f"{database['database']}",
                session=False,
                manage_tables=False,
            )
            return self.container.new_session(database['session_id'])
        else:
            return sessions.SQLiteSession(session_id=database['session_id'])

    def _get_proxy(self, mtproxy=None):
        if mtproxy and mtproxy.get('enabled', True):
            proxy_config = mtproxy
            return {
                'connection':
                connection.tcpmtproxy.
                ConnectionTcpMTProxyRandomizedIntermediate,
                'proxy': (proxy_config['url'], proxy_config['port'],
                          proxy_config['secret'])
            }
        return {}

    @retry(retry=retry_if_exception_type(ConnectionError), wait=wait_fixed(5))
    async def start(self):
        await self._telegram_client.start(bot_token=self.bot_token)

    async def stop(self):
        return await self.disconnect()

    def add_event_handler(self, *args, **kwargs):
        return self._telegram_client.add_event_handler(*args, **kwargs)

    def catch_up(self):
        return self._telegram_client.catch_up()

    def delete_messages(self, *args, **kwargs):
        return self._telegram_client.delete_messages(*args, **kwargs)

    def disconnect(self):
        return self._telegram_client.disconnect()

    @property
    def disconnected(self):
        return self._telegram_client.disconnected

    def download_document(self, *args, **kwargs):
        return self._telegram_client._download_document(
            *args,
            date=datetime.datetime.now(),
            thumb=None,
            progress_callback=None,
            msg_data=None,
            **kwargs,
        )

    def edit_message(self, *args, **kwargs):
        return self._telegram_client.edit_message(*args, **kwargs)

    def edit_permissions(self, *args, **kwargs):
        return self._telegram_client.edit_permissions(*args, **kwargs)

    def forward_messages(self, *args, **kwargs):
        return self._telegram_client.forward_messages(*args, **kwargs)

    def get_entity(self, *args, **kwargs):
        return self._telegram_client.get_entity(*args, **kwargs)

    def get_input_entity(self, *args, **kwargs):
        return self._telegram_client.get_input_entity(*args, **kwargs)

    def iter_admin_log(self, *args, **kwargs):
        return self._telegram_client.iter_admin_log(*args, **kwargs)

    def iter_messages(self, *args, **kwargs):
        return self._telegram_client.iter_messages(*args, **kwargs)

    def list_event_handlers(self):
        return self._telegram_client.list_event_handlers()

    def remove_event_handlers(self):
        for handler in reversed(self.list_event_handlers()):
            self._telegram_client.remove_event_handler(*handler)

    def run_until_disconnected(self):
        return self._telegram_client.run_until_disconnected()

    def send_message(self, *args, **kwargs):
        return self._telegram_client.send_message(*args, **kwargs)

    def send_file(self, *args, **kwargs):
        return self._telegram_client.send_file(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        return self._telegram_client(*args, **kwargs)
Пример #6
0
    curwd = os.path.dirname(os.path.realpath(__file__))
    client = TelegramClient(
        os.path.abspath(curwd + '/telethon.session'),
        config.get('api_id'),
        config.get('api_hash')
    )
    client.start()

    sent_ids = json.load(open(curwd + '/sent.json', 'r'))

    msg_from = client.get_messages(config.get('channel_from'))
    msg_to = client.get_messages(config.get('channel_from'))

    for message in msg_from:
        search = config.get('search')
        found = False
        if type(search) == list:
            for term in search:
                found = found or term in message.message
        else:
            found = search in message.message

        if found:
            if message.id not in sent_ids:
                sent_ids.append(message.id)
                client.forward_messages(config.get('channel_to'), message)

    json.dump(sent_ids, open(curwd + '/sent.json', 'w'))
except Exception:
    rv_client.captureException()