Python Telegram脚本遇无效用户名报错,如何让代码继续处理下一个用户?
解决Telegram脚本无效用户名跳过问题
你在编写Telegram脚本时遇到ValueError异常,提示No user has "bvbjjkhjb" as username,希望遇到无效用户名时跳过该用户,继续处理下一个。
原代码的问题在于:当mode=2时,client.get_input_entity(user['username'])这行代码未被包含在try-except块中,抛出的ValueError无法被捕获,直接导致脚本中断。
修改方案
将获取receiver的逻辑移到try块内部,同时新增专门的异常分支处理无效用户名场景,确保异常被捕获后跳过当前用户继续执行。
修改后的完整代码
for user in users: receiver = None if mode == 2: if user['username'] == "": continue elif mode == 1: receiver = InputPeerUser(user['id'], user['access_hash']) else: print(re+"[!] Invalid Mode. Exiting.") client.disconnect() sys.exit() try: if mode == 2: receiver = client.get_input_entity(user['username']) print(gr+"[+] Sending Message to:", user['name']) client.send_message(receiver, data.format(user['name'])) print(gr+"[+] Waiting {} seconds".format(SLEEP_TIME)) time.sleep(SLEEP_TIME) except PeerFloodError: print(re+"[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again after some time.") client.disconnect() sys.exit() except ValueError as e: print(re+f"[!] Invalid username: {user['username']}, error: {e}") print(re+"[!] Skipping this user...") continue except Exception as e: print(re+"[!] Error:", e) print(re+"[!] Trying to continue...") continue client.disconnect() print("Done. Message sent to all users.")
修改说明
- 将
mode=2下获取receiver的代码移入try块,确保get_input_entity抛出的异常能被捕获。 - 新增
except ValueError as e分支,专门处理无效用户名的情况,输出更精准的提示信息。 - 保留原有的
PeerFloodError处理逻辑(遇限流直接退出)和其他异常的通用处理(跳过当前用户继续执行)。
内容的提问来源于stack exchange,提问作者Dax Shit
相关产品推荐
相关产品推荐

