我想自动回复新的私人信息,我还没有一个对话之前。但我的代码给出了一个错误,我不能找出什么解决方案。
这是我尝试过的:
from telethon import TelegramClient, events
from telethon import functions, types
from time import sleep
api_id = 123456
api_hash = 'enterownapihash'
msg = 'Sorry, I am unavailable right now.'
client = TelegramClient('automessage', api_id, api_hash, sequential_updates=True)
@client.on(events.NewMessage(incoming=True, blacklist_chats=True))
async def setup():
users = set()
async for dialog in client.iter_dialogs():
if dialog.is_user:
users.add(dialog.id)
async def handler(event):
if event.is_private and event.sender_id not in users:
await event.respond(msg)
这是我得到的错误:
Unhandled exception on setup
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\updates.py", line 520, in _dispatch_update
await callback(event)
TypeError: setup() takes 0 positional arguments but 1 was given
现在尝试了这个:
from telethon import TelegramClient, events
from telethon import functions, types
from time import sleep
api_id = 123456
api_hash = 'enterownapihash'
msg = 'Sorry, I am unavailable right now.'
client = TelegramClient('automessage', api_id, api_hash, sequential_updates=True)
async def setup():
global users
users = set()
async for dialog in client.iter_dialogs():
if dialog.is_user and not dialog.entity.bot:
users.add(dialog.id)
@client.on(events.NewMessage(incoming=True))
async def handler(event):
if event.is_private and event.sender_id not in users:
await event.respond(msg)
client.start()
client.run_until_disconnected()
每当我的帐户收到消息时,我都会收到此错误:
Unhandled exception on handler
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\updates.py", line 520, in _dispatch_update
await callback(event)
File "C:\Users\user\Desktop\Scripts\CODING\telethon\AutoRespond.py", line 27, in handler
if event.is_private and event.sender_id not in users:
NameError: name 'users' is not defined
解决这个问题的方法是什么?提前感谢!
1条答案
按热度按时间lawou6xi1#
编辑:
你没有调用setup(),你必须在锁定客户端之前在文件的页脚相应地运行它,直到断开连接以监听事件,比如:
users似乎不在全局范围内,至于错误,装饰器在错误的函数之上。
而且,如果没有提供“聊天”,则“blacklist_chats”是无意义的。