Ramiz404
Update: Smart Assistant Logic - Quiet mode, Mention/Reply trigger, and Admin Monitoring
1ec8067
Raw History Blame Contribute Delete
5.39 kB
import telebot
import requests
import os
import io
import time
from telebot import types
from threading import Thread
from flask import Flask
from huggingface_hub import InferenceClient
from PIL import Image
# Flask for Hugging Face Health Check
app = 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 Models
TEXT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"
IMAGE_MODEL = "stabilityai/stable-diffusion-2-1"
# Get Bot Username for Mention Check
BOT_USERNAME = bot.get_me().username
# Security Config
ANTI_LINK = True
ANTI_SPAM = True
user_last_msg_time = {}
# --- AI FUNCTIONS ---
def get_ai_response(prompt):
try:
response = client.text_generation(prompt, model=TEXT_MODEL, max_new_tokens=250)
return response
except Exception as e:
return f"AI Error: {str(e)}"
def generate_image(prompt):
try:
image = client.text_to_image(prompt, model=IMAGE_MODEL)
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format='PNG')
img_byte_arr.seek(0)
return img_byte_arr
except: return None
# --- HANDLERS ---
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
markup = types.InlineKeyboardMarkup(row_width=2)
markup.add(
types.InlineKeyboardButton("πŸ€– AI Chat", callback_data="ai_chat"),
types.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.id
bot.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.id
user_id = message.from_user.id
text = message.text or ""
# 1. Admin Monitoring & Auto-Reply
if 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':
if "http" in text or "t.me/" in text:
if user_id not in ADMIN_IDS:
bot.delete_message(chat_id, message.message_id)
bot.send_message(chat_id, f"🚫 *No Links Allowed!* @{message.from_user.username}", parse_mode='Markdown')
return
# 3. Anti-Spam
if ANTI_SPAM:
now = time.time()
if now - user_last_msg_time.get(user_id, 0) < 0.8:
bot.delete_message(chat_id, message.message_id)
return
user_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 text
is_replied = message.reply_to_message and message.reply_to_message.from_user.username == BOT_USERNAME
# Special Case: Someone mentions/replies to Admin
is_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_IDS
if (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 messages
if message.from_user.username == BOT_USERNAME:
return
bot.send_chat_action(chat_id, 'typing')
# Simple Logic: If admin is mentioned/replied, bot helps
if is_admin_mentioned or is_admin_replied:
prompt = f"Someone is asking about the admin. User said: {text}. Help them professionally."
else:
prompt = text
response = 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: return
bot.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()
bot.infinity_polling()