-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
232 lines (208 loc) · 10.5 KB
/
bot.py
File metadata and controls
232 lines (208 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
import os
import logging
import telebot
import random
import string
import time
from telebot import types
from config import TELEGRAM_TOKEN, CHANNEL_ID, BOT_OWNER_ID, PASTEBIN_API_KEY, URL_SHORTENER_API_KEY
from db import init_db, can_claim_cookie, can_generate_giftcode, is_valid_giftcode, get_random_cookie_file, redeem_giftcode, add_bulk_cookies, add_giftcode, add_user, get_all_users
from utils import generate_gift_code, create_pastebin_entry, shorten_url
from flask import Flask, request, jsonify
from multiprocessing import Process
from requests.exceptions import ConnectionError
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
bot = telebot.TeleBot(TELEGRAM_TOKEN)
bot_owner_uploading = {}
# Ensure necessary directories exist
if not os.path.exists('cookies'):
os.makedirs('cookies')
if not os.path.exists('bulk_cookies'):
os.makedirs('bulk_cookies')
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
logger.debug("Webhook received")
try:
update = telebot.types.Update.de_json(request.stream.read().decode("utf-8"))
logger.debug(f"Update received: {update}")
bot.process_new_updates([update])
except Exception as e:
logger.error(f"Error processing update: {e}")
return jsonify({'ok': True}), 200
@bot.message_handler(commands=['start'])
def send_welcome(message):
user_id = message.from_user.id
logger.debug(f"Received /start command from user {user_id}")
try:
add_user(user_id)
except Exception as e:
logger.error(f"Error adding user {user_id} to the database: {e}")
bot.send_message(message.chat.id, "An error occurred while processing your request. Please try again later.")
return
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(types.KeyboardButton('Generate Gift Code'))
keyboard.add(types.KeyboardButton('Claim Cookies'))
keyboard.add(types.KeyboardButton('Support'))
try:
bot.send_message(message.chat.id, "Welcome! Please choose an option:", reply_markup=keyboard)
logger.debug(f"Sent welcome message to user {user_id}")
except Exception as e:
logger.error(f"Error sending welcome message to user {user_id}: {e}")
# ... (rest of the code remains the same) ...
@bot.message_handler(func=lambda message: message.text == 'Generate Gift Code')
def handle_generate_gift_code(message):
user_id = message.from_user.id
logger.debug(f"Received 'Generate Gift Code' from user {user_id}")
if can_generate_giftcode(user_id):
gift_code = generate_gift_code()
cookie_data = f"Cookie data for {gift_code}" # Replace with actual cookie data generation
pastebin_url = create_pastebin_entry(gift_code, cookie_data, PASTEBIN_API_KEY)
if pastebin_url:
shortened_url = shorten_url(pastebin_url, URL_SHORTENER_API_KEY)
if shortened_url:
add_giftcode(user_id, gift_code)
bot.send_message(message.chat.id, f"Here is your gift code URL: {shortened_url}")
logger.debug(f"Sent gift code URL to user {user_id}")
else:
bot.send_message(message.chat.id, "Failed to shorten URL. Please try again.")
logger.error("Failed to shorten URL")
else:
bot.send_message(message.chat.id, "Failed to create Pastebin entry. Please try again.")
logger.error("Failed to create Pastebin entry")
else:
bot.send_message(message.chat.id, "You can only generate a gift code every 6 hours. Please try again later.")
logger.debug(f"User {user_id} attempted to generate a gift code too soon")
@bot.message_handler(func=lambda message: message.text == 'Claim Cookies')
def handle_claim_cookies(message):
logger.debug(f"Received 'Claim Cookies' from user {message.from_user.id}")
bot.send_message(message.chat.id, "Please enter your gift code.")
@bot.message_handler(func=lambda message: message.text == 'Support')
def handle_support(message):
logger.debug(f"Received 'Support' from user {message.from_user.id}")
bot.send_message(message.chat.id, "Support: @SinwarX, Please share screenshot of cookies not working within 15 minutes after received")
@bot.message_handler(commands=['upload_cookies'])
def handle_bulk_upload_command(message):
if str(message.from_user.id) == str(BOT_OWNER_ID):
logger.debug(f"Received /upload_cookies from bot owner {message.from_user.id}")
bot.send_message(message.chat.id, "Please send the bulk cookies file.")
bot_owner_uploading[message.from_user.id] = 'upload_cookies'
else:
logger.debug(f"Unauthorized user {message.from_user.id} attempted to use /upload_cookies")
bot.send_message(message.chat.id, "You are not authorized to use this command.")
@bot.message_handler(content_types=['document'])
def handle_bulk_upload(message):
if bot_owner_uploading.get(message.from_user.id) == 'upload_cookies':
try:
logger.debug(f"Processing bulk upload from bot owner {message.from_user.id}")
file_info = bot.get_file(message.document.file_id)
downloaded_file = bot.download_file(file_info.file_path)
extension = os.path.splitext(message.document.file_name)[1]
random_name = ''.join(random.choices(string.digits, k=10)) + extension
file_path = f"bulk_cookies/{random_name}"
with open(file_path, 'wb') as new_file:
new_file.write(downloaded_file)
process_bulk_cookies(file_path, random_name)
bot.reply_to(message, "Bulk cookies uploaded and processed.")
bot_owner_uploading[message.from_user.id] = False
except Exception as e:
logger.error(f"Error uploading bulk cookies: {e}")
bot.reply_to(message, f"There was an error uploading the bulk cookies: {e}")
bot_owner_uploading[message.from_user.id] = False
else:
bot.reply_to(message, "You are not authorized to upload cookies.")
def process_bulk_cookies(file_path, file_name):
add_bulk_cookies([(file_name, file_path)])
logger.debug(f"Processed bulk cookies from file {file_path}")
@bot.message_handler(commands=['broadcast'])
def handle_broadcast_command(message):
if str(message.from_user.id) == str(BOT_OWNER_ID):
logger.debug(f"Received /broadcast from bot owner {message.from_user.id}")
bot.send_message(message.chat.id, "Please send the message you want to broadcast.")
bot_owner_uploading[message.from_user.id] = 'broadcast'
else:
logger.debug(f"Unauthorized user {message.from_user.id} attempted to use /broadcast")
bot.send_message(message.chat.id, "You are not authorized to use this command.")
@bot.message_handler(func=lambda message: message.from_user.id in bot_owner_uploading and bot_owner_uploading[message.from_user.id] == 'broadcast')
def handle_broadcast_message(message):
if str(message.from_user.id) == str(BOT_OWNER_ID):
broadcast_message = message.text
users = get_all_users()
logger.debug(f"Broadcasting message to all users from bot owner {message.from_user.id}")
for user_id in users:
try:
bot.send_message(user_id, broadcast_message)
except Exception as e:
logger.error(f"Error sending message to user {user_id}: {e}")
bot.reply_to(message, "Broadcast message sent to all users.")
bot_owner_uploading[message.from_user.id] = False
else:
bot.reply_to(message, "You are not authorized to send broadcast messages.")
@bot.message_handler(func=lambda message: True)
def handle_message(message):
user_id = message.from_user.id
user_text = message.text
logger.debug(f"Received message from user {user_id}: {user_text}")
add_user(user_id)
if is_member(user_id):
if is_valid_giftcode(user_text):
if can_claim_cookie(user_id):
cookie_file = get_random_cookie_file()
if cookie_file:
try:
with open(cookie_file, 'rb') as doc:
bot.send_document(message.chat.id, doc)
redeem_giftcode(user_id, user_text)
logger.debug(f"User {user_id} successfully claimed a cookie")
except FileNotFoundError:
bot.send_message(message.chat.id, "Error: The cookie file was not found. Please try again later.")
logger.error(f"Cookie file not found for user {user_id}")
else:
bot.send_message(message.chat.id, "No cookies available. Please try again later.")
logger.debug(f"No cookies available for user {user_id}")
else:
bot.send_message(message.chat.id, "You can only claim one cookie every 3 hours. Please try again later.")
logger.debug(f"User {user_id} attempted to claim a cookie too soon")
else:
bot.send_message(message.chat.id, "Invalid or already redeemed gift code. Please try again.")
logger.debug(f"User {user_id} provided an invalid or already redeemed gift code")
else:
bot.send_message(message.chat.id, "You must join our channel @dailynetflixcookiesfree to use this bot. Please join and try again.")
logger.debug(f"User {user_id} is not a member of the channel")
def is_member(user_id):
try:
member_status = bot.get_chat_member(chat_id=CHANNEL_ID, user_id=user_id).status
logger.debug(f"Checked membership status for user {user_id}: {member_status}")
return member_status in ["member", "administrator", "creator"]
except telebot.apihelper.ApiTelegramException as e:
logger.error(f"Failed to check membership for user {user_id}: {e}")
return False
@app.route('/health', methods=['GET'])
def health_check():
return 'OK'
def run_flask():
app.run(host='0.0.0.0', port=8000)
def run_telegram():
retry_count = 5
for i in range(retry_count):
try:
logger.debug("Removing webhook")
bot.remove_webhook()
break
except ConnectionError as e:
logger.error(f"Connection error while removing webhook: {e}")
if i < retry_count - 1:
time.sleep(2 ** i)
else:
raise
bot.set_webhook(url='https://claimgiftcode.onrender.com/webhook')
if __name__ == '__main__':
init_db()
# Start Flask and Telegram webhook in separate processes
p1 = Process(target=run_flask)
p2 = Process(target=run_telegram)
p1.start()
p2.start()
p1.join()
p2.join()