Spaces:
Runtime error
Runtime error
Ramiz404 commited on
Commit Β·
1ec8067
1
Parent(s): d32d0a9
Update: Smart Assistant Logic - Quiet mode, Mention/Reply trigger, and Admin Monitoring
Browse files11 unmodified lines12131415161718192021222324252627282930313233343536373839408 unmodified lines495051525354555657582 unmodified lines61626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310411 unmodified lines11611711811912012112212312412511 unmodified lines# Flask for Hugging Face Health Checkapp = Flask(__name__)@app.route('/')def health(): return "AI Master Bot is Running!"def run_flask(): app.run(host='0.0.0.0', port=7860)# TOKENS (Get from Environment Variables)BOT_TOKEN = os.getenv('BOT_TOKEN')HF_TOKEN = os.getenv('HF_TOKEN')bot = telebot.TeleBot(BOT_TOKEN)client = InferenceClient(token=HF_TOKEN)# Admin IDsADMIN_IDS = [1772952626]# AI ModelsTEXT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"IMAGE_MODEL = "stabilityai/stable-diffusion-2-1"# Security ConfigANTI_LINK = TrueANTI_SPAM = Trueuser_last_msg_time = {}# AI Functionsdef get_ai_response(prompt):try:response = client.text_generation(prompt, model=TEXT_MODEL, max_new_tokens=250)8 unmodified linesimage.save(img_byte_arr, format='PNG')img_byte_arr.seek(0)return img_byte_arrexcept Exception as e:return None# Handlers@bot.message_handler(commands=['start', 'help'])def send_welcome(message):markup = types.InlineKeyboardMarkup(row_width=2)2 unmodified linestypes.InlineKeyboardButton("π¨ Image Gen", callback_data="ai_image"),types.InlineKeyboardButton("π‘οΈ Group Security", callback_data="security_info"))bot.send_message(message.chat.id, "π *Ultimate AI & Group Security Bot* π\n\nSelect a service:", parse_mode='Markdown', reply_markup=markup)@bot.callback_query_handler(func=lambda call: True)def callback_query(call):chat_id = call.message.chat.idbot.answer_callback_query(call.id)if call.data == "ai_chat":bot.send_message(chat_id, "π¬ *AI Chat Mode:* Just ask me anything directly!")elif call.data == "ai_image":bot.send_message(chat_id, "π¨ *Image Gen:* Type `/image <prompt>` to generate image.")elif call.data == "security_info":bot.send_message(chat_id, "π‘οΈ *Security:* Anti-Link and Anti-Spam are ACTIVE in groups.")# Image Gen Command@bot.message_handler(commands=['image'])def image_gen(message):prompt = message.text.replace('/image', '').strip()if not prompt:bot.reply_to(message, "Usage: `/image a high-tech robotic cat`", parse_mode='Markdown')returnbot.reply_to(message, "β³ *Generating Image...* Please wait.")img = generate_image(prompt)if img:bot.send_photo(message.chat.id, img, caption=f"π¨ Prompt: {prompt}")else:bot.reply_to(message, "β Image generation failed.")# Monitoring & Security@bot.message_handler(func=lambda message: True, content_types=['text', 'photo', 'video'])def monitor(message):chat_id = message.chat.iduser_id = message.from_user.idtext = message.text or ""# 1. Admin Auto-Replyif user_id in ADMIN_IDS and ("bot" in text.lower() or "hello" in text.lower()):bot.reply_to(message, "π Welcome Boss! I am monitoring everything. Let me know if you need help.")return# 2. Group Security (Anti-Link)if ANTI_LINK and message.chat.type != 'private':11 unmodified linesreturnuser_last_msg_time[user_id] = now# 4. Private AI Chatif message.chat.type == 'private' and not text.startswith('/'):bot.send_chat_action(chat_id, 'typing')bot.reply_to(message, get_ai_response(text))if __name__ == '__main__':Thread(target=run_flask).start()11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243448 unmodified lines535455565758596061622 unmodified lines656667686970717273747576777879808182838485868788899091929394959611 unmodified lines10810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514611 unmodified lines# Flask for Hugging Face Health Checkapp = Flask(__name__)@app.route('/')def health(): return "AI Smart Assistant is Running!"def run_flask(): app.run(host='0.0.0.0', port=7860)# TOKENS (Environment Variables theke asche)BOT_TOKEN = os.getenv('BOT_TOKEN')HF_TOKEN = os.getenv('HF_TOKEN')bot = telebot.TeleBot(BOT_TOKEN)client = InferenceClient(token=HF_TOKEN)# Admin IDs (Apnar ID ekhane add kora jete pare)ADMIN_IDS = [1772952626] # Sample, replace with yours if needed# AI ModelsTEXT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"IMAGE_MODEL = "stabilityai/stable-diffusion-2-1"# Get Bot Username for Mention CheckBOT_USERNAME = bot.get_me().username# Security ConfigANTI_LINK = TrueANTI_SPAM = Trueuser_last_msg_time = {}# --- AI FUNCTIONS ---def get_ai_response(prompt):try:response = client.text_generation(prompt, model=TEXT_MODEL, max_new_tokens=250)8 unmodified linesimage.save(img_byte_arr, format='PNG')img_byte_arr.seek(0)return img_byte_arrexcept: return None# --- HANDLERS ---@bot.message_handler(commands=['start', 'help'])def send_welcome(message):markup = types.InlineKeyboardMarkup(row_width=2)2 unmodified linestypes.InlineKeyboardButton("π¨ Image Gen", callback_data="ai_image"),types.InlineKeyboardButton("π‘οΈ Group Security", callback_data="security_info"))bot.send_message(message.chat.id, f"π *Smart AI Assistant (@{BOT_USERNAME})* π\n\nAmi apnake AI help ebong Group Security dite ready. Select a service below:", parse_mode='Markdown', reply_markup=markup)@bot.callback_query_handler(func=lambda call: True)def callback_query(call):chat_id = call.message.chat.idbot.answer_callback_query(call.id)if call.data == "ai_chat":bot.send_message(chat_id, "π¬ *AI Chat Mode:* Private chat-e direct message pathan, group-e amake mention korun!")elif call.data == "ai_image":bot.send_message(chat_id, "π¨ *Image Gen:* Type `/image <prompt>`")elif call.data == "security_info":bot.send_message(chat_id, "π‘οΈ *Security:* Anti-Link, Anti-Spam are ACTIVE. Mention me for help.")# --- AI MONITORING & SMART REPLY ---@bot.message_handler(func=lambda message: True, content_types=['text', 'photo', 'video'])def monitor_smartly(message):chat_id = message.chat.iduser_id = message.from_user.idtext = message.text or ""# 1. Admin Monitoring & Auto-Replyif user_id in ADMIN_IDS:if "hello bot" in text.lower():bot.reply_to(message, "π Welcome Boss! Ami shob kichu secretly monitor korchi. Kono help lagle bolun.")return# 2. Group Security (Anti-Link)if ANTI_LINK and message.chat.type != 'private':11 unmodified linesreturnuser_last_msg_time[user_id] = now# 4. Smart Reply (Only Mentioned, Replied, or Private)is_private = message.chat.type == 'private'is_mentioned = f"@{BOT_USERNAME}" in textis_replied = message.reply_to_message and message.reply_to_message.from_user.username == BOT_USERNAME# Special Case: Someone mentions/replies to Adminis_admin_mentioned = any(str(admin) in text for admin in ADMIN_IDS)is_admin_replied = message.reply_to_message and message.reply_to_message.from_user.id in ADMIN_IDSif (is_private or is_mentioned or is_replied or is_admin_mentioned or is_admin_replied) and not text.startswith('/'):# Don't respond to own messagesif message.from_user.username == BOT_USERNAME:returnbot.send_chat_action(chat_id, 'typing')# Simple Logic: If admin is mentioned/replied, bot helpsif is_admin_mentioned or is_admin_replied:prompt = f"Someone is asking about the admin. User said: {text}. Help them professionally."else:prompt = textresponse = get_ai_response(prompt)bot.reply_to(message, response)# Image Gen Command@bot.message_handler(commands=['image'])def image_gen(message):prompt = message.text.replace('/image', '').strip()if not prompt: returnbot.reply_to(message, "β³ Generating...")img = generate_image(prompt)if img: bot.send_photo(message.chat.id, img)else: bot.reply_to(message, "β Failed.")if __name__ == '__main__':Thread(target=run_flask).start()
app.py+55-34