Instagram-Discord通知Bot运行异常:环境变量配置问题
解决Instagram-Discord通知Bot的环境变量配置问题
问题根源
你错误地把环境变量的值当成了os.environ.get()的参数(也就是环境变量的键名)。比如:
- 你用
os.environ.get('instagram')想获取监控的Instagram用户名,但这里的'instagram'应该是环境变量的名称(比如INSTAGRAM_TARGET_USER),实际用户名是这个变量对应的值。 - Discord Webhook地址同理,不能直接把URL作为键名传入
os.environ.get(),得用合法的变量名(比如DISCORD_WEBHOOK_URL)。 - 检查间隔时间的
os.environ.get('10')也是错误,应该用变量名(比如CHECK_INTERVAL)。
修正步骤
1. 修改代码中的环境变量键名
把代码里所有错误的键名替换成合法变量名,核心修改点如下:
# 替换原用户名获取逻辑 INSTAGRAM_USERNAME = os.environ.get('INSTAGRAM_TARGET_USER') # 替换webhook调用中的键名 webhook(os.environ.get('DISCORD_WEBHOOK_URL'), get_instagram_html(INSTAGRAM_USERNAME)) # 替换入口判断和sleep逻辑 if __name__ == "__main__": if os.environ.get('INSTAGRAM_TARGET_USER') is not None and os.environ.get('DISCORD_WEBHOOK_URL') is not None: while True: main() time.sleep(float(os.environ.get('CHECK_INTERVAL') or 600)) else: print('Please configure environment variables properly!')
2. 设置环境变量
根据操作系统设置对应环境变量:
Windows(命令提示符)
set INSTAGRAM_TARGET_USER=你要监控的Instagram用户名 set DISCORD_WEBHOOK_URL=你的Discord Webhook完整地址 set CHECK_INTERVAL=600 # 可选,默认10分钟(600秒)
PowerShell环境:
$env:INSTAGRAM_TARGET_USER="你要监控的Instagram用户名" $env:DISCORD_WEBHOOK_URL="你的Discord Webhook完整地址" $env:CHECK_INTERVAL=600
Linux/macOS(终端)
export INSTAGRAM_TARGET_USER="你要监控的Instagram用户名" export DISCORD_WEBHOOK_URL="你的Discord Webhook完整地址" export CHECK_INTERVAL=600
如果想永久生效,可将上述命令添加到~/.bashrc(Linux)或~/.zshrc(macOS)文件中。
3. 完整修正后的代码
import os import requests import json import time # 补全原代码缺失的导入 INSTAGRAM_USERNAME = os.environ.get('INSTAGRAM_TARGET_USER') # ----------------------- Do not modify under this line ----------------------- # def get_user_fullname(html): return html.json()["graphql"]["user"]["full_name"] def get_total_photos(html): return int(html.json()["graphql"]["user"]["edge_owner_to_timeline_media"]["count"]) def get_last_publication_url(html): return html.json()["graphql"]["user"]["edge_owner_to_timeline_media"]["edges"][0]["node"]["shortcode"] def get_last_photo_url(html): return html.json()["graphql"]["user"]["edge_owner_to_timeline_media"]["edges"][0]["node"]["display_url"] def get_last_thumb_url(html): return html.json()["graphql"]["user"]["edge_owner_to_timeline_media"]["edges"][0]["node"]["thumbnail_src"] def get_description_photo(html): try: return html.json()["graphql"]["user"]["edge_owner_to_timeline_media"]["edges"][0]["node"]["edge_media_to_caption"]["edges"][0]["node"]["text"] except IndexError: return "无描述" # 处理无描述内容的异常 def webhook(webhook_url, html): data = {} data["embeds"] = [] embed = {} embed["color"] = 15467852 embed["title"] = f"New pic of @{INSTAGRAM_USERNAME}" embed["url"] = f"https://www.instagram.com/p/{get_last_publication_url(html)}/" embed["description"] = get_description_photo(html) embed["thumbnail"] = {"url": get_last_thumb_url(html)} data["embeds"].append(embed) result = requests.post(webhook_url, data=json.dumps(data), headers={"Content-Type": "application/json"}) try: result.raise_for_status() except requests.exceptions.HTTPError as err: print(err) else: print(f"Image successfully posted in Discord, code {result.status_code}.") def get_instagram_html(INSTAGRAM_USERNAME): headers = { "Host": "www.instagram.com", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11" } html = requests.get(f"https://www.instagram.com/{INSTAGRAM_USERNAME}/feed/?__a=1", headers=headers) return html def main(): try: html = get_instagram_html(INSTAGRAM_USERNAME) html.raise_for_status() # 检查请求是否成功 last_image_id = os.environ.get("LAST_IMAGE_ID") current_image_id = get_last_publication_url(html) if last_image_id == current_image_id: print("Not new image to post in discord.") else: os.environ["LAST_IMAGE_ID"] = current_image_id print("New image to post in discord.") webhook(os.environ.get('DISCORD_WEBHOOK_URL'), get_instagram_html(INSTAGRAM_USERNAME)) except Exception as e: print(e) if __name__ == "__main__": required_vars = ['INSTAGRAM_TARGET_USER', 'DISCORD_WEBHOOK_URL'] if all(os.environ.get(var) is not None for var in required_vars): while True: main() time.sleep(float(os.environ.get('CHECK_INTERVAL') or 600)) else: missing = [var for var in required_vars if os.environ.get(var) is None] print(f"Please configure environment variables properly! Missing: {', '.join(missing)}")
验证
设置好环境变量后运行代码,若未提示错误则配置成功。当目标Instagram用户发布新内容时,Discord频道会收到对应通知。
内容的提问来源于stack exchange,提问作者user20536234
相关产品推荐
相关产品推荐

