Skill: dinghaibin/telegram-bot-pro (version 1.0.0)

--- name: telegram-bot description: Create and manage Telegram bots. Use when user wants to build a Telegram bot for notifications, automation, customer support, group management, or interactive commands. --- # Telegram Bot Create and manage Telegram bots using the Bot API. ## Quick Start ```bash # Get bot token from @BotFather on Telegram # Create bot.py: python scripts/bot.py --token YOUR_TOKEN --handler my_handler.py ``` ## Bot Creation Steps 1. Open Telegram, search for @BotFather 2. Send /newbot to create new bot 3. Get API token 4. Configure webhooks or polling ## Core Features - **Commands**: /start, /help, /settings - **Callbacks**: Inline buttons, queries - **Groups**: Admin tools, filters - **Webhooks**: Receive updates via HTTP ## Script Usage ```bash python scripts/bot.py [OPTIONS] Options: --token TEXT Bot API token (required) --handler PATH Python handler file --webhook-url URL Webhook endpoint URL --port PORT Webhook server port (default: 8443) --poll Use long polling instead of webhook ``` ## Handler Format ```python # my_handler.py def handle_update(update, context): """Handle incoming updates.""" if update.message: text = update.message.text if text == "/start": context.bot.send_message( chat_id=update.message.chat_id, text="Hello! I'm your bot." ) ``` ## Examples See `references/examples.md` for: - Echo bot - Inline keyboard bot - Group admin bot - Notification bot - Weather bot

path: references/examples.md
content: # Telegram Bot Examples

## Example 1: Simple Echo Bot

```python
# echo_bot.py
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Echo bot started!")

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(update.message.text)

app = Application.builder().token("YOUR_TOKEN").build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT, echo))
app.run_polling()
```

## Example 2: Inline Keyboard Bot

```python
# keyboard_bot.py
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [
        [InlineKeyboardButton("Option 1", callback_data="1")],
        [InlineKeyboardButton("Option 2", callback_data="2")]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text("Choose:", reply_markup=reply_markup)

async def button_click(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    await query.edit_message_text(f"You chose: {query.data}")

app = Application.builder().token("YOUR_TOKEN").build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CallbackQueryHandler(button_click))
app.run_polling()
```

## Example 3: Admin Bot for Groups

```python
# admin_bot.py
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

ADMIN_IDS = [123456789]  # Your user ID

async def ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.from_user.id not in ADMIN_IDS:
        await update.message.reply_text("Not authorized")
        return
    if update.message.reply_to_message:
        await context.bot.ban_chat_member(
            chat_id=update.message.chat_id,
            user_id=update.message.reply_to_message.from_user.id
        )
        await update.message.reply_text("User banned")

app = Application.builder().token("YOUR_TOKEN").build()
app.add_handler(CommandHandler("ban", ban))
app.run_polling()
```

## Example 4: Notification Bot

```python
# notify_bot.py
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

# Store user IDs
USER_IDS = set()

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    USER_IDS.add(update.message.from_user.id)
    await update.message.reply_text(f"Registered! Your ID: {update.message.from_user.id}")

async def notify(context: ContextTypes.DEFAULT_TYPE, message: str):
    for user_id in USER_IDS:
        await context.bot.send_message(chat_id=user_id, text=message)

# Usage:
# await notify(context, "Something happened!")
```

## Running the Bot

```bash
# Polling mode (development)
python scripts/bot.py --token YOUR_TOKEN --poll

# Webhook mode (production)
python scripts/bot.py --token YOUR_TOKEN --webhook-url https://your-domain.com/webhook
```

## Getting Help

- Bot API: https://core.telegram.org/bots/api
- python-telegram-bot: https://python-telegram-bot.org


path: scripts/bot.py
content: #!/usr/bin/env python3
"""
Telegram Bot - Simple bot framework using python-telegram-bot
"""

import argparse
import os
import sys
from pathlib import Path

# Try to import telegram, install if needed
try:
    from telegram import Update
    from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
except ImportError:
    print("Installing python-telegram-bot...")
    os.system("pip install python-telegram-bot")
    from telegram import Update
    from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes


async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /start command."""
    await update.message.reply_text("Hello! I'm your bot. Type /help for commands.")


async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /help command."""
    await update.message.reply_text(
        "Available commands:\n"
        "/start - Start the bot\n"
        "/help - Show this help\n"
        "/echo [text] - Echo back your message"
    )


async def echo_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle /echo command."""
    text = ' '.join(context.args) if context.args else "Please provide text"
    await update.message.reply_text(text)


async def echo_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Echo back incoming messages."""
    await update.message.reply_text(update.message.text)


def load_handler(handler_path: str):
    """Load custom handler from Python file."""
    if not os.path.exists(handler_path):
        print(f"Handler file not found: {handler_path}")
        return None
    
    # Add directory to path
    sys.path.insert(0, os.path.dirname(handler_path))
    
    # Import module
    module_name = Path(handler_path).stem
    try:
        return __import__(module_name)
    except Exception as e:
        print(f"Error loading handler: {e}")
        return None


def run_bot(token: str, handler_path: str = None, poll: bool = False):
    """Run the bot."""
    application = Application.builder().token(token).build()
    
    # Add default handlers
    application.add_handler(CommandHandler("start", start_command))
    application.add_handler(CommandHandler("help", help_command))
    application.add_handler(CommandHandler("echo", echo_command))
    
    # Add message handler (echo)
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo_message))
    
    # Load custom handler if provided
    if handler_path:
        handler_module = load_handler(handler_path)
        if handler_module and hasattr(handler_module, 'handle_update'):
            application.add_handler(
                MessageHandler(filters.ALL, handler_module.handle_update)
            )
    
    # Run
    if poll:
        print("Running in polling mode...")
        application.run_polling()
    else:
        print("Running in webhook mode (set --webhook-url)...")


def main():
    parser = argparse.ArgumentParser(description='Telegram Bot')
    parser.add_argument('--token', required=True, help='Bot API token')
    parser.add_argument('--handler', help='Custom handler Python file')
    parser.add_argument('--webhook-url', help='Webhook URL')
    parser.add_argument('--port', type=int, default=8443, help='Webhook server port')
    parser.add_argument('--poll', action='store_true', help='Use polling instead of webhook')
    
    args = parser.parse_args()
    run_bot(args.token, args.handler, args.poll)


if __name__ == '__main__':
    main()


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)