A Telegram bot that discovers, analyzes, and delivers meme templates with AI-powered context.
- MemeStream Agent π
MemeStream Agent is a full-stack TypeScript application that combines web scraping, AI integration, and bot development to create an intelligent meme discovery platform. It allows users to request memes by name, and the bot will deliver a blank template, a brief history of the meme, and a gallery of examples.
This project demonstrates a robust, scalable, and resilient architecture, with a focus on performance optimization and a great user experience.
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Telegram Bot βββββΆβ Meme Agent βββββΆβ Web Scraping β
β (Webhook) β β (AI Logic) β β (Playwright) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β User Interfaceβ β Google Gemini β β Meme Database β
β (Commands) β β (AI Context) β β (Templates) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ- π€ Intelligent Meme Discovery: Utilizes natural language processing to understand user requests and handle variations in meme names.
- π¨ Instant Template Generation: Delivers blank meme templates for customization, along with a gallery of examples.
- π§ AI-Powered Context: Provides historical and cultural background for each meme using Google Gemini.
- β‘ High Performance: Optimized for speed and low memory usage, with concurrent processing and resource pooling.
- π‘οΈ Error Resilience: Graceful degradation and intelligent retry logic ensure high availability.
- π Advanced Search Capabilities: Implements fuzzy string matching, partial matching, and Levenshtein distance for robust meme name recognition, ensuring users find their memes even with typos or incomplete queries.
This project showcases several advanced software engineering practices and technical implementations:
Our bot goes beyond simple keyword matching. It employs a multi-layered approach to meme discovery:
- Exact & Partial Matching: Prioritizes direct matches while also identifying memes where the search term is a substring.
- Levenshtein Distance: For close but not exact matches (e.g., "Two Path" for "Two Paths"), we calculate the Levenshtein distance to find memes with minor typos or variations, ensuring a high success rate for user queries.
- Fuzzy Word Matching: Breaks down complex search terms into individual words to find relevant memes even if the full phrase isn't an exact match.
-
Direct API Integration for
/blank: The/blankcommand now directly interacts with the Imgflip API, bypassing the job queue for instant responses and reduced latency. -
Playwright Browser Optimization: The web scraping component utilizes Playwright with aggressive optimizations for serverless environments, including:
--no-sandbox,--disable-dev-shm-usage,--disable-gpuflags for reduced memory footprint.- Resource blocking (
image,font,media) to minimize page load times and memory consumption during scraping. - Page reuse and intelligent cleanup to prevent memory leaks.
-
Redis Caching: Extensive use of Redis for caching meme data, user contexts, and popular meme suggestions, significantly reducing API calls and improving response times.
- Comprehensive Error Notifications: Users receive clear, actionable feedback when memes are not found or when API calls fail.
- Graceful Shutdowns: Implemented across the bot, worker, and Redis connections to ensure clean exits, prevent data corruption, and maintain system stability during restarts or deployments.
- Retry Mechanisms: AI calls and other external interactions are wrapped with intelligent retry logic using exponential backoff, enhancing the bot's resilience to transient network issues or API rate limits.
- Structured Logging: Detailed console logs provide insights into job processing, cache hits/misses, and error occurrences.
- Modular Architecture: The codebase is organized into distinct modules (bot core, meme generator, API, utilities) promoting maintainability, testability, and scalability.
- TypeScript: Strong typing throughout the project enhances code quality, reduces bugs, and improves developer experience.
- Backend: TypeScript, Node.js, Express.js
- Bot Framework: node-telegram-bot-api
- Web Scraping: Playwright
- AI: Google Gemini (Function Calling, Streaming)
- Infrastructure: Docker, Webhooks, Redis (BullMQ for job queuing)
Follow these instructions to get a copy of the project up and running on your local machine for development and testing purposes.
- Node.js (v16 or higher)
- Docker (optional, for containerized deployment)
- An
ngrokaccount or other tunneling service to expose your local server to the internet. - A Telegram Bot Token (get from @BotFather)
- A Google Generative AI API Key
-
Clone the repository:
git clone https://github.com/Patoski-patoski/MemeStream-Agent.git cd MemeStream-Agent -
Install dependencies:
npm install
-
Create a
.envfile in the root directory by copying the example file:cp .env.example .env
-
Open the
.envfile and add your credentials:# Your Telegram Bot token from @BotFather TELEGRAM_BOT_TOKEN=your_telegram_bot_token # Your public URL from ngrok or a similar service WEBHOOK_URL=https://your-ngrok-url.ngrok.io # The port your local server will run on PORT=3300 # Your Gemini API Key GEMINI_API_KEY=your_gemini_api_key MODEL_NAME=gemini-pro
-
Start your tunneling service to expose your local port. For example, using
ngrok:ngrok http 3300
Copy the HTTPS forwarding URL provided by
ngrokinto theWEBHOOK_URLvariable in your.envfile. -
Start the bot in development mode:
npm run dev
nodemonwill watch for any changes in thesrcdirectory and automatically restart the bot. -
Interact with the bot in Telegram:
/start- Get a welcome message and instructions./meme [name]- Search for a specific meme (e.g.,/meme Distracted Boyfriend)./blank [name]- Get a blank meme template (e.g.,/blank Drake hotline bling).
MemeStream-Agent/
βββ .github/ # GitHub Actions workflows
βββ dist/ # Compiled TypeScript files
βββ src/ # Source code
β βββ bot/ # Telegram bot logic
β β βββ core/ # Core bot functionalities
β β βββ types/ # TypeScript types for the bot
β β βββ utils/ # Utility functions for the bot
β βββ meme-generator/ # Meme agent and tools
β βββ agents/ # AI agent for meme generation
β βββ tools/ # Web scraping and other tools
β βββ types/ # TypeScript types for the meme generator
β βββ utils/ # Utility functions for the meme generator
βββ tests/ # Test files
βββ .dockerignore # Docker ignore file
βββ .env.example # Example environment variables
βββ .gitignore # Git ignore file
βββ Dockerfile # Docker configuration
βββ eslint.config.ts # ESLint configuration
βββ jest.config.mjs # Jest configuration
βββ nodemon.json # Nodemon configuration
βββ package.json # Project dependencies and scripts
βββ README.md # This file
βββ tsconfig.json # TypeScript configurationContributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Distributed under the MIT License. See LICENSE for more information.
Patrick Patoski - @codesbypatrick
Project Link: https://github.com/Patoski-patoski/MemeStream-Agent
Live Demo: @MemeStreamAgentBot