Building a Telegram Bot for Community Management With DeFiKit

Community management in crypto Telegram groups is broken at scale. Moderators burn out policing spam, answering the same questions on repeat, and manually onboarding thousands of new members every week. The volume is unsustainable — and the cost of letting quality slip is lost trust and compromised security.

DeFiKit Bot Maker solves this with a modular, open-source bot architecture purpose-built for Web3 communities. It wraps grammY, Prisma, and a clean middleware pipeline into a framework you can deploy in minutes and extend indefinitely. This tutorial walks through building a production-ready community management bot — the same architecture powering berabear_bot, the flagship DeFiKit demo.

The Problem — Manual Community Management for Crypto TG Groups

Every crypto project with a thriving Telegram community eventually hits the same wall. A handful of moderators cover all time zones, filter every message, catch every scam link, and answer every newcomer question. The math doesn't work.

Consider a moderately active group of 10,000 members:

- **200–500 messages per hour** during peak times

- **30–50 new joiners daily**, each needing a welcome and role assignment

- **10–20 support questions per hour**, most of them duplicates

- **Scam link frequency spikes** during token launches and market events

Manual moderation at this volume means 4–6 moderators working overlapping shifts, each burning hours daily on repetitive tasks. The real cost isn't just time — it's inconsistency. One mod approves what another bans. Newcomers wait 20 minutes for a response. Scam content survives long enough to cause damage.

The Solution — DeFiKit Bot Maker as a Modular Bot Platform

DeFiKit Bot Maker is not a single bot — it's a bot-building framework. It provides:

- **Pluggable command system** — each feature lives in its own module

- **Middleware pipeline** — grammY's composable middleware for message processing

- **Prisma ORM** — typed database access for member profiles, roles, and analytics

- **Docker-first deployment** — single command to spin up the full stack

- **Built-in admin UI** — manage commands, roles, and analytics from a dashboard

The architecture is clean, testable, and extensible. Adding a new moderation rule or command takes minutes, not days.

Architecture — grammY, Prisma, and a Modular Command System

The bot runs on a three-layer architecture:

```

Client Layer: Telegram API ← Webhook Polling

Middleware: grammY → Session → RateLimit → Filter → Handler

Data Layer: Prisma → PostgreSQL / SQLite

```

**grammY** provides the bot framework — context objects, middleware composition, error handling, and session management. It handles all Telegram API interactions.

**Prisma** sits between the bot and the database, providing type-safe queries for member records, guild settings, filtered content logs, and analytics.

**The command system** is modular by design. Each feature — greetings, roles, FAQ, filtering — is a self-contained module exposing its own middleware and handlers.

Prisma Schema (Simplified)

```prisma

model Member {

id String @id

firstName String?

lastName String?

username String?

roles Role[]

joinedAt DateTime @default(now())

messageCount Int @default(0)

warnings Int @default(0)

isMuted Boolean @default(false)

}

model Guild {

id String @id

title String?

welcomeMsg String?

filterRules Json?

createdAt DateTime @default(now())

}

model FilteredContent {

id String @id @default(cuid())

memberId String

contentType String

content String?

detectedAt DateTime @default(now())

}

```

This schema captures the essentials — member state, per-guild configuration, and an audit trail.

Implementation — Building the Bot Step by Step

1. Auto-Greetings with Role Assignment

The bot listens for the `chat_member` update and responds with a customizable welcome. Role assignment can happen automatically based on wallet verification or NFT holding.

```typescript

import { Bot } from 'grammy';

bot.on('chat_member', async (ctx) => {

const { new_chat_member } = ctx.chatMember;

if (new_chat_member.status === 'member') {

const welcomeMsg = `Welcome ${ctx.from?.firstName}! 👋\n\nPlease read /rules and verify your wallet with /verify to access the full chat.`;

await ctx.reply(welcomeMsg);

}

});

```

2. FAQ Bot — Automatic Answers to Common Questions

A grammY middleware that matches incoming messages against a FAQ database and responds immediately:

```typescript

import { Composer } from 'grammy';

const faqComposer = new Composer();

faqComposer.hear(/\b(gas|fees|transaction cost)\b/i, async (ctx) => {

await ctx.reply(

'💡 *Gas Fees FAQ*\n\n' +

'Gas fees vary by network congestion. Check current rates at:\n' +

'• Ethereum: etherscan.io/gastracker\n' +

'• BSC: bscscan.com/gastracker\n'

);

});

```

3. Content Filtering Middleware

The filtering pipeline catches spam and scam links before they reach the group:

```typescript

const filterMiddleware = async (ctx, next) => {

const text = ctx.message?.text || '';

const suspiciousPatterns = [

/(?:airdrop|giveaway).*(?:free|claim)/i,

/(?:http|https):\/\/[^\s]*(?:claim|free|earn)/i,

];

const isSuspicious = suspiciousPatterns.some(p => p.test(text));

if (isSuspicious) {

await ctx.deleteMessage();

await ctx.reply(`⚠️ @${ctx.from?.username || ctx.from?.id} that looks suspicious and has been removed.`);

return;

}

await next();

};

bot.use(filterMiddleware);

```

4. Analytics Tracking

Track message volume, active hours, and member growth with a simple middleware:

```typescript

const analyticsMiddleware = async (ctx, next) => {

const memberId = ctx.from?.id.toString();

if (memberId) {

await prisma.member.upsert({

where: { id: memberId },

update: { messageCount: { increment: 1 } },

create: { id: memberId, firstName: ctx.from?.firstName },

});

}

await next();

};

```

5. berabear_bot — The Flagship Demo

berabear_bot, the DeFiKit flagship bot, demonstrates the full capabilities of the framework. It runs on the same architecture and handles:

- Automated onboarding for 5,000+ new members per month

- Real-time scam filtering with 98.7% precision

- 24/7 FAQ responses covering 40+ common topics

- Weekly community analytics reports

- Multi-role assignment tied to on-chain verification

Built with grammY + Prisma + PostgreSQL, berabear_bot processes over 50,000 messages daily with 99.9% uptime on a single $20/month VPS.

Deployment

Docker Setup

```bash

git clone https://github.com/your-org/defikit-bot-maker.git

cd defikit-bot-maker

cp .env.example .env

Edit .env with your BOT_TOKEN and DATABASE_URL

docker compose up -d

docker compose logs -f bot

```

Manual Deployment

```bash

npm install

npx prisma generate

npx prisma migrate dev

npm run dev

```

Results and Metrics

DeFiKit Bot Maker deployments consistently show:

- **80–90% reduction** in repetitive moderator workload

- **< 5 second response time** for FAQ questions (vs. 5–20 minutes manually)

- **98%+ spam capture rate** with sub-1% false positives

- **Zero missed greetings** — every joiner welcomed within seconds

- **50–70% fewer support tickets** as the FAQ bot handles Tier-1 questions

Teams running berabear_bot reported reclaiming 20+ moderator-hours per week — time redirected to community engagement and event planning.

Key Takeaways

1. **Automation is not optional** — at Web3 community scale, manual moderation breaks. DeFiKit Bot Maker provides a production-ready automation layer.

2. **Modular architecture wins** — grammY's middleware pipeline and DeFiKit's module system let you add features incrementally without rewriting the bot.

3. **Type safety matters** — Prisma's generated types catch schema mismatches at compile time, reducing runtime errors in production.

4. **Start simple, extend later** — a bot with auto-greetings, FAQ matching, and basic filtering covers 80% of the workload. Add on-chain verification and analytics as needed.

5. **DeFiKit is open source** — audit every line, extend every module, deploy on your own infrastructure. No vendor lock-in, no per-user pricing.

Start building today: `docker compose up -d` is all it takes to go from zero to production.