help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
telegram-bot
RSK World
telegram-bot
Telegram Bot - Python + Telegram Bot API + SQLite + PHP Dashboard + Bot Commands + Automation
telegram-bot
  • __pycache__
  • assets
  • .env1.5 KB
  • .gitignore845 B
  • CHANGELOG.md3.8 KB
  • LICENSE1.3 KB
  • LICENSE.txt1.3 KB
  • PROJECT_STATUS.md3.2 KB
  • README.md6.7 KB
  • RELEASE_NOTES.md5.5 KB
  • SETUP.md1.5 KB
  • bot.db0 B
  • bot.py3.9 KB
  • config.py773 B
  • dashboard.php8.1 KB
  • database.py7.5 KB
  • handlers.py19.5 KB
  • index.html6.6 KB
  • project_info.php1.5 KB
  • requirements.txt564 B
  • setup.py3.1 KB
  • utils.py8.9 KB
handlers.py
handlers.py
Raw Download
Find: Go to:

# Project: Telegram Bot
# Author: Molla Samser
# Designer & Tester: Rima Khatun
# Website: https://rskworld.in
# Contact: hello@rskworld.in | +91 93305 39277
# Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
# Copyright: Ā© 2026 RSK World. All rights reserved.

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes, ConversationHandler, CommandHandler, MessageHandler, filters
import config
import database
import utils

# States for Feedback Conversation
FEEDBACK_MESSAGE = 1

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Send a message when the command /start is issued."""
    user = update.effective_user
    # Add user to database
    database.add_user(user)
    
    welcome_message = (
        f"Hi {user.mention_html()}! \n"
        "I am a Pro Telegram Bot created by RSK World. \n"
        "I have advanced features like database tracking, QR codes, and more.\n\n"
        "Use /help to see what I can do."
    )
    
    keyboard = [
        [
            InlineKeyboardButton("Visit Website", url="https://rskworld.in"),
            InlineKeyboardButton("Contact Us", url="https://rskworld.in/contact.php"),
        ],
        [
            InlineKeyboardButton("Help", callback_data="help"),
        ]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    
    await update.message.reply_html(welcome_message, reply_markup=reply_markup)

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Send a message when the command /help is issued."""
    help_text = (
        "<b>šŸ“š Available Commands:</b>\n\n"
        "<b>Basic Commands:</b>\n"
        "/start - Start the bot\n"
        "/help - Show this help message\n"
        "/features - List bot features\n"
        "/contact - Get contact info\n"
        "/profile - View your profile & stats\n"
        "/leaderboard - View top users\n\n"
        "<b>Utility Commands:</b>\n"
        "/qr <text> - Generate a QR code\n"
        "/speak <text> - Convert text to speech\n"
        "/translate <lang> <text> - Translate text\n"
        "/pdf <text> - Create PDF from text\n"
        "/weather <city> - Get weather info\n\n"
        "<b>Advanced Features:</b>\n"
        "/ai <question> - Ask AI assistant\n"
        "/remind <minutes> <message> - Set reminder\n"
        "/password [length] - Generate password\n"
        "/shorten <url> - Shorten URL\n"
        "/calc <expression> - Calculator\n"
        "/convert <value> <from> <to> - Unit converter\n"
        "/news [topic] - Get news\n"
        "/summarize <text> - Summarize text\n\n"
        "<b>Other:</b>\n"
        "/feedback - Send feedback to us\n"
        "/export - Export database (Admin only)"
    )
    await update.message.reply_html(help_text)

async def features_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """List features"""
    features = (
        "<b>šŸ¤– Bot Features:</b>\n\n"
        "<b>Core Features:</b>\n"
        "• Command handling\n"
        "• Inline keyboards\n"
        "• File sharing capability\n"
        "• Group chat support\n"
        "• Persistent Database\n"
        "• Admin Dashboard\n\n"
        "<b>Utility Features:</b>\n"
        "• QR Code Generator\n"
        "• Text to Speech\n"
        "• PDF Creator\n"
        "• Language Translator\n"
        "• Weather Info\n\n"
        "<b>Advanced Features:</b>\n"
        "• AI Assistant (OpenAI integration)\n"
        "• Task Reminders\n"
        "• Password Generator\n"
        "• URL Shortener\n"
        "• Calculator\n"
        "• Unit Converter\n"
        "• News Fetcher\n"
        "• Text Summarizer\n"
        "• User Leaderboard\n"
        "• XP & Leveling System"
    )
    await update.message.reply_html(features)

async def contact_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Send contact info"""
    contact_info = (
        "<b>Contact RSK World:</b>\n"
        "Email: hello@rskworld.in\n"
        "Phone: +91 93305 39277\n"
        "Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India"
    )
    await update.message.reply_html(contact_info)

async def qr_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Generate a QR code from arguments."""
    try:
        database.update_user_activity(update.effective_user.id)
        if not context.args:
            await update.message.reply_text("Please provide text for the QR code.\nUsage: /qr <text>")
            return

        text = " ".join(context.args)
        qr_image = utils.generate_qr(text)
        if qr_image:
            await update.message.reply_photo(photo=qr_image, caption=f"QR Code for: {text}")
        else:
            await update.message.reply_text("Error generating QR code.")
    except Exception as e:
        await update.message.reply_text(f"Error: {str(e)}")

async def speak_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Convert text to speech."""
    database.update_user_activity(update.effective_user.id)
    if not context.args:
        await update.message.reply_text("Please provide text to speak.\nUsage: /speak <text>")
        return
    
    text = " ".join(context.args)
    audio = utils.text_to_speech_file(text)
    if audio:
        await update.message.reply_voice(voice=audio)
    else:
        await update.message.reply_text("Sorry, I couldn't generate the voice note.")

async def translate_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Translate text."""
    database.update_user_activity(update.effective_user.id)
    if len(context.args) < 2:
        await update.message.reply_text("Usage: /translate <target_lang_code> <text>\nExample: /translate hi Hello")
        return
    
    target_lang = context.args[0]
    text = " ".join(context.args[1:])
    translated = utils.translate_text(text, target_lang)
    await update.message.reply_text(f"šŸŒ <b>Translation ({target_lang}):</b>\n{translated}", parse_mode='HTML')

async def pdf_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Generate a PDF from text."""
    database.update_user_activity(update.effective_user.id)
    if not context.args:
        await update.message.reply_text("Please provide text for the PDF.\nUsage: /pdf <text>")
        return
    
    text = " ".join(context.args)
    pdf_file = utils.create_pdf(text)
    if pdf_file:
        await update.message.reply_document(document=pdf_file, filename="note.pdf", caption="šŸ“„ Your generated PDF")
    else:
        await update.message.reply_text("Sorry, I couldn't generate the PDF.")

async def profile_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Show user profile and ranking."""
    user_id = update.effective_user.id
    data = database.get_user_rank(user_id)
    
    if data:
        name, msg_count, xp = data
        # Simple level calculation: Level = (XP // 100) + 1
        level = (xp // 100) + 1
        profile_text = (
            f"šŸ‘¤ <b>User Profile: {name}</b>\n"
            f"━━━━━━━━━━━━━━━━━━\n"
            f"šŸ… Level: {level}\n"
            f"⭐ Total XP: {xp}\n"
            f"šŸ’¬ Messages Sent: {msg_count}\n"
            f"━━━━━━━━━━━━━━━━━━\n"
            f"Keep chatting to level up!"
        )
        await update.message.reply_html(profile_text)
    else:
        await update.message.reply_text("Profile not found. Send /start first!")

async def ai_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Get AI response."""
    database.update_user_activity(update.effective_user.id)
    if not context.args:
        await update.message.reply_text("Please provide a question for the AI.\nUsage: /ai <your question>")
        return
    
    query = " ".join(context.args)
    response = utils.ai_response(query)
    await update.message.reply_text(f"šŸ¤– <b>AI Assistant:</b>\n{response}", parse_mode='HTML')

async def remind_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Set a reminder."""
    database.update_user_activity(update.effective_user.id)
    if len(context.args) < 2:
        await update.message.reply_text("Usage: /remind <minutes> <message>\nExample: /remind 5 Drink water")
        return
    
    try:
        minutes = int(context.args[0])
        message = " ".join(context.args[1:])
        from datetime import datetime, timedelta
        remind_at = (datetime.now() + timedelta(minutes=minutes)).strftime('%Y-%m-%d %H:%M:%S')
        
        database.add_reminder(update.effective_user.id, message, remind_at)
        await update.message.reply_text(f"ā° Reminder set for {minutes} minute(s) from now.")
    except ValueError:
        await update.message.reply_text("Please provide a valid number of minutes.")

async def weather_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Get weather info."""
    database.update_user_activity(update.effective_user.id)
    if not context.args:
        await update.message.reply_text("Please provide a city name.\nUsage: /weather <city>")
        return
    
    city = " ".join(context.args)
    response = utils.get_weather(city)
    await update.message.reply_text(response, parse_mode='HTML')

async def export_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Export database (Admin only)."""
    if update.effective_user.id != config.ADMIN_ID:
        await update.message.reply_text("ā›” Permission denied.")
        return
    
    await update.message.reply_text("šŸ“¦ Exporting database...")
    try:
        with open(config.DB_NAME, 'rb') as db_file:
            await update.message.reply_document(document=db_file, filename=config.DB_NAME, caption="Database Export")
    except Exception as e:
        await update.message.reply_text(f"Error exporting database: {e}")

async def check_reminders(context: ContextTypes.DEFAULT_TYPE):
    """Checks for due reminders and sends them."""
    reminders = database.get_pending_reminders()
    for rid, uid, msg in reminders:
        try:
            await context.bot.send_message(chat_id=uid, text=f"ā° <b>Reminder:</b>\n{msg}", parse_mode='HTML')
            database.update_reminder_status(rid, 'sent')
        except Exception as e:
            print(f"Error sending reminder {rid}: {e}")

async def message_activity_tracker(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Track user activity on every text message."""
    try:
        if update.message and update.message.text and not update.message.text.startswith('/'):
            database.update_user_activity(update.effective_user.id)
    except Exception as e:
        # Silently log error for activity tracking
        pass

async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle document uploads."""
    try:
        database.update_user_activity(update.effective_user.id)
        document = update.message.document
        file_info = await context.bot.get_file(document.file_id)
        
        file_size_mb = document.file_size / (1024 * 1024)
        await update.message.reply_text(
            f"šŸ“„ <b>File Received:</b>\n"
            f"Name: {document.file_name}\n"
            f"Size: {file_size_mb:.2f} MB\n"
            f"Type: {document.mime_type}\n\n"
            f"File ID: <code>{document.file_id}</code>",
            parse_mode='HTML'
        )
    except Exception as e:
        await update.message.reply_text(f"Error processing file: {str(e)}")

async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle photo uploads."""
    try:
        database.update_user_activity(update.effective_user.id)
        photo = update.message.photo[-1]  # Get largest photo
        file_info = await context.bot.get_file(photo.file_id)
        
        await update.message.reply_text(
            f"šŸ“· <b>Photo Received:</b>\n"
            f"Size: {photo.width}x{photo.height}\n"
            f"File Size: {photo.file_size / 1024:.2f} KB\n\n"
            f"Use /help to see image processing commands.",
            parse_mode='HTML'
        )
    except Exception as e:
        await update.message.reply_text(f"Error processing photo: {str(e)}")

# --- Admin Commands ---
async def stats_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Show bot statistics (Admin Only)."""
    user_id = update.effective_user.id
    if user_id != config.ADMIN_ID:
        await update.message.reply_text("ā›” Permission denied.")
        return

    stats = database.get_stats()
    stats_text = (
        f"šŸ“Š <b>Bot Statistics</b>\n"
        f"━━━━━━━━━━━━━━━━━━\n"
        f"šŸ‘„ Total Users: {stats['user_count']}\n"
        f"šŸ’¬ Total Messages: {stats['total_messages']}\n"
        f"⭐ Total XP: {stats['total_xp']}\n"
        f"šŸ’­ Feedbacks: {stats['feedback_count']}\n"
        f"ā° Reminders: {stats['reminder_count']}"
    )
    await update.message.reply_html(stats_text)

async def broadcast_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Broadcast message to all users (Admin Only)."""
    user_id = update.effective_user.id
    if user_id != config.ADMIN_ID:
        await update.message.reply_text("ā›” Permission denied.")
        return

    if not context.args:
        await update.message.reply_text("Usage: /broadcast <message>")
        return

    message = " ".join(context.args)
    users = database.get_all_users()
    count = 0
    
    await update.message.reply_text(f"šŸš€ Starting broadcast to {len(users)} users...")
    
    for uid in users:
        try:
            await context.bot.send_message(chat_id=uid, text=f"šŸ“¢ <b>Announcement:</b>\n{message}", parse_mode='HTML')
            count += 1
        except Exception:
            pass # User might have blocked the bot
            
    await update.message.reply_text(f"āœ… Broadcast sent to {count} users.")

# --- Feedback Conversation ---
async def start_feedback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Starts the feedback conversation."""
    await update.message.reply_text("Please send your feedback or suggestion in the next message.\nType /cancel to cancel.")
    return FEEDBACK_MESSAGE

async def receive_feedback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Stores the feedback."""
    message = update.message.text
    user = update.effective_user
    database.save_feedback(user.id, message)
    await update.message.reply_text("Thank you! Your feedback has been recorded.")
    return ConversationHandler.END

async def cancel_feedback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Cancels the feedback conversation."""
    await update.message.reply_text("Feedback cancelled.")
    return ConversationHandler.END

async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Parses the CallbackQuery and updates the message text."""
    query = update.callback_query
    await query.answer()

    if query.data == "help":
        await query.edit_message_text(text="Here is the help section... (Use /help for full details)")

# --- Advanced Features ---
async def password_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Generate a random password."""
    database.update_user_activity(update.effective_user.id)
    length = 12
    if context.args:
        try:
            length = int(context.args[0])
            if length < 8 or length > 50:
                await update.message.reply_text("Password length must be between 8 and 50 characters.")
                return
        except ValueError:
            await update.message.reply_text("Please provide a valid number for password length.")
            return
    
    password = utils.generate_password(length)
    await update.message.reply_text(f"šŸ” <b>Generated Password:</b>\n<code>{password}</code>\n\n<i>Length: {length} characters</i>", parse_mode='HTML')

async def shorten_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Shorten a URL."""
    database.update_user_activity(update.effective_user.id)
    if not context.args:
        await update.message.reply_text("Please provide a URL to shorten.\nUsage: /shorten <url>")
        return
    
    url = " ".join(context.args)
    if not url.startswith(('http://', 'https://')):
        url = 'https://' + url
    
    short_url = utils.shorten_url(url)
    await update.message.reply_text(f"šŸ”— <b>Shortened URL:</b>\n{short_url}", parse_mode='HTML')

async def calc_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Calculate a mathematical expression."""
    database.update_user_activity(update.effective_user.id)
    if not context.args:
        await update.message.reply_text("Please provide a mathematical expression.\nUsage: /calc 2+2*3")
        return
    
    expression = " ".join(context.args)
    result = utils.calculate(expression)
    await update.message.reply_text(f"🧮 <b>Calculation:</b>\n<code>{expression}</code> = <b>{result}</b>", parse_mode='HTML')

async def convert_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Convert between units."""
    database.update_user_activity(update.effective_user.id)
    if len(context.args) < 3:
        await update.message.reply_text("Usage: /convert <value> <from_unit> <to_unit>\nExample: /convert 100 km miles")
        return
    
    try:
        value = context.args[0]
        from_unit = context.args[1]
        to_unit = context.args[2]
        result = utils.convert_unit(value, from_unit, to_unit)
        await update.message.reply_text(f"šŸ“ <b>Unit Conversion:</b>\n{result}", parse_mode='HTML')
    except Exception as e:
        await update.message.reply_text(f"Error: {e}")

async def news_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Get news articles."""
    database.update_user_activity(update.effective_user.id)
    topic = "technology"
    if context.args:
        topic = " ".join(context.args)
    
    news = utils.get_news(topic)
    await update.message.reply_text(f"šŸ“° <b>Latest News ({topic.title()}):</b>\n\n{news}", parse_mode='HTML')

async def summarize_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Summarize text."""
    database.update_user_activity(update.effective_user.id)
    if not context.args:
        await update.message.reply_text("Please provide text to summarize.\nUsage: /summarize <text>")
        return
    
    text = " ".join(context.args)
    summary = utils.summarize_text(text)
    await update.message.reply_text(f"šŸ“ <b>Summary:</b>\n{summary}", parse_mode='HTML')

async def leaderboard_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Show top users leaderboard."""
    user_id = update.effective_user.id
    leaderboard = database.get_leaderboard(limit=10)
    
    if not leaderboard:
        await update.message.reply_text("No users found in the leaderboard.")
        return
    
    text = "šŸ† <b>Top Users Leaderboard:</b>\n━━━━━━━━━━━━━━━━━━\n"
    for idx, (uid, name, xp, level) in enumerate(leaderboard, 1):
        medal = "šŸ„‡" if idx == 1 else "🄈" if idx == 2 else "šŸ„‰" if idx == 3 else f"{idx}."
        text += f"{medal} {name} - Level {level} ({xp} XP)\n"
    
    await update.message.reply_html(text)
472 lines•19.5 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer