如何将电报频道中的消息保存为变量

问题描述

这是我的代码,不会产生可在我的Python脚本的其他部分使用的变量。我需要处理该消息以从中获取输入。

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)

它一共打印了#条。 (这些#和xd都只是用于测试,它们对程序并不重要)。但是我需要将message.text放入'new'变量中,并能够在不仅仅在main()中使用它。由于测试的缘故,while循环的最后只是现在。谢谢大家的帮助。 :)和平。

解决方法

为了从函数中引用变量,您需要将其清除为函数的全局变量,以便Python知道需要编辑全局变量而不是私有变量。

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

您也可以省略该限制,因为您可以在docs

中进行阅读

如果未设置限制,则默认情况下将为1,除非同时设置了min_id和max_id(作为命名参数),在这种情况下将返回整个范围。