如何将来自电报频道的消息保存为变量 [英] How to save message from telegram channel as variable

查看:36
本文介绍了如何将来自电报频道的消息保存为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

它只打印 # 一次,然后什么也不打印.(这些 # 和 xd 都只是为了测试它们对程序并不重要).但是我需要将 message.text 放入 'new' 变量中,并能够在任何地方使用它,而不仅仅是在 main() 中.由于测试,最后的 while 循环只是暂时的.谢谢大家的帮助.:) 和平.

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.

推荐答案

为了从函数中引用变量,您需要在函数中将其声明为全局变量,以便 Python 知道它需要编辑全局变量并不是私人的.

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

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

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.

这篇关于如何将来自电报频道的消息保存为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆