如何使用Python的Instabot库向同一用户发送多条消息?
解决instabot仅发送第一行消息的问题
以下是针对该问题的几种有效解决方案:
1. 清理文本中的换行符
readlines()读取的每行末尾会保留\n换行符,可能导致instabot处理消息时出错。先过滤掉换行符和空行:
with open("rawtext.txt", encoding="utf8") as f: # 去除每行首尾空白,同时过滤空行 lines = [line.strip() for line in f if line.strip()] for line in lines: bot.send_messages(line, ["REDACTED_USER"])
2. 重置Bot的API会话状态
instabot在发送一次消息后,会话状态可能出现异常,导致后续请求无法正常执行。每次发送后重置API状态:
with open("rawtext.txt", encoding="utf8") as f: lines = [line.strip() for line in f if line.strip()] for line in lines: bot.send_messages(line, ["REDACTED_USER"]) bot.api.reset() # 重置API会话,恢复初始状态
3. 添加请求延迟避免触发限制
Instagram对请求频率有严格的反爬限制,短时间内连续发送消息会被拦截。添加延迟降低请求频率:
import time with open("rawtext.txt", encoding="utf8") as f: lines = [line.strip() for line in f if line.strip()] for line in lines: bot.send_messages(line, ["REDACTED_USER"]) time.sleep(5) # 每次发送后等待5秒,可根据情况调整时长 bot.api.reset()
4. 改用单用户消息接口
send_messages原本是用于给多个用户批量发送同一条消息的接口,针对单个用户多次发送,改用send_message方法更合适:
import time with open("rawtext.txt", encoding="utf8") as f: lines = [line.strip() for line in f if line.strip()] for line in lines: bot.send_message(line, "REDACTED_USER") # 参数顺序为消息内容、用户名 time.sleep(5) bot.api.reset()
5. 异常捕获与重试机制
添加异常处理,针对发送失败的情况自动重试,提升稳定性:
import time from instabot import Bot bot = Bot() bot.login(username="你的用户名", password="你的密码") with open("rawtext.txt", encoding="utf8") as f: lines = [line.strip() for line in f if line.strip()] for line in lines: success = False retry_times = 3 while not success and retry_times > 0: try: bot.send_message(line, "REDACTED_USER") success = True except Exception as e: print(f"发送失败:{e},剩余重试次数:{retry_times-1}") retry_times -= 1 time.sleep(10) bot.api.reset() time.sleep(5)
内容的提问来源于stack exchange,提问作者Dumi
相关产品推荐
相关产品推荐

