【发布时间】:2020-12-10 19:06:44
【问题描述】:
据我所知,在 python 中使用“全局”是一种不好的做法,但我不知道如何在这里避免它。 提前谢谢你。
import asyncio
from telethon import TelegramClient, sync, events
api_id = ***
api_hash = '***'
client = TelegramClient('session_name', api_id, api_hash).start()
channel_id = ***
@client.on(events.NewMessage(chats=channel_id))
async def handler(event):
text = event.raw_text.lower()
global task
if text == 'start':
task = client.loop.create_task(main())
await client.send_message(channel_id, 'task was started')
if text == 'stop':
task.cancel()
await client.send_message(channel_id, 'task was canceled')
async def main():
while True:
await client.send_message(channel_id, 'do something')
await asyncio.sleep(3)
client.run_until_disconnected()
【问题讨论】:
-
通常人们使用类变量而不是全局变量,并且只是传递对该类的引用。或者,您可以让该类包含所有变量 和 逻辑,因此您甚至不必传递引用。当然,前提是你应该防范竞态条件和其他线程陷阱,如果它是全局的,你就必须这样做。
标签: python python-asyncio telethon