How to use the telethon.TelegramClient function in Telethon

To help you get started, we’ve selected a few Telethon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github LonamiWebs / Telethon / telethon_examples / replier.py View on Github external
# We can also use client methods from here
    client = event.client

    # If we sent the message, we are replying to someone,
    # and we said "save pic" in the message
    if event.out and event.reply_to_msg_id and 'save pic' in event.raw_text:
        reply_msg = await event.get_reply_message()
        replied_to_user = await reply_msg.get_input_sender()

        message = await event.reply('Downloading your profile photo...')
        file = await client.download_profile_photo(replied_to_user)
        await message.edit('I saved your photo in {}'.format(file))


client = TelegramClient(
    os.environ.get('TG_SESSION', 'replier'),
    get_env('TG_API_ID', 'Enter your API ID: ', int),
    get_env('TG_API_HASH', 'Enter your API hash: '),
    proxy=None
)

with client:
    # This remembers the events.NewMessage we registered before
    client.add_event_handler(handler)

    print('(Press Ctrl+C to stop this)')
    client.run_until_disconnected()
github voidbar / forwardgram / forwardgram.py View on Github external
def start(config):
    client = TelegramClient(config["session_name"], 
                            config["api_id"], 
                            config["api_hash"])
    client.start()

    input_channels_entities = []
    output_channel_entities = []
    for d in client.iter_dialogs():
        if d.name in config["input_channel_names"]:
            input_channels_entities.append(InputChannel(d.entity.id, d.entity.access_hash))
        if d.name in config["output_channel_names"]:
            output_channel_entities.append(InputChannel(d.entity.id, d.entity.access_hash))
            
    if not output_channel_entities:
        logger.error(f"Could not find any output channels in the user's dialogs")
        sys.exit(1)
github kandnub / TG-UserBot / generate_session.py View on Github external
redis_connection = redis.Redis(
        host=endpoint.split(':')[0],
        port=endpoint.split(':')[1],
        password=password.strip()
    )
    try:
        redis_connection.ping()
    except Exception:
        print("Invalid Redis credentials! Exiting the script")
        sys.exit(1)
    session = RedisSession("userbot", redis_connection)
else:
    session = "userbot"

client = telethon.TelegramClient(session, api_id, api_hash)
try:
    with client:
        me = client.loop.run_until_complete(client.get_me())
        name = telethon.utils.get_display_name(me)
    print(f"Successfully generated a session for {name}")
except (AuthKeyError, InvalidBufferError):
    client.session.delete()
    print(
        "Your old session was invalid and has been automatically deleted! "
        "Run the script again to generate a new session."
    )
    sys.exit(1)
github LonamiWebs / Telethon-calls / calls.py View on Github external
PhoneCallRequested, PhoneCallDiscarded, PhoneCall, PhoneCallAccepted, \
    UpdatePhoneCall, PhoneCallProtocol, InputPhoneCall, Updates, UpdateShort
from telethon.utils import get_input_user

try:
    with open('session.conf') as f:
        conf = json.load(f)
        api_id = conf['api_id']
        api_hash = conf['api_hash']
        phone_number = conf['phone_number']
        session_name = conf['session_name']
except Exception as e:
    print('Failed to load session.conf:', repr(e))
    quit()

client = TelegramClient(session_name, api_id, api_hash, process_updates=True)
client.connect()

try:
    top_users = {}
    _, users = client.get_dialogs()
    for u in users:
        try:
            top_users[u.id] = get_input_user(u)
        except ValueError:
            "Not an user"

    # TODO Enhance for security and reliability:
    # https://github.com/danog/MadelineProto/blob/90fc78014eda47b8bf5bfdaaeef435c92884011c/src/danog/MadelineProto/MTProtoTools/AuthKeyHandler.php#L501
    def get_dh_config():
        class DH:
            def __init__(self, dh_config):
github MasterScrat / Chatistics / downloaders / telegram.py View on Github external
def main():
    client = TelegramClient('session_name', config.TELEGRAM_API_ID, config.TELEGRAM_API_HASH)
    client.connect()
    me = sign_in(client)
    list_dialogs(client)
    limit = None
    dd = client.get_message_history(me.id, limit=limit)
    import pdb; pdb.set_trace()
    total_messages, messages, users = client.get_message_history(me.id, limit=limit)
    header = ['id', 'from_id', 'to_id', 'date', 'message', 'is_media', 'is_edited']
    with open('message_history.csv', 'w') as f:
        writer = csv.writer(f)
        writer.writerow(header)
        for message in messages:
            is_media = message.media is not None
            is_edited = message.edit_date is not None
            row = [message.id, message.from_id, message.to_id.user_id, message.date,
                   message.message, is_media, is_edited]
github fakedon / donbot / utils / telegram.py View on Github external
if session:
        config['session'] = session
    if api_id:
        config['api_id'] = api_id
    if api_hash:
        config['api_hash'] = api_hash
    if phone:
        config['phone'] = phone
    if proxy:
        config['proxy'] = proxy
    else:
        config['proxy'] = config.get('proxy', None)

    try:
        client = TelegramClient(config['session'], config['api_id'], config['api_hash'], proxy=config['proxy'])
        client.connect()

        if not client.is_user_authorized():
            # client.send_code_request(config['phone'])
            # client.sign_in(config['phone'], input('Enter the code: '))
            client.sign_in(phone=config['phone'])
            client.sign_in(code=input('Enter the code: '))

        return client
    except Exception:
        return None
github thehelvijs / Instagagement / instagagement / instagagement.py View on Github external
def login():
	global instabot, client, user_followers, user_following, user_media, user_id

	instabot = API()
	instabot.login(	username = config['ig_username'],
					password = config['ig_password'], 
					use_cookie = True, 
					cookie_fname = config['cookie_name'])

	# Telegram client
	client = TelegramClient(config['session'], config['telegram_api_id'], config['telegram_api_hash'])
	client.flood_sleep_threshold = 24 * 60 * 60

	# Get user info
	instabot.get_username_info(instabot.user_id)
	user_followers = instabot.last_json['user']['follower_count']
	user_following = instabot.last_json['user']['following_count']
	user_media = instabot.last_json['user']['media_count']
	user_id = instabot.user_id

	return [user_followers, user_following, user_media, client, instabot]
github LonamiWebs / Telethon / telethon_examples / print_messages.py View on Github external
while True:
        value = input(message)
        try:
            return cast(value)
        except ValueError as e:
            print(e, file=sys.stderr)
            time.sleep(1)


session = os.environ.get('TG_SESSION', 'printer')
api_id = get_env('TG_API_ID', 'Enter your API ID: ', int)
api_hash = get_env('TG_API_HASH', 'Enter your API hash: ')
proxy = None  # https://github.com/Anorov/PySocks

# Create and start the client so we can make requests (we don't here)
client = TelegramClient(session, api_id, api_hash, proxy=proxy).start()


# `pattern` is a regex, see https://docs.python.org/3/library/re.html
# Use https://regexone.com/ if you want a more interactive way of learning.
#
# "(?i)" makes it case-insensitive, and | separates "options".
@client.on(events.NewMessage(pattern=r'(?i).*\b(hello|hi)\b'))
async def handler(event):
    sender = await event.get_sender()
    name = utils.get_display_name(sender)
    print(name, 'said', event.text, '!')

try:
    print('(Press Ctrl+C to stop this)')
    client.run_until_disconnected()
finally:
github kdrag0n / pyrobud / pyrobud / core / telegram_bot.py View on Github external
async def init_client(self: "Bot") -> None:
        # Get Telegram parameters from config and check types
        session_name = self.tg_config["session_name"]
        if not isinstance(session_name, str):
            raise TypeError("Session name must be a string")

        api_id = self.tg_config["api_id"]
        if not isinstance(api_id, int):
            raise TypeError("API ID must be an integer")

        api_hash = self.tg_config["api_hash"]
        if not isinstance(api_hash, str):
            raise TypeError("API hash must be a string")

        # Initialize Telegram client with gathered parameters
        self.client = tg.TelegramClient(
            session_name, api_id, api_hash, connection_retries=10, retry_delay=5
        )