Grokii

Author: retoor retoor@molodetz.nl

Grokii is an AI-powered assistant bot for the devRant platform. It monitors for @mentions and responds intelligently using advanced language models via OpenRouter. The bot also includes spam detection and moderation capabilities for community maintenance.

Table of Contents

Overview

Grokii operates as a devRant community bot that:

  1. Fetches @mentions from external JSON feed (https://static.molodetz.nl/dr.mentions.json)
  2. Extracts questions and context from conversations
  3. Generates intelligent responses using Grok AI (or other models via OpenRouter)
  4. Posts replies back to the conversation
  5. Optionally scans for and downvotes spam content

The bot is designed for the devRant developer community, understanding programming concepts, developer culture, and the platform's informal, rant-friendly atmosphere.

Features

AI Chat Mode (Default)

  • Real-time mention monitoring with configurable polling intervals
  • Context-aware responses using rant content and comment history
  • Powered by x]AI Grok models via OpenRouter
  • Customizable AI personality through system prompts
  • Adjustable response parameters (temperature, max tokens)
  • Automatic @mention reply formatting
  • Dry-run mode for testing without posting

Spam Detection Mode

  • Pattern-based content analysis
  • Behavioral anomaly detection
  • Automatic downvoting with spam classification
  • Detection categories:
    • Cryptocurrency and investment scams
    • Self-promotion and link spam
    • Adult/NSFW content
    • Phishing attempts
    • Gambling promotions
    • Malware and piracy links
    • Excessive capitalization
    • Repetitive character abuse
    • Suspicious posting frequency
    • Duplicate content detection

Operational Features

  • Continuous daemon mode for 24/7 operation
  • Comprehensive logging with file output option
  • Debug mode for troubleshooting
  • Graceful shutdown handling
  • Session statistics reporting

Requirements

System Requirements

  • Swift 5.9 or later
  • macOS 13+ or Linux (Ubuntu 20.04+, Debian 11+)
  • Network access to devRant API and OpenRouter API

External Services

  • devRant account for the bot
  • OpenRouter API key (free tier available)

Installation

From Source

git clone https://github.com/user/grokii.git
cd grokii

swift build -c release

sudo cp .build/release/grokii /usr/local/bin/

Development Build

swift build

.build/debug/grokii --help

Configuration

Environment Variables

Variable Required Description
OPENROUTER_API_KEY Yes (chat mode) API key from openrouter.ai

Obtaining an OpenRouter API Key

  1. Visit https://openrouter.ai
  2. Create an account or sign in
  3. Navigate to https://openrouter.ai/keys
  4. Generate a new API key
  5. Add credits or use free tier models

Usage

Quick Start

export OPENROUTER_API_KEY="sk-or-v1-..."

grokii chat -u YOUR_BOT_USERNAME -p YOUR_BOT_PASSWORD --continuous

Chat Mode Commands

grokii chat -u USERNAME -p PASSWORD --dry-run

grokii chat -u USERNAME -p PASSWORD --continuous --interval 30

grokii chat -u USERNAME -p PASSWORD -c --model "anthropic/claude-3.5-sonnet"

grokii chat -u USERNAME -p PASSWORD -c --temperature 0.9 --max-tokens 300

grokii chat -u USERNAME -p PASSWORD -c -l /var/log/grokii.log

Spam Mode Commands

grokii spam -u USERNAME -p PASSWORD --dry-run

grokii spam -u USERNAME -p PASSWORD --continuous --interval 300

grokii spam -u USERNAME -p PASSWORD -c --debug -l spam.log

Command Reference

Global Options

Option Short Description Default
--username -u devRant bot account username Required
--password -p devRant bot account password Required
--continuous -c Run in daemon mode false
--interval -i Polling interval (seconds) 30
--dry-run Test mode - no actions taken false
--log-file -l Path to log file None
--debug Enable verbose logging false

Chat Mode Options

Option Description Default
--model OpenRouter model identifier x-ai/grok-code-fast-1
--system-prompt Custom AI personality prompt Built-in
--max-tokens Maximum response length 500
--temperature AI creativity (0.0-2.0) 0.7

Architecture

Sources/Grokii/
├── Main.swift              # CLI entry point, argument parsing, subcommands
├── MentionBot.swift        # Notification monitoring, mention processing
├── OpenRouterClient.swift  # OpenRouter API integration
├── SpamActions.swift       # Voting actions, spam scanner
├── SpamPattern.swift       # Spam detection patterns, behavioral analysis
└── Logger.swift            # Logging infrastructure

Component Overview

Main.swift

Entry point using Swift Argument Parser. Defines the grokii command with chat and spam subcommands. Handles authentication and bot initialization.

MentionBot.swift

Core mention-response logic:

  • Fetches mentions from external JSON feed (https://static.molodetz.nl/dr.mentions.json)
  • Filters mentions where target matches bot username
  • Uses guid from JSON for deduplication
  • Extracts question text by removing bot @mention
  • Builds context from rant and recent comments
  • Coordinates with OpenRouterClient for AI response
  • Filters self-mentions from AI responses to prevent self-reply loops
  • Posts formatted reply via devRant API

OpenRouterClient.swift

HTTP client for OpenRouter API:

  • Implements chat completions endpoint
  • Manages authentication headers
  • Configurable model, temperature, max tokens
  • Built-in system prompt for Grokii personality
  • Error handling with descriptive messages

SpamActions.swift

Moderation utilities:

  • SpamActions: Voting operations (upvote/downvote)
  • SpamScanner: Feed scanning and spam detection
  • Integrates with SpamDetector for analysis
  • Tracks processed content to avoid duplicates

SpamPattern.swift

Spam detection engine:

  • SpamPattern: Individual detection rules
  • SpamDetector: Pattern orchestration
  • Regex and keyword matching
  • Behavioral analysis (posting frequency, duplicates)
  • Configurable scoring thresholds

Logger.swift

Async-safe logging:

  • Multiple log levels (debug, info, warning, error, spam)
  • Console and file output
  • Timestamped messages
  • Actor-based thread safety

AI Configuration

Default Model

Grokii uses x-ai/grok-code-fast-1 by default - xAI's fast inference model optimized for quick, accurate responses.

Alternative Models

Any OpenRouter-supported model can be used:

grokii chat -u USER -p PASS --model "anthropic/claude-4.5-sonnet"

grokii chat -u USER -p PASS --model "openai/gpt-4o"

grokii chat -u USER -p PASS --model "meta-llama/llama-3.1-70b-instruct"

grokii chat -u USER -p PASS --model "google/gemini-pro-2.5"

Temperature Settings

Value Behavior
0.0-0.3 Focused, deterministic responses
0.4-0.7 Balanced creativity and accuracy
0.8-1.2 Creative, varied responses
1.3-2.0 Highly creative, potentially unpredictable

Custom System Prompts

Override the default Grokii personality:

grokii chat -u USER -p PASS --system-prompt "You are a sarcastic senior developer who has seen it all. Keep responses short and witty."

Spam Detection

Detection Patterns

Pattern Triggers
Crypto Scam bitcoin, ethereum, invest, airdrop, 100x gains
Promotion check out my channel, join discord, bit.ly links
Adult onlyfans, nsfw, explicit content references
Phishing verify account, confirm password, urgent action
Gambling casino, betting, jackpot, slots
Malware cracked software, keygen, free download hacks
Format Abuse EXCESSIVE CAPS, repeated characters

Behavioral Analysis

  • Rapid posting: Multiple posts within 60 seconds
  • Duplicate content: Same text posted repeatedly
  • Link spam: More than 3 URLs in single post
  • Short posts with links: Minimal text + URL

Scoring System

Each matched pattern contributes to a spam score. Content with score >= 2 is flagged as spam and downvoted with the "offensive/spam" reason.

Deployment

Systemd Service (Linux)

Create /etc/systemd/system/grokii.service:

[Unit]
Description=Grokii devRant Bot
After=network.target

[Service]
Type=simple
User=grokii
Environment=OPENROUTER_API_KEY=sk-or-v1-...
ExecStart=/usr/local/bin/grokii chat -u BOT_USER -p BOT_PASS -c -i 30 -l /var/log/grokii/chat.log
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl enable grokii
sudo systemctl start grokii
sudo journalctl -u grokii -f

Docker

FROM swift:5.9-jammy
WORKDIR /app
COPY . .
RUN swift build -c release
CMD [".build/release/grokii", "chat", "-u", "$BOT_USER", "-p", "$BOT_PASS", "-c"]

Process Manager (PM2)

pm2 start "grokii chat -u USER -p PASS -c" --name grokii
pm2 save
pm2 startup

API Reference

External Mentions Feed

  • Endpoint: GET https://static.molodetz.nl/dr.mentions.json
  • Format: JSON array of mention objects
  • Fields: from, to, content, rant_id, comment_id, created_time, identifiers.guid

devRant API (via SwiftDevRantSDK)

  • Authentication: Username/password login
  • Rants: Fetch rant content and comments
  • Comments: Post replies to rants
  • Voting: Upvote/downvote with reason

OpenRouter API

  • Endpoint: POST https://openrouter.ai/api/v1/chat/completions
  • Authentication: Bearer token
  • Request: Messages array with system/user roles
  • Response: Chat completion with content

Dependencies

Package Purpose
SwiftDevRantSDK devRant API client
swift-argument-parser CLI framework
KreeRequest HTTP networking

License

MIT License

Copyright (c) 2025 retoor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.