-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
183 lines (126 loc) · 4.6 KB
/
Copy pathmain.py
File metadata and controls
183 lines (126 loc) · 4.6 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
from fastapi import FastAPI, Request
from pydantic import BaseModel
from dotenv import load_dotenv
import os
import requests
from ai_model import generate_reply
load_dotenv()
VERIFY_TOKEN = os.getenv("VERIFY_TOKEN")
app = FastAPI()
class SendMessageRequest(BaseModel):
recipient_id: str
message_text: str
@app.get("/")
def read_root():
return {"Server": "Running"}
#------------------Verify Webhook----------------------
@app.get("/webhook")
async def verify(
hub_mode: str = None,
hub_verify_token: str = None,
hub_challenge: str = None
):
if hub_verify_token == VERIFY_TOKEN:
return int(hub_challenge)
return "error"
#--------------Receive Instagram Messages-------------------
processed_comments = set()
@app.post("/webhook")
async def receive_message(request: Request):
data = await request.json()
print("Incoming:", data)
try:
entry_list = data.get("entry")
if not entry_list:
return {"status": "no entry"}
for entry in entry_list:
# ===== DMs =====
# messaging_list = entry.get("messaging")
# if messaging_list:
# for msg_event in messaging_list:
# if msg_event.get("message", {}).get("is_echo"):
# continue
# sender_id = msg_event.get("sender", {}).get("id")
# text = msg_event.get("message", {}).get("text")
# if not sender_id or not text:
# continue
# print(f"User (DM): {text}")
# reply = await generate_reply(text)
# send_instagram_message(sender_id, reply)
# print(f"Bot: {reply}")
# ===== Comments =====
if entry.get("changes"):
for change in entry.get("changes"):
if change.get("field") != "comments":
continue
value = change.get("value", {})
comment_id = value.get("id")
text = value.get("text")
username = value.get("from", {}).get("username")
commenter_id = value.get("from", {}).get("id")
# Ignore replies (prevents loops)
if value.get("parent_id"):
continue
# Deduplicate
if comment_id in processed_comments:
continue
processed_comments.add(comment_id)
# Ignore bot itself
if username == "_clinqo":
continue
if not text:
continue
print(f"{username} (comment): {text}")
reply = await generate_reply(text)
send_instagram_comment_reply(comment_id, reply)
print("Comment ID:", comment_id)
print(f"Bot (comment reply): {reply}")
except Exception as e:
print("Error:", str(e))
return {"status": "ok"}
#------------------Send Reply to Instagram----------------------
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
import requests
def send_instagram_message(recipient_id, text):
url = "https://graph.facebook.com/v19.0/1107771282409772/messages"
payload = {
"recipient": {
"id": recipient_id
},
"message": {
"text": text
}
}
params = {
"access_token": ACCESS_TOKEN # Page token
}
print("Sending to:", recipient_id)
print("Payload:", payload)
response = requests.post(url, json=payload, params=params)
print("Send response:", response.text)
#------------------Send comment reply to Instagram----------------------
def send_instagram_comment_reply(comment_id: str, message: str):
"""
Sends a reply to an Instagram comment using Meta Graph API.
Args:
comment_id (str): ID of the Instagram comment
message (str): Reply text
Returns:
dict: API response (success or error)
"""
url = f"https://graph.facebook.com/v19.0/{comment_id}/replies"
params = {
"message": message,
"access_token": ACCESS_TOKEN
}
try:
response = requests.post(url, params=params)
data = response.json()
if response.status_code == 200:
print("✅ Reply sent successfully")
else:
print("❌ Error:", data)
return data
except Exception as e:
print("⚠️ Exception occurred:", str(e))
return {"error": str(e)}