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
  • Blog
  • 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
utils.py
utils.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.

import qrcode
import io
import os
from gtts import gTTS
from deep_translator import GoogleTranslator
from fpdf import FPDF

def generate_qr(text):
    """Generates a QR code image from the given text."""
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(text)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    
    # Save to bytes buffer
    bio = io.BytesIO()
    bio.name = 'qrcode.png'
    img.save(bio, 'PNG')
    bio.seek(0)
    
    return bio

def text_to_speech_file(text, lang='en'):
    """Generates audio file from text."""
    try:
        tts = gTTS(text=text, lang=lang)
        bio = io.BytesIO()
        bio.name = 'voice.mp3'
        tts.write_to_fp(bio)
        bio.seek(0)
        return bio
    except Exception as e:
        print(f"TTS Error: {e}")
        return None

def translate_text(text, target_lang='en'):
    """Translates text to target language."""
    try:
        translator = GoogleTranslator(source='auto', target=target_lang)
        return translator.translate(text)
    except Exception as e:
        return f"Translation Error: {e}"

def create_pdf(text):
    """Creates a simple PDF with the text."""
    try:
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", size=12)
        
        # Better unicode handling
        try:
            # Try UTF-8 first
            pdf.multi_cell(0, 10, text)
        except:
            # Fallback to latin-1
            pdf.multi_cell(0, 10, text.encode('latin-1', 'replace').decode('latin-1'))
        
        bio = io.BytesIO()
        bio.name = 'note.pdf'
        pdf_content = pdf.output(dest='S').encode('latin-1', 'replace')
        bio.write(pdf_content)
        bio.seek(0)
        return bio
    except Exception as e:
        print(f"PDF Error: {e}")
        return None

def ai_response(query):
    """AI response using OpenAI API if available, otherwise fallback to rule-based responses."""
    import os
    from dotenv import load_dotenv
    
    load_dotenv()
    api_key = os.getenv("OPENAI_API_KEY")
    
    if api_key:
        try:
            from openai import OpenAI
            client = OpenAI(api_key=api_key)
            response = client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "You are a helpful Telegram bot assistant created by RSK World. Be concise and friendly."},
                    {"role": "user", "content": query}
                ],
                max_tokens=150
            )
            return response.choices[0].message.content
        except Exception as e:
            print(f"OpenAI Error: {e}")
    
    # Fallback to rule-based responses
    query_lower = query.lower()
    if "hello" in query_lower or "hi" in query_lower:
        return "Hello! I am your AI assistant from RSK World. How can I help you today?"
    elif "who are you" in query_lower:
        return "I am a multi-functional Telegram Bot created by Molla Samser and Rima Khatun at RSK World."
    elif "time" in query_lower:
        from datetime import datetime
        return f"The current server time is {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}."
    elif "joke" in query_lower:
        jokes = [
            "Why did the computer show up late to work? Because it had a hard drive!",
            "Why do programmers prefer dark mode? Because light attracts bugs!",
            "What's a programmer's favorite hangout place? Foo Bar!"
        ]
        import random
        return random.choice(jokes)
    else:
        return f"Interesting! You said: '{query}'. I'm still learning as an AI, but I'm here to support you!"

def get_weather(city):
    """Fetches weather data for a city using OpenWeatherMap API (if available) or simulated data."""
    import os
    import requests
    from dotenv import load_dotenv
    
    load_dotenv()
    api_key = os.getenv("OPENWEATHER_API_KEY")
    
    if api_key:
        try:
            url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                data = response.json()
                temp = data['main']['temp']
                condition = data['weather'][0]['description'].title()
                humidity = data['main']['humidity']
                return f"🌤️ <b>Weather in {city.title()}:</b>\n🌡️ Temperature: {temp}°C\n☁️ Condition: {condition}\n💧 Humidity: {humidity}%"
        except Exception as e:
            print(f"Weather API Error: {e}")
    
    # Fallback to simulated data
    import random
    temps = [20, 25, 18, 30, 15, 22]
    conditions = ["Sunny ☀️", "Cloudy ☁️", "Rainy 🌧️", "Partly Cloudy ⛅"]
    
    temp = random.choice(temps)
    cond = random.choice(conditions)
    
    return f"🌤️ <b>Weather in {city.title()}:</b>\nTemperature: {temp}°C\nCondition: {cond}\n<i>(Simulated Data - RSK World)</i>"

def generate_password(length=12, include_symbols=True):
    """Generates a random secure password."""
    import random
    import string
    
    chars = string.ascii_letters + string.digits
    if include_symbols:
        chars += "!@#$%^&*"
    
    password = ''.join(random.choice(chars) for _ in range(length))
    return password

def shorten_url(url):
    """Shortens a URL using TinyURL or similar service."""
    try:
        import pyshorteners
        s = pyshorteners.Shortener()
        short_url = s.tinyurl.short(url)
        return short_url
    except Exception as e:
        return f"Error shortening URL: {e}"

def calculate(expression):
    """Safely evaluates a mathematical expression."""
    import re
    # Only allow numbers, operators, and parentheses
    if re.match(r'^[0-9+\-*/().\s]+$', expression):
        try:
            result = eval(expression)
            return str(result)
        except:
            return "Invalid expression"
    return "Invalid characters in expression"

def convert_unit(value, from_unit, to_unit):
    """Converts between common units."""
    try:
        value = float(value)
        conversions = {
            ('km', 'miles'): value * 0.621371,
            ('miles', 'km'): value * 1.60934,
            ('kg', 'lbs'): value * 2.20462,
            ('lbs', 'kg'): value * 0.453592,
            ('celsius', 'fahrenheit'): (value * 9/5) + 32,
            ('fahrenheit', 'celsius'): (value - 32) * 5/9,
            ('m', 'ft'): value * 3.28084,
            ('ft', 'm'): value * 0.3048,
        }
        
        key = (from_unit.lower(), to_unit.lower())
        if key in conversions:
            return f"{value} {from_unit} = {conversions[key]:.2f} {to_unit}"
        else:
            return f"Conversion from {from_unit} to {to_unit} not supported"
    except ValueError:
        return "Invalid number"

def process_image(image_bytes, operation='resize', size=(800, 600)):
    """Processes an image (resize, rotate, etc.)."""
    try:
        from PIL import Image
        import io
        
        img = Image.open(io.BytesIO(image_bytes))
        
        if operation == 'resize':
            img = img.resize(size, Image.Resampling.LANCZOS)
        elif operation == 'rotate':
            img = img.rotate(90, expand=True)
        elif operation == 'grayscale':
            img = img.convert('L')
        
        output = io.BytesIO()
        img.save(output, format='PNG')
        output.seek(0)
        return output
    except Exception as e:
        print(f"Image processing error: {e}")
        return None

def get_news(topic='technology', limit=5):
    """Fetches news articles (simulated for now)."""
    # In production, use NewsAPI or similar
    news_items = [
        f"📰 Latest {topic} news: Breaking developments in the tech world",
        f"📰 {topic.title()} Update: New innovations announced",
        f"📰 {topic.title()} Report: Industry trends and analysis"
    ]
    return "\n".join(news_items[:limit])

def summarize_text(text, max_length=100):
    """Summarizes text to a shorter version."""
    if len(text) <= max_length:
        return text
    # Simple summarization - take first sentence or truncate
    sentences = text.split('.')
    summary = sentences[0] if sentences else text[:max_length]
    if len(summary) > max_length:
        summary = summary[:max_length] + "..."
    return summary

261 lines•8.9 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

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