python - 如何避免将“全局”与 asyncio(电视节目)一起使用?
问题描述
据我所知,在 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()
解决方案
查看文档,我找不到将客户端与类一起使用的推荐方法,但您应该始终能够自己连接它。例如:
class MyClient:
def __init__(self, client):
self.task = None
self.client = client
async def on_message(self, channel_id, event):
text = event.raw_text.lower()
if text == 'start':
self.task = self.client.loop.create_task(self.main(channel_id))
await self.client.send_message(channel_id, 'task was started')
if text == 'stop':
self.task.cancel()
await self.client.send_message(channel_id, 'task was canceled')
async def main(self, channel_id):
while True:
await self.client.send_message(channel_id, 'do something')
await asyncio.sleep(3)
def run_client():
# instantiate telegram client, my client, and connect the two
api_id = ***
api_hash = '***'
channel_id = ***
client = TelegramClient('session_name', api_id, api_hash).start()
my_client = MyClient(client)
@client.on(events.NewMessage(chats=channel_id))
async def handle(event):
await my_client.on_message(channel_id, event)
client.run_until_disconnected()
run_client()
推荐阅读
- c# - Replace text which contain line breaks without dropping them
- reactjs - 在导航离开事件上反应路由器 v5
- javascript - 框显示警报,但我想要其他方法,例如使用 if 链或 switch 或使用 for 循环或使用 map 运算符
- javafx - 在JavaFX中未硬编码的文本框中键入时如何使用所有颜色
- llvmlite - LLVMLITE Hello World 示例产生错误的输出
- c# - Cosmonaut(CosmosDb) - 序列化问题
- gradle - 如何覆盖一个依赖项的配置级别“transitive = false”
- android - 在android中创建自定义视图组
- javascript - JS用斜杠替换字符串
- svg - 是否有混合模式来替换黑色并保留其他颜色(即白色)?