Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
335 lines (279 loc) · 10.5 KB
/
Copy pathapp.py
File metadata and controls
335 lines (279 loc) · 10.5 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import os
import time
import uuid
import threading
import requests
import psutil
from io import BytesIO
from urllib.parse import urlparse
from flask import Flask, jsonify, render_template_string
from PIL import Image, ImageFilter
import praw
# Resolve files next to this script, not the current working directory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
USER_AGENT = "AddGoku bot (github.com/python11235/AddGoku)"
TEST_IMAGE = "https://picsum.photos/800/600"
TEST_COOLDOWN = 60
IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp")
# =============================
# LOAD GOKU (png preferred)
# =============================
GOKU = None
GOKU_FOUND = False
GOKU_FILE = None
for name in ["goku.png", "goku.webp"]:
path = os.path.join(BASE_DIR, name)
if os.path.exists(path):
GOKU = Image.open(path).convert("RGBA")
GOKU_FOUND = True
GOKU_FILE = name
print(f"Loaded {name}", flush=True)
break
# =============================
# TASK STORAGE
# =============================
tasks = []
tasks_lock = threading.Lock()
network_start = psutil.net_io_counters()
def new_task(status, result=None, link=None):
with tasks_lock:
task = {"id": len(tasks), "status": status, "result": result, "link": link}
tasks.append(task)
return task
# =============================
# IMAGE PROCESSING
# =============================
def add_goku_to_image(image_url):
if not GOKU_FOUND:
return None
try:
r = requests.get(image_url, timeout=10, headers={"User-Agent": USER_AGENT})
r.raise_for_status()
base = Image.open(BytesIO(r.content)).convert("RGBA")
base.thumbnail((800, 800))
# Resize Goku (25px height)
aspect = GOKU.width / GOKU.height
goku_resized = GOKU.resize((max(1, int(25 * aspect)), 25))
# Fast dark area detection (a 100x100 copy is cheap to scan fully,
# the blur makes the darkest pixel the middle of a dark area)
small = base.resize((100, 100)).convert("L").filter(ImageFilter.BoxBlur(2))
pixels = small.load()
sx, sy = min(((x, y) for x in range(100) for y in range(100)), key=lambda p: pixels[p])
# Center Goku on the darkest spot, keeping him inside the image
best_x = int(sx / 100 * base.width) - goku_resized.width // 2
best_y = int(sy / 100 * base.height) - goku_resized.height // 2
best_x = max(0, min(best_x, base.width - goku_resized.width))
best_y = max(0, min(best_y, base.height - goku_resized.height))
base.paste(goku_resized, (best_x, best_y), goku_resized)
os.makedirs(app.static_folder, exist_ok=True)
filename = f"output_{int(time.time())}_{uuid.uuid4().hex[:8]}.png"
base.save(os.path.join(app.static_folder, filename))
return "/static/" + filename
except Exception as e:
print("Image error:", e, flush=True)
return None
# =============================
# IMGUR UPLOAD
# =============================
def upload_to_imgur(result):
# Imgur links survive restarts and redeploys, unlike files in static/
if not os.getenv("IMGUR_CLIENT_ID"):
return None
try:
with open(os.path.join(app.static_folder, os.path.basename(result)), "rb") as f:
r = requests.post(
"https://api.imgur.com/3/image",
headers={"Authorization": f"Client-ID {os.getenv('IMGUR_CLIENT_ID')}"},
files={"image": f},
timeout=30
)
r.raise_for_status()
return r.json()["data"]["link"]
except Exception as e:
print("Imgur error:", e, flush=True)
return None
# =============================
# REDDIT BOT
# =============================
def find_image_url(submission):
url = submission.url
if urlparse(url).path.lower().endswith(IMAGE_EXTS):
return url
# Gallery posts: use the first image
if getattr(submission, "is_gallery", False):
try:
first = submission.gallery_data["items"][0]["media_id"]
return submission.media_metadata[first]["s"]["u"]
except (KeyError, IndexError, TypeError):
pass
# Anything else Reddit made a preview image for (imgur pages, etc.)
try:
return submission.preview["images"][0]["source"]["url"]
except (AttributeError, KeyError, IndexError):
return None
def handle_mention(item, bot_mention, public_url):
try:
# The inbox also holds DMs and replies to the bot's own comments,
# only comments that actually mention the bot get a Goku
if not isinstance(item, praw.models.Comment) or bot_mention not in item.body.lower():
return
print("Mention from:", item.author, flush=True)
image_url = find_image_url(item.submission)
if not image_url:
print("No image found on post.", flush=True)
return
task = new_task("processing")
result = add_goku_to_image(image_url)
task["result"] = result
# Prefer imgur, fall back to the self-hosted copy
link = result and (upload_to_imgur(result) or (public_url and public_url + result))
if link:
item.reply(f"[Goku has been added 🔥]({link})")
task["status"] = "done"
task["link"] = link
else:
task["status"] = "failed"
except Exception as e:
print("Reddit error:", e, flush=True)
finally:
# Always mark as read, so the same mention is never handled twice
item.mark_read()
def start_reddit_bot():
if not all([
os.getenv("REDDIT_CLIENT_ID"),
os.getenv("REDDIT_CLIENT_SECRET"),
os.getenv("REDDIT_USERNAME"),
os.getenv("REDDIT_PASSWORD")
]):
print("Reddit credentials missing.", flush=True)
return
if os.getenv("PUBLIC_URL"):
public_url = os.getenv("PUBLIC_URL").rstrip("/")
elif os.getenv("RENDER_EXTERNAL_HOSTNAME"):
public_url = f"https://{os.getenv('RENDER_EXTERNAL_HOSTNAME')}"
elif os.getenv("IMGUR_CLIENT_ID"):
public_url = None
else:
print("IMGUR_CLIENT_ID or PUBLIC_URL (or RENDER_EXTERNAL_HOSTNAME) missing.", flush=True)
return
reddit = praw.Reddit(
client_id=os.getenv("REDDIT_CLIENT_ID"),
client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
username=os.getenv("REDDIT_USERNAME"),
password=os.getenv("REDDIT_PASSWORD"),
user_agent=os.getenv("REDDIT_USER_AGENT") or USER_AGENT
)
bot_mention = "u/" + os.getenv("REDDIT_USERNAME").lower()
print("Reddit bot started.", flush=True)
# The stream yields unread inbox items, so mentions that came in while
# the app was asleep still get handled. If Reddit or the network
# hiccups, restart the stream instead of letting the thread die.
while True:
try:
for item in reddit.inbox.stream():
handle_mention(item, bot_mention, public_url)
except Exception as e:
print("Reddit stream error:", e, flush=True)
time.sleep(30)
# =============================
# SYSTEM STATS
# =============================
@app.route("/stats")
def stats():
net = psutil.net_io_counters()
return jsonify({
"cpu": psutil.cpu_percent(),
"ram": psutil.virtual_memory().percent,
"sent": net.bytes_sent - network_start.bytes_sent,
"recv": net.bytes_recv - network_start.bytes_recv,
"goku": GOKU_FOUND,
"file": GOKU_FILE
})
@app.route("/tasks")
def get_tasks():
with tasks_lock:
return jsonify(tasks[-50:])
# =============================
# MANUAL TEST
# =============================
last_test = 0
test_lock = threading.Lock()
@app.route("/test")
def test():
global last_test
# Anyone can reach this, so don't let it be spammed
# (every test is an imgur upload when imgur is set up)
with test_lock:
if time.time() - last_test < TEST_COOLDOWN:
return jsonify({"error": f"Slow down, one test per {TEST_COOLDOWN}s"}), 429
last_test = time.time()
result = add_goku_to_image(TEST_IMAGE)
link = result and upload_to_imgur(result)
# With imgur set up, the test only passes if the upload worked too
ok = result and (link or not os.getenv("IMGUR_CLIENT_ID"))
task = new_task("done" if ok else "failed", result, link)
return jsonify(task)
# =============================
# KEEP ALIVE
# =============================
@app.route("/ping")
def ping():
return "alive"
# =============================
# DASHBOARD
# =============================
@app.route("/")
def dashboard():
return render_template_string("""
<html>
<head>
<script>
async function update(){
let stats = await fetch('/stats').then(r=>r.json());
document.getElementById('cpu').innerText = stats.cpu;
document.getElementById('ram').innerText = stats.ram;
document.getElementById('sent').innerText = stats.sent;
document.getElementById('recv').innerText = stats.recv;
document.getElementById('goku').innerText = stats.file + " | " + stats.goku;
let tasks = await fetch('/tasks').then(r=>r.json());
let html = "";
tasks.slice().reverse().forEach(t=>{
html += `<div class="card">
<b>Task ${t.id}</b><br>
Status: ${t.status}<br>
${t.result ? `<a href="${t.link || t.result}" target="_blank"><img src="${t.result}"></a>` : ""}
</div>`;
});
document.getElementById('tasks').innerHTML = html;
}
setInterval(update, 1000);
</script>
<style>
body { font-family: Arial; background:#111; color:#eee; }
.grid { display:grid; grid-template-columns:repeat(auto-fill,200px); gap:10px; }
.card { background:#222; padding:10px; border-radius:10px; }
img { width:100%; }
</style>
</head>
<body onload="update()">
<h2>Goku Bot Dashboard</h2>
CPU: <span id="cpu"></span>%<br>
RAM: <span id="ram"></span>%<br>
Net Sent: <span id="sent"></span><br>
Net Recv: <span id="recv"></span><br>
Goku: <span id="goku"></span><br><br>
<button onclick="fetch('/test').then(r=>r.json()).then(j=>{ if(j.error) alert(j.error); update(); })">Test Goku</button>
<div id="tasks" class="grid"></div>
</body>
</html>
""")
# =============================
# START THREAD
# =============================
threading.Thread(target=start_reddit_bot, daemon=True).start()
# =============================
# RUN
# =============================
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.getenv("PORT", 10000)))