我正在使用 urllib2 向 Giphy API 发出请求,并且我正在使用公共 API 密钥。完全相同的代码在 Google App Engine 上运行良好,但是当我尝试使用 Pythonanywhere 执行它时,我得到“HTTPError: HTTP Error 403: Forbidden”。我已经尝试添加一些标题。
WEBHOOK_URL = 'https://url/webhook'
GIPHY_API_KEY = 'xxx'
BOT_TOKEN = 'xxx'
GIPHY_HOST = "http://api.giphy.com"
app = Flask(__name__)
bot = telegram.Bot(token=BOT_TOKEN)
@app.route('/webhook', methods=['POST'])
def webhook_handler():
if request.method == "POST":
update = telegram.Update.de_json(request.get_json(force=True))
chat_id = update.message.chat_id
text = update.message.text.encode('utf-8')
if text:
values = text.split(" ", 1)
command = values[0].lower()
if command == '/gif':
if len(values) > 1:
endpoint = GIPHY_HOST + '/v1/gifs/random'
data = {
"api_key": GIPHY_API_KEY,
"tag": values[1],
}
endpoint = endpoint + '?' + urllib.urlencode(data)
req = urllib2.Request(endpoint)
resp= urllib2.urlopen(req)
image_url = json.loads(resp.read())["data"]["image_url"]
bot.sendMessage(chat_id=chat_id, text=image_url)
return 'ok'
@app.route('/set_webhook', methods=['GET', 'POST'])
def set_webhook():
bot.setWebhook(WEBHOOK_URL)
return "webhook set"
@app.route('/')
def index():
return '.'
2015-09-08 23:20:25,273 :Exception on /webhook [POST]
Traceback (most recent call last):
File "/home/jannikko2/untitled/venv/local/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/jannikko2/untitled/venv/local/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/jannikko2/untitled/venv/local/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/jannikko2/untitled/venv/local/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/home/jannikko2/untitled/venv/local/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/jannikko2/untitled/main.py", line 42, in webhook_handler
resp= urllib2.urlopen(req)
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden