How to save message from telegram channel as variable

1k views Asked by At

This is my code and it doesn't make variable that can be used in other part of my Python script. I need to work with that message to get input from it.

from telethon import TelegramClient, events, sync
from telethon.errors import SessionPasswordNeededError
import time

# Setting configuration values
api_id = 'my api id'
api_hash ='my api hash'

phone = '+my phone number'
username = 'my username'

# Create the client and connect
client = TelegramClient(username, api_id, api_hash)
client.start()
print("Client Created")
# 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: '))

new = '#'
old = 'xd'


async def main():
    limit = 1
    async for message in client.iter_messages('channel sample', limit):
        new = (message.text)
while True:
    with client:
        client.loop.run_until_complete(main())
    if new != old:
        old = new
        print(old)
    time.sleep(5)

It printed # once and than nothing. (these # and xd are both just for testing they aren't important for program). But I need to get message.text into 'new' variable and be able to use it everywhere not just in main(). while loop at the end is just for now because of testing. Thanks everyone for help. :) Peace.

1

There are 1 answers

1
TheKill-996 On

In order to refer to the variable from a function, you need to declare it as global in the function so Python knows that it needs to edit the global variable and not the private one.

import asyncio
new = 'random text'

# start session

async def main():
    global new
    messages = await client.get_messages('channel sample')
    new = messages[0].text

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
print(new)  # message text

You can also can omit the limit since as you can read in the docs

If the limit is not set, it will be 1 by default unless both min_id and max_id are set (as named arguments), in which case the entire range will be returned.