-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
79 lines (65 loc) · 2.18 KB
/
app.py
File metadata and controls
79 lines (65 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
Simple Twitter/X posting microservice
Uses requests-oauthlib for OAuth 1.0a signing
Deploy to Railway, call from n8n
"""
import os
from flask import Flask, request, jsonify
from requests_oauthlib import OAuth1Session
app = Flask(__name__)
# Load from environment variables
API_KEY = os.environ.get('TWITTER_API_KEY')
API_SECRET = os.environ.get('TWITTER_API_SECRET')
ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
WEBHOOK_SECRET = os.environ.get('WEBHOOK_SECRET', 'change-me-in-production')
def get_twitter_session():
"""Create OAuth1 session for Twitter API v2"""
return OAuth1Session(
API_KEY,
client_secret=API_SECRET,
resource_owner_key=ACCESS_TOKEN,
resource_owner_secret=ACCESS_TOKEN_SECRET
)
@app.route('/health', methods=['GET'])
def health():
return jsonify({"status": "ok"})
@app.route('/tweet', methods=['POST'])
def post_tweet():
# Simple auth check
auth_header = request.headers.get('Authorization', '')
if auth_header != f'Bearer {WEBHOOK_SECRET}':
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json()
if not data or 'text' not in data:
return jsonify({"error": "Missing 'text' field"}), 400
tweet_text = data['text']
try:
twitter = get_twitter_session()
response = twitter.post(
"https://api.twitter.com/2/tweets",
json={"text": tweet_text}
)
if response.status_code == 201:
result = response.json()
return jsonify({
"success": True,
"tweet_id": result['data']['id'],
"text": tweet_text
})
else:
return jsonify({
"success": False,
"status_code": response.status_code,
"error": response.text
}), response.status_code
except Exception as e:
return jsonify({
"success": False,
"error": str(e)
}), 500
if __name__ == '__main__':
port = int(os.environ.get('PORT', 8080))
app.run(host='0.0.0.0', port=port)
```
---