noranisa commited on
Commit
e56b60e
Β·
verified Β·
1 Parent(s): d852d89

Update services/reddit.py

Browse files
Files changed (1) hide show
  1. services/reddit.py +14 -52
services/reddit.py CHANGED
@@ -1,73 +1,35 @@
1
  import praw
2
- import os
3
 
4
- # πŸ” Ambil dari environment (WAJIB untuk HuggingFace)
5
- CLIENT_ID = os.getenv("REDDIT_CLIENT_ID")
6
- CLIENT_SECRET = os.getenv("REDDIT_CLIENT_SECRET")
7
- USER_AGENT = os.getenv("REDDIT_USER_AGENT", "sentiment-analysis-app")
8
-
9
- # πŸ” Debug (optional, bisa dihapus nanti)
10
- print("Reddit CLIENT_ID:", CLIENT_ID)
11
-
12
- # πŸ”§ Inisialisasi Reddit
13
  def init_reddit():
14
  try:
15
- if not CLIENT_ID or not CLIENT_SECRET:
16
- print("❌ Reddit API key tidak ditemukan")
17
  return None
18
 
19
- reddit = praw.Reddit(
20
- client_id=CLIENT_ID,
21
- client_secret=CLIENT_SECRET,
22
- user_agent=USER_AGENT
23
  )
24
-
25
- return reddit
26
-
27
- except Exception as e:
28
- print("❌ Gagal init Reddit:", e)
29
  return None
30
 
31
-
32
- # πŸš€ Ambil komentar Reddit
33
  def get_reddit_comments(keyword, limit=30):
34
  comments = []
35
-
36
  reddit = init_reddit()
37
 
38
  if reddit is None:
39
- print("⚠️ Reddit tidak aktif")
40
  return comments
41
 
42
  try:
43
- print(f"πŸ”Ž Cari Reddit: {keyword}")
44
-
45
- # πŸ”₯ Search subreddit global
46
- for submission in reddit.subreddit("all").search(keyword, limit=3):
47
-
48
- try:
49
- submission.comments.replace_more(limit=0)
50
-
51
- for comment in submission.comments.list():
52
- text = comment.body
53
-
54
- # filter sederhana
55
- if text and len(text) > 10:
56
- comments.append(text)
57
-
58
- if len(comments) >= limit:
59
- break
60
-
61
  if len(comments) >= limit:
62
  break
63
-
64
- except Exception as e:
65
- print("⚠️ Error di submission:", e)
66
- continue
67
-
68
- except Exception as e:
69
- print("❌ Reddit error:", e)
70
-
71
- print(f"βœ… Total komentar Reddit: {len(comments)}")
72
 
73
  return comments
 
1
  import praw
2
+ from config import REDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET, REDDIT_USER_AGENT
3
 
 
 
 
 
 
 
 
 
 
4
  def init_reddit():
5
  try:
6
+ if not REDDIT_CLIENT_ID:
 
7
  return None
8
 
9
+ return praw.Reddit(
10
+ client_id=REDDIT_CLIENT_ID,
11
+ client_secret=REDDIT_CLIENT_SECRET,
12
+ user_agent=REDDIT_USER_AGENT
13
  )
14
+ except:
 
 
 
 
15
  return None
16
 
 
 
17
  def get_reddit_comments(keyword, limit=30):
18
  comments = []
 
19
  reddit = init_reddit()
20
 
21
  if reddit is None:
 
22
  return comments
23
 
24
  try:
25
+ for submission in reddit.subreddit("all").search(keyword, limit=2):
26
+ submission.comments.replace_more(limit=0)
27
+ for c in submission.comments.list():
28
+ if len(c.body) > 10:
29
+ comments.append(c.body)
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  if len(comments) >= limit:
31
  break
32
+ except:
33
+ pass
 
 
 
 
 
 
 
34
 
35
  return comments