async def init(): print('Logging in and creating new .session file...') if os.path.exists('bot.session'): os.remove('bot.session') client = Client('bot', plugins={'enabled': False}) await client.start() session_config = { k: v for section in config.sections() for k, v in config.items(section) } session_config = json.dumps(session_config) session_config = b64encode(session_config) session_string = client.export_session_string() me = await client.get_me() mention = f"@{me.username}" if me.username else me.first_name cprint(f"Logged in as {mention}", 'green') print("\nYour PYROGRAM_CONFIG (SENSITIVE DATA, DO NOT SHARE):") cprint(session_config, 'blue') print("\nYour PYROGRAM_SESSION (SENSITIVE DATA, DO NOT SHARE):") cprint(session_string + "\n", 'green') await client.stop()
def handle(self, phone_number, **options): if not is_mobile_number(phone_number): raise ValueError( "Le numéro doit être un numéro de téléphone mobile.") (session, created) = TelegramSession.objects.get_or_create( phone_number=phone_number) client = Client(":memory:", phone_number=str(phone_number), **api_params) client.start() session_string = client.export_session_string() session.session_string = session_string session.save() client.stop()
from pyrogram import Client c = Client( ":memory:", api_id=123456, # EDIT ME in api_id=YOUR_API_ID_HERE, api_hash="abcdefgh", # EDIT ME in api_hash="YOUR_API_HASH_HERE", config_file="no_configuration_files" ) c.start() print("Session string ->", c.export_session_string()) c.stop()
################################ # pip install pyrogram # mainly for termux ################################ import os try: import pyrogram from pyrogram import Client except: os.system("pip install --upgrade pyrogram") import pyrogram from pyrogram import Client APP_ID = input("Enter your APP_ID : ") API_HASH = input("Enter your API_HASH : ") app = Client("pyrouserbot", api_id=APP_ID, api_hash=API_HASH) with app: print(app.export_session_string())
while len(API_HASH) != 32: API_HASH = input('API HASH: ') app = Client( 'sedenuserbot', api_id=API_ID, api_hash=API_HASH, app_version='Seden UserBot', device_model='DerUntergang', system_version='Session', lang_code='en', ) with app: self = app.get_me() session = app.export_session_string() out = f'''**Hi [{self.first_name}](tg://user?id={self.id}) \nAPI_ID:** `{API_ID}` \n**API_HASH:** `{API_HASH}` \n**SESSION:** `{session}` \n**NOTE: Don't give your account information to others!**''' out2 = 'Session successfully generated!' if self.is_bot: print(f'{session}\n{out2}') else: app.send_message('me', out) print('''Session successfully generated! Please check your Telegram Saved Messages''') elif lang == 'tr': print('''Lütfen my.telegram.org adresine gidin
c.execute( 'CREATE TABLE IF NOT EXISTS keys (key text PRIMARY KEY NOT NULL, value text)' ) db.commit() c.execute('INSERT INTO keys (key, value) VALUES (%s,%s)', ("api_id", id_)) db.commit() c.execute('INSERT INTO keys (key, value) VALUES (%s,%s)', ("api_hash", hash_)) db.commit() c.execute('INSERT INTO keys (key, value) VALUES (%s,%s)', ("bot_token", btoken)) db.commit() c.execute('INSERT INTO keys (key, value) VALUES (%s,%s)', ("channel", channel)) db.commit() user_app = Client(":memory:", api_id=id_, api_hash=hash_) bot_app = Client(":memory:", api_id=id_, api_hash=hash_, bot_token=btoken) bot_app.start() c.execute('INSERT INTO keys (key, value) VALUES (%s,%s)', ["bot_session", bot_app.export_session_string()]) db.commit() bot_app.stop() user_app.start() user_app.authorize() c.execute('INSERT INTO keys (key, value) VALUES (%s,%s)', ["user_session", user_app.export_session_string()]) db.commit() db.close() user_app.stop() print("Success! Everything is set up. Enjoy!")
# Complete the authorization process # More info https://docs.pyrogram.org/intro/setup.html from pyrogram import Client from pyrogram.types import Message from app.core.config import TELEGRAM_API_ID, TELEGRAM_API_HASH if __name__ == '__main__': app = Client(':memory:', TELEGRAM_API_ID, TELEGRAM_API_HASH) SESSION_STRING = '' with app: print('Save this in SESSION_STRING environment variable') print('SESSION_STRING\n') SESSION_STRING = app.export_session_string() print(SESSION_STRING) print('\n') client = Client(SESSION_STRING, TELEGRAM_API_ID, TELEGRAM_API_HASH) @client.on_message() def cid_handler(client: Client, message: Message): print(f'CHANNEL ID {message.chat.id}') print( 'Send some text in your channel and save channel id in CID environment variable' ) print('PRESS Ctrl^c to stop') client.run()
import os from pyrogram import Client if __name__ == "__main__": client = Client("pyrogram", api_id=os.getenv("CLIENT_API_ID"), api_hash=os.getenv("CLIENT_API_HASH")) with client: print(client.export_session_string())
import os from pyrogram import Client as TelegramClient telegram = TelegramClient(":memory:", api_id=os.environ['TELEGRAM_API_ID'], api_hash=os.environ['TELEGRAM_API_HASH']) with telegram: print("Successfully logged in!") print("Session string: ") session_string = telegram.export_session_string() print(session_string) with open('telegram_session.string', 'w') as write_file: write_file.write(session_string)
class Telegram: def __init__(self, config=None): self.app = None self.django_telegram_link = link self.init_apps = [] self.connector = None self.session_string = None self.groups = [] if config: self.config = config self.django_config_id = self.config['id'] self.session_name = self.config['session_name'] self.api_id = self.config['api_id'] self.api_hash = self.config['api_hash'] self.access_token = self.config['access_token'] self.bot_token = self.config['bot_token'] self.is_bot = bool(self.config['is_bot']) self.is_active = bool(self.config['is_active']) self.is_ready = bool(self.config['is_ready']) async def run_session(self): if self.is_ready: await self.run() else: await logger('config is not ready!') def get_updates_groups(self): for line in self.app.get_dialogs(): if line['chat']['type'] != 'private' and line['chat']['type'] != 'bot': if not line['chat'] in self.groups: chat = line['chat'] permissions = chat['permissions'] data = { "id": str(chat['id']), "type": str(chat['type']), "is_verified": bool(chat['is_verified']), "is_restricted": bool(chat['is_restricted']), "is_scam": bool(chat['is_scam']), "title": str(chat['title']), "username": str(chat['username']), # "can_send_messages": bool(permissions['can_send_messages']), # "can_send_media_messages": bool(permissions['can_send_media_messages']), # "can_send_other_messages": bool(permissions['can_send_other_messages']), # "can_add_web_page_previews": bool(permissions['can_add_web_page_previews']), # "can_send_polls": bool(permissions['can_send_polls']), # "can_change_info": bool(permissions['can_change_info']), # "can_invite_users": bool(permissions['can_invite_users']), # "can_pin_messages": bool(permissions['can_pin_messages']), } self.groups.append(data) return self.groups def get_groups(self): return self.groups def send_message(self, to, text): self.app.send_message(to, text) async def run(self): if self.is_bot: await logger('Init Bot session') self.app = Client( self.session_name, api_id=self.api_id, api_hash=self.api_hash, bot_token=self.bot_token, workers=2, workdir='apps/telegram/sessions/', device_model='MacBookPro12,1, macOS 10.14.6', app_version='Telegram macOS 5.8 (185085) APPSTORE', system_version='Darwin 18.7.0', ) if not self.is_bot: await logger('Init User-Bot session') self.app = Client( self.session_name, api_id=self.api_id, api_hash=self.api_hash, workers=2, workdir='apps/telegram/sessions/', device_model='MacBookPro12,1, macOS 10.14.6', app_version='Telegram macOS 5.8 (185085) APPSTORE', system_version='Darwin 18.7.0', ) @self.app.on_message() def message_handler(client, message): print(message) ''' { async.core | "_": "pyrogram.Message", async.core | "message_id": 52, async.core | "date": "2019-12-11 14:37:57", async.core | "chat": { async.core | "_": "pyrogram.Chat", async.core | "id": -1001294234578, async.core | "type": "supergroup", async.core | "is_verified": false, async.core | "is_restricted": false, async.core | "is_scam": false, async.core | "title": "Mew mew cats", async.core | "username": "******", async.core | "permissions": { async.core | "_": "pyrogram.ChatPermissions", async.core | "can_send_messages": true, async.core | "can_send_media_messages": true, async.core | "can_send_other_messages": true, async.core | "can_add_web_page_previews": true, async.core | "can_send_polls": true, async.core | "can_change_info": false, async.core | "can_invite_users": true, async.core | "can_pin_messages": false async.core | } async.core | }, async.core | "from_user": { async.core | "_": "pyrogram.User", async.core | "id": 889996703, async.core | "is_self": true, async.core | "is_contact": false, async.core | "is_mutual_contact": false, async.core | "is_deleted": false, async.core | "is_bot": false, async.core | "is_verified": false, async.core | "is_restricted": false, async.core | "is_scam": false, async.core | "is_support": false, async.core | "first_name": "Апчхи", async.core | "status": "online", async.core | "next_offline_date": "2019-12-11 14:42:43", async.core | "username": "******", async.core | "phone_number": "***********" async.core | }, async.core | "mentioned": false, async.core | "scheduled": false, async.core | "from_scheduled": false, async.core | "media": true, async.core | "photo": { async.core | "_": "pyrogram.Photo", async.core | "file_id": "AgADAgADbawxG2r0iEsD5etIC9BKM7yywg8ABAEAAwIAA3kAA9bJAAIWBA", async.core | "file_ref": "BE0kc9IAAAA0XfFTpWZMm8I7UFlfxfbGRYHIpZk", async.core | "width": 862, async.core | "height": 1080, async.core | "file_size": 152766, async.core | "date": "2019-12-11 14:34:38", async.core | "thumbs": [ async.core | { async.core | "_": "pyrogram.Thumbnail", async.core | "file_id": "AgADAgADbawxG2r0iEsD5etIC9BKM7yywg8ABAEAAwIAA20AA9jJAAIWBA", async.core | "width": 256, async.core | "height": 320, async.core | "file_size": 21119 async.core | }, async.core | { async.core | "_": "pyrogram.Thumbnail", async.core | "file_id": "AgADAgADbawxG2r0iEsD5etIC9BKM7yywg8ABAEAAwIAA3gAA9nJAAIWBA", async.core | "width": 639, async.core | "height": 800, async.core | "file_size": 100745 async.core | } async.core | ] async.core | }, async.core | "caption": "здесь какая то подпись", async.core | "outgoing": true async.core | } ''' result = parse_message(message) result.update({ "id": self.django_config_id, "access_token": self.access_token, "app_id": self.api_id, "api_hash": self.api_hash, "session_name": self.session_name, "is_bot_session": self.is_bot, }) requests.post(create_message_link, data=result) @self.app.on_disconnect() def disconnect_handler(message=None): print('disconnect signal') print(message) self.app.add_handler(message_handler) self.app.add_handler(disconnect_handler) self.app.start() self.session_string = self.app.export_session_string() app_data = { "app_id": self.api_id, "api_hash": self.api_hash, "session_name": self.session_name, "session_string": self.session_string, "access_token": self.access_token, "is_bot_session": self.is_bot, "is_ready": self.is_ready, "is_active": self.is_active, "connected": self.app.is_connected, } requests.post(f'{DJANGO_SERVER_URL}/api/telegram/config', data=app_data) app_data.update({ "telegram_instance": self, "app": self.app, }) self.connector = TelegramAppConnector(app_data) if not self.is_bot: connector.add(self.connector, default=True) else: connector.add(self.connector) async def get_config(self): return self.config