-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
317 lines (283 loc) · 9.77 KB
/
main.py
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
import os
import requests
import json
import traceback
from dotenv import load_dotenv
import telebot
import psycopg2
from flask import Flask,request,jsonify
app = Flask(__name__)
load_dotenv()
ENV = os.environ.get('ENV')
BOT_TOKEN = os.environ.get('BOT_TOKEN')
DB_HOST = os.environ.get('DB_HOST')
DB_PORT = os.environ.get('DB_PORT')
DB_USER = os.environ.get('DB_USER')
DB_PASS = os.environ.get('DB_PASS')
DB_NAME = os.environ.get('DB_NAME')
API_URL = os.environ.get('API_URL')
API_PROVIDER = os.environ.get('API_PROVIDER')
IFRAME_LINK = os.environ.get('IFRAME_LINK')
def initDb():
db = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASS,
database=DB_NAME
)
return db
mydb = initDb()
try:
cur = mydb.cursor()
cur.execute('SELECT 1')
print("Berhasil terhubung ke database")
except Exception as err:
print(err)
print("Gagal terhubung ke database")
pass
def checkUser(user_id):
global mydb
try:
mycursor = mydb.cursor()
except psycopg2.InterfaceError as err:
print(err)
mydb = initDb()
mycursor = mydb.cursor()
try:
sql = "SELECT * FROM users WHERE user_id = %s"
val = [user_id]
mycursor.execute(sql, val)
myresult = mycursor.fetchone()
mydb.commit()
return myresult
except Exception as err:
print("Error Check User : ")
print(err)
return None
def insertUser(user_id,username):
global mydb
cek = checkUser(user_id)
if cek is None:
try:
mycursor = mydb.cursor()
except psycopg2.InterfaceError as err:
print(err)
mydb = initDb()
mycursor = mydb.cursor()
try:
sql = "INSERT INTO users (user_id, username) VALUES (%s, %s)"
val = (user_id,str(username))
mycursor.execute(sql, val)
mydb.commit()
return True
except Exception as err:
print("Error Insert User : ")
print(err)
return False
else:
return False
def getHistoryById(id):
global mydb
try:
mycursor = mydb.cursor()
except Exception as err:
print(err)
mydb = initDb()
mycursor = mydb.cursor()
sql = "SELECT * FROM history_film WHERE id = %s"
val = (id,)
mycursor.execute(sql, val)
myresult = mycursor.fetchone()
mydb.commit()
return myresult
def getHistoryByLink(link):
global mydb
try:
mycursor = mydb.cursor()
except Exception as err:
print(err)
mydb = initDb()
mycursor = mydb.cursor()
sql = "SELECT * FROM history_film WHERE link = %s"
val = (link,)
mycursor.execute(sql, val)
myresult = mycursor.fetchone()
mydb.commit()
return myresult
def insertHistory(link,message_id):
global mydb
cek = getHistoryByLink(link)
if cek is None:
try:
mycursor = mydb.cursor()
except psycopg2.InterfaceError as err:
print(err)
mydb = initDb()
mycursor = mydb.cursor()
sql = "INSERT INTO history_film (link, message_id) VALUES (%s, %s) RETURNING id;"
val = (link,message_id)
mycursor.execute(sql, val)
data = mycursor.fetchone()
mydb.commit()
id_of_new_row = data[0]
return id_of_new_row
else:
return cek[0]
bot = telebot.TeleBot(BOT_TOKEN, threaded=False)
def searchMovie(movieName):
print("Start search movie... ",movieName)
url = API_URL+"/search?query=" + str(movieName) + "&providers[]="+API_PROVIDER
response = requests.get(url)
if response.status_code != 200:
print("Error : "+str(response.text))
return []
else:
data = response.json()
return data
def detailMovie(movieLink):
url = API_URL + "/get?link=" + movieLink + "/&provider="+API_PROVIDER
print(url)
response = requests.get(url)
data = response.json()
return data
def cleanLink(link):
return link.replace("/api/get?link=","").replace("/&provider="+API_PROVIDER,"")
@bot.message_handler(commands=['search'])
def search(message):
print(message.from_user.id,message.from_user.username)
print("Search movie... ",message.text)
movieName = message.text.replace("/search ", "")
if movieName == "" or movieName == "/search":
bot.reply_to(message, 'Silahkan ketik /search "judul film" (tanpa tanda kutip) untuk mencari film, contoh /search avenger')
return
bot.reply_to(message, "Mencari film "+movieName+" silahkan tunggu...")
data = searchMovie(movieName)
data5 = data[:5]
if len(data5) == 0:
bot.reply_to(message, "Film "+movieName+" tidak ditemukan")
return
for i in data5:
link = cleanLink(i['link'])
id = insertHistory(link,message.id)
markup = telebot.types.InlineKeyboardMarkup()
markup.add(telebot.types.InlineKeyboardButton(text="Link Stream 🎥", callback_data="/detail "+str(id)))
try:
bot.send_photo(message.chat.id, i['thumb'], caption=i['title'], reply_markup=markup,parse_mode="Markdown")
except Exception as err:
print(err)
bot.send_message(message.chat.id, "Link Stream "+i['title'],reply_markup=markup,parse_mode="Markdown")
@bot.message_handler(commands=['start', 'hello','help'])
def send_welcome(message):
print(message.from_user.id,message.from_user.username)
try:
insertUser(message.from_user.id,message.from_user.username)
except Exception as err:
print(err)
print(err.__traceback__)
traceback.print_tb(err.__traceback__)
bot.reply_to(message, """
Selamat datang di bot """+API_PROVIDER+"""
Ketik /search "judul film" (tanpa tanda kutip) untuk mencari film, contoh /search avenger
""")
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
if call.data.startswith("/detail"):
# print(call.text)
try:
id = call.data.replace("/detail ","")
history = getHistoryById(id)
link = history[2]
print("Link : "+link)
bot.send_message(call.message.chat.id, "Mencari link streaming film silahkan tunggu...")
data = detailMovie(link)
if "episode" in data:
markup = telebot.types.InlineKeyboardMarkup()
for e in data['episode']:
link = cleanLink(e['link'])
id = insertHistory(link,call.message.id)
markup.add(telebot.types.InlineKeyboardButton(text="Eps "+e['title'], callback_data="/detail "+str(id)))
bot.send_message(call.message.chat.id, data['title'] + " Episode : ", reply_markup=markup,parse_mode="Markdown")
else:
linkMessage = "Link Streaming "+data['title']+" (Tidak Menjamin Semua Link Work): \n"
markup = telebot.types.InlineKeyboardMarkup()
for s in data['stream']:
if s['detail'] == None or s['detail'] == "" or s['detail'] == "None" or s['detail'] == "null":
streamLink = s['link']
# if steramLink start with //
if streamLink.startswith("//"):
streamLink = "https:"+streamLink
markup.add(telebot.types.InlineKeyboardButton(text=s['title'], url=streamLink))
else:
if "/iframe?link=" in s['detail']:
link_frame = IFRAME_LINK+s['detail']
else:
link_frame = s['detail']
markup.add(telebot.types.InlineKeyboardButton(text=s['title'], url=link_frame))
bot.send_message(call.message.chat.id, linkMessage, reply_markup=markup,parse_mode="Markdown")
except Exception as err:
print(err)
bot.send_message(call.message.chat.id, "Maaf terjadi kesalahan, silahkan coba lagi")
WEB_PORT = os.environ.get('WEB_PORT', '5000')
WEB_URL = os.environ.get('WEB_URL')
HOOK_URL = WEB_URL + '/' + BOT_TOKEN
@app.route('/' + BOT_TOKEN, methods=['POST'])
def getMessage():
json_string = request.get_data().decode('utf-8')
update = telebot.types.Update.de_json(json_string)
bot.process_new_updates([update])
return "!", 200
@app.route("/")
def webhook():
bot.remove_webhook()
drop_pending_updates = False
if request.args.get("drop_pending_updates"):
drop_pending_updates = True
bot.set_webhook(url=HOOK_URL,drop_pending_updates=drop_pending_updates)
return "!", 200
# check if webhook is working
@app.route("/status")
def status():
info = bot.get_webhook_info()
result = {
"url": info.url,
"last_error_date": info.last_error_date,
"last_error_message": info.last_error_message,
"pending_update_count": info.pending_update_count,
}
return jsonify(result),200
# route to check status database
@app.route("/dbstatus")
def dbstatus():
try:
cur = mydb.cursor()
cur.execute('SELECT 1')
return "Database connected",200
except Exception as err:
return "Database not connected",500
# route list users
@app.route('/users')
def users():
try:
mycursor = mydb.cursor()
except Exception as err:
print(err)
mydb = initDb()
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM users")
myresult = mycursor.fetchall()
mydb.commit()
return jsonify(myresult),200
@app.route("/stop")
def stop():
bot.remove_webhook()
bot.stop_polling()
return "Bot stopped",200
def main():
if ENV != "production":
bot.remove_webhook()
bot.infinity_polling()
else:
app.run(host="0.0.0.0", port=WEB_PORT)
if __name__ == "__main__":
main()