Files
mortimer/README.md
2025-12-19 09:54:03 +01:00

7.6 KiB

Telegram AI Assistant for n8n

AI-powered Telegram bot that helps you manage tasks in Nextcloud Deck, search emails via IMAP, and chat with OpenAI - all controlled through Telegram commands.

Features

🤖 AI-Powered Assistant

  • Natural language task creation with date extraction
  • Smart email search and summarization
  • General AI chat capabilities using GPT-4o-mini

📋 Nextcloud Deck Integration

  • Add tasks directly from Telegram
  • AI extracts task details, due dates, descriptions
  • Supports German date formats (morgen, übermorgen)

📧 IMAP Email Search

  • Search your inbox from Telegram
  • View recent emails
  • AI-formatted summaries

Architecture

The system consists of 4 n8n workflows:

  1. telegram-receiver.json - Telegram webhook listener

    • Receives all Telegram messages
    • Parses commands vs natural language
    • Routes to main router workflow
  2. telegram-router.json - Command router

    • Switches on command type (/deck, /email, /ask, /help)
    • Handles help and start messages
    • Delegates to specialized workflows
  3. telegram-deck.json - Nextcloud Deck integration

    • Processes /deck commands
    • Uses OpenAI to extract task details
    • Calls existing /home/node/create_card_from_ai.sh script
  4. telegram-email.json - IMAP email search

    • Processes /email commands
    • Searches IMAP inbox with configured credentials
    • Formats results for Telegram
  5. telegram-ai.json - AI chat

    • Processes /ask commands
    • Calls OpenAI API for general questions
    • Returns formatted Markdown responses

Setup

Prerequisites

  • n8n instance running at https://flow.egonetix.de/
  • Telegram bot token (already configured as credential Csk5cg4HtaSqP5jJ)
  • OpenAI API key (already configured as openai_api_key)
  • IMAP credentials (already configured as BntHPR3YbFD5jAIM)
  • Nextcloud Deck accessible at https://nextcloud.egonetix.de/

Installation

  1. Import workflows into n8n:

    cd /home/icke/assistant
    ./import_workflows.sh
    
  2. Configure Telegram webhook:

    • Get your bot token from BotFather
    • Set webhook URL to: https://flow.egonetix.de/webhook/8f3f59db-aaa5-4762-9416-94be04131fd2
    • Command:
      curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
        -H "Content-Type: application/json" \
        -d '{"url":"https://flow.egonetix.de/webhook/8f3f59db-aaa5-4762-9416-94be04131fd2"}'
      
  3. Activate all workflows in n8n UI:

Telegram Bot Commands

/start          - Welcome message and feature overview
/help           - Show all available commands

📋 Deck Commands:
/deck add <task>         - Add task to Nextcloud Deck
                          Example: /deck add Review Q4 reports by Friday
/deck list              - List tasks (coming soon)

📧 Email Commands:
/email search <query>   - Search your inbox
                          Example: /email search invoice November
/email recent           - Show 5 most recent emails

💬 AI Commands:
/ask <question>         - Ask AI anything
                          Example: /ask What's the weather like today?

Technical Details

Credentials Used

  • Telegram API (Csk5cg4HtaSqP5jJ)

    • Bot token for sending/receiving messages
  • OpenAI API (openai_api_key)

    • Model: gpt-4o-mini
    • Used for task extraction and AI chat
  • IMAP (BntHPR3YbFD5jAIM)

    • Server: imap.egonetix.de:993
    • SSL enabled, read-only mode

Workflow Communication

Workflows communicate via internal HTTP webhooks:

  • Main receiver → Router: http://localhost:8098/webhook/telegram-router
  • Router → Deck: http://localhost:8098/webhook/telegram-deck
  • Router → Email: http://localhost:8098/webhook/telegram-email
  • Router → AI: http://localhost:8098/webhook/telegram-ai

Nextcloud Deck Integration

Uses existing bash script at /home/node/create_card_from_ai.sh:

/home/node/create_card_from_ai.sh "<title>" "<description>" "<duedate>"

The script handles:

  • Authentication with Nextcloud
  • Board/stack selection (hardcoded to board 1, stack 1)
  • Card creation via Deck API
  • Returns success/error status

AI Task Extraction

OpenAI prompt for extracting task details:

Extract task information from user input. Return JSON with:
- title (required, concise task name)
- description (optional, details)
- duedate (optional, YYYY-MM-DD format)

For German dates like 'morgen', 'übermorgen', calculate from today.

Security Considerations

⚠️ Current Status:

  • n8n password is weak (changeme) - CHANGE THIS
  • Nextcloud credentials hardcoded in bash scripts
  • OpenAI API key exposed in multiple files
  • No rate limiting on Telegram commands

🔒 Recommendations:

  1. Change n8n admin password
  2. Migrate credentials to n8n credential store
  3. Rotate OpenAI API key after migration
  4. Implement user authentication/whitelisting
  5. Add rate limiting to prevent abuse
  6. Enable n8n execution logging

Troubleshooting

Webhook Not Receiving Messages

# Check Telegram webhook status
curl "https://api.telegram.org/bot<TOKEN>/getWebhookInfo"

# Verify n8n workflow is active
curl https://flow.egonetix.de/webhook/8f3f59db-aaa5-4762-9416-94be04131fd2

# Check n8n logs
docker logs n8n

Deck Card Creation Fails

# Test bash script manually
docker exec n8n /home/node/create_card_from_ai.sh "Test Task" "Description" ""

# Verify Nextcloud credentials
curl -u robert.wiegand:November1985** \
  https://nextcloud.egonetix.de/index.php/apps/deck/api/v1.0/boards

OpenAI API Errors

  • Check API key validity in n8n credentials
  • Verify quota not exceeded
  • Check model availability (gpt-4o-mini)

IMAP Connection Issues

  • Verify credentials in n8n: BntHPR3YbFD5jAIM
  • Test IMAP connection: openssl s_client -connect imap.egonetix.de:993
  • Check mailbox name (should be "INBOX")

Development

Testing Workflows Locally

Use n8n's webhook test feature or curl:

# Test router
curl -X POST http://localhost:8098/webhook/telegram-router \
  -H "Content-Type: application/json" \
  -d '{
    "command": "/help",
    "args": "",
    "chatId": "579304651",
    "userId": 123456,
    "username": "testuser"
  }'

# Test deck workflow
curl -X POST http://localhost:8098/webhook/telegram-deck \
  -H "Content-Type: application/json" \
  -d '{
    "command": "/deck",
    "args": "add Test task for tomorrow",
    "chatId": "579304651"
  }'

Extending Functionality

To add new commands:

  1. Add case in telegram-router.json Switch node
  2. Create new workflow with webhook endpoint
  3. Update router to call new workflow
  4. Update help text in /help command
  5. Import updated workflows

Monitoring

View execution history in n8n:

Future Enhancements

🚀 Planned Features:

  • Deck task listing and completion
  • Calendar integration for appointments
  • Multi-turn conversations with context
  • Voice message transcription (Whisper)
  • Document upload to Nextcloud
  • Scheduled reminders
  • User authentication/whitelisting
  • Analytics dashboard

Credits

  • Built on existing credit card workflow patterns
  • Uses proven integration with Nextcloud Deck API
  • Leverages existing IMAP and OpenAI credentials
  • Telegram bot token from existing infrastructure

License

Internal tool for personal use on srvdocker02.


Author: AI Assistant
Created: 2025-12-02
n8n Version: 1.19.4
Infrastructure: srvdocker02