How to Easily Build a Telegram AI Agent to Summarize Articles Using n8n


Hero

Hey there! Ever feel like you’re drowning in a sea of articles, blog posts, and news updates? Yeah, me too. Wouldn’t it be awesome to have a little helper that could just… poof… give you the gist?

Well, guess what? You can totally build that helper yourself! Today, we’re diving into a fun project: creating your very own AI-powered Telegram bot using the magic of n8n to summarize articles for you. Ready to automate your reading list? Let’s get started!

Why Bother with Automation?

Setting things up takes a little bit of effort upfront. But think about the payoff! Automating tasks like summarizing articles frees up your precious time and mental energy. Instead of manually copy-pasting or skimming, you get the core info delivered right where you are. It’s like having a super-efficient personal assistant!

So, What Awesome Thing Are We Building?

Picture this: you find an interesting article online, but you’re short on time. Instead of adding it to that ever-growing “read later” list, you just send the link (or even paste the text) to your personal Telegram bot.

Moments later, ding! Your bot replies with a neat, concise summary.

We need something that works anywhere – on your phone, tablet, or computer. That’s why a simple script or command-line tool won’t cut it. And building a whole web app? Way too much hassle for this! We want quick, effective, and cool.

Telegram: Your Bot’s New Best Friend

Telegram bot example

Why Telegram? It’s perfect for this job!

  1. Instant UI: A Telegram bot is the user interface. It’s familiar, works everywhere, and is super easy for chat-based interactions. No need to design buttons or pages!
  2. Super Simple Setup: Getting a bot ready is a breeze. Just chat with the BotFather (yes, that’s its actual name!).
    • Start a chat with BotFather and type /start, then /newbot.
    • Give your bot a friendly name (like “Article Summarizer Buddy”). This is what you’ll see in your chat list.
    • Pick a unique username for your bot (it must end in “bot”, e.g., MyArticleSumBot). Think of this as its official address.
    • Important! BotFather will give you an API Access Token. This is the key to controlling your bot. Keep it safe and secure like your favorite password!

n8n: Your Automation Superhero

Workflow

Now, how do we connect your Telegram bot to the AI smarts? Enter n8n!

n8n is a fantastic visual workflow automation tool. Think of it like digital Lego bricks – you connect different services and actions together to build powerful automations without getting bogged down in complex code (though you can add code if you want!). It’s perfect for building bots quickly and reliably.

Let’s Build the Workflow!

1. Listen for Telegram Messages (The Trigger)

Telegram trigger node

First, we need n8n to know when you send a message to your bot.

  • Add a Telegram Trigger node.
  • Connect it to your bot using the API token you saved earlier. (n8n makes adding credentials super easy and secure).
  • Set it to trigger whenever a new message arrives.

Telegram trigger node

2. Keep Your Bot Private (Optional but Smart!)

If node workflow

You probably don’t want everyone using your summarizer bot, right? Let’s add a simple check:

If node

  • Add an If node right after the trigger.
  • Configure it to check the userId from the incoming Telegram message. Does it match your Telegram User ID (you can just hard-code your id)?
    • If YES: Continue to the summarization part!
    • If NO: Send a polite “Sorry, this bot is private!” message back using a Telegram Send Message node.

This little step keeps your bot personal and prevents unexpected usage (and potential costs if you’re using paid AI services!).

3. The Core Magic: Fetching & Summarizing

HTTP Request node

Okay, here’s where the real intelligence comes in. When the ‘If’ node gives the green light (meaning it’s you!), we need to pass the message to our AI summarizer. This is where we get a bit technical, but don’t worry – I’ll guide you through it!

We will use a n8n HTTP Request node to call an AWS Lambda function. This function will handle the heavy lifting of fetching the article content and summarizing it.

  • Add an HTTP Request node after the ‘true’ output of the ‘If’ node.
  • Configure it to call the URL of your deployed Lambda function (we’ll cover the Lambda code next!).
  • Pass the message content from the Telegram trigger as data (e.g., in the JSON body { "content": "{{ $json.message.text }}" }).

HTTP Request node

Deep Dive: The Brains of the Operation (Our Lambda Function)

This Lambda function is the heart of our AI agent. Don’t worry if the code looks a bit daunting at first – we’ll break it down! We’re using TypeScript here, but the concepts apply to other languages too.

It does three main things: loads the article, prepares the AI prompt, and gets the summary.

Loading the Article Content

If you send a URL, we need to grab the actual text from that page. We use libraries like jsdom and @mozilla/readability to parse the HTML and extract the core article content, stripping out menus, ads, etc. It’s like getting just the juicy filling of a pie!

import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";

export const getArticleAsMarkdown = async (url: string): Promise<string> => {
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`Failed to fetch article: ${response.statusText}`);
  }

  const content = await response.text();
  const doc = new JSDOM(content);
  const reader = new Readability(doc.window.document);
  const article = reader.parse();

  return article
};

Summarization Time!

This is where the AI magic happens. We use a Large Language Model (LLM) – in this case, via Anthropic’s API (using the ChatAnthropic library with Langchain).

We need a good prompt to tell the AI exactly what we want. A well-crafted prompt is key to getting great summaries! We used Anthropic’s Console to help generate a solid starting prompt.

Anthropic Console

By describing our needs, we get a system prompt that guides the AI to summarize the article effectively. Here’s a simplified version of what we use:

export const SUMMARY_ARTICLE_SYSTEM_PROMPT = `You are tasked with shortening an article while retaining its most important information and overall value. Here is the article you need to summarize:
Your goal is to create a concise version of this article that includes the most crucial information while ensuring it doesn't lose its essential value. Follow these guidelines:

1. Identify the main topic and key points of the article.
2. Retain information that is central to understanding the article's purpose and message.
3. Keep important facts, statistics, and quotes that support the main ideas.
4. Eliminate redundant information, excessive examples, and tangential details.
5. Ensure that the shortened version still provides a coherent and comprehensive overview of the original article.

To accomplish this task, follow these steps:

1. Read the article carefully to understand its main topic and key points.
2. Highlight or note down the most important information, including crucial facts, statistics, and quotes.
3. Identify any redundant information, excessive examples, or tangential details that can be removed without affecting the article's core message.
4. Draft a shortened version of the article, focusing on the main ideas and essential supporting information.
5. Review your draft to ensure it captures the most important aspects of the original article and maintains its value.
6. Make any necessary adjustments to improve clarity and coherence.
7. Do not use markdown. Use bullet points or numbered lists only if they are present in the original article. Otherwise, use plain text.

Once you have completed the summarization process, provide your shortened version of the article within <shortened_article> tags. Aim for a length that is significantly shorter than the original while still conveying the most important information effectively.`;

export const createArticlePrompt = (document: string) => `Here is the article:
<article>
${document}
</article>
`;

Putting It All Together: The Lambda Handler

This is the main entry point for our Lambda function. It orchestrates the process:

  1. Gets the content (URL or text) sent from n8n.
  2. Checks if it’s a URL. If yes, calls getArticleAsMarkdown to fetch the content.
  3. Packages the article text with our system prompt.
  4. Sends it all to the Anthropic AI model using Langchain.
  5. Returns the AI-generated summary back to n8n.
export const handler = async (event) => {
  const { content } = JSON.parse(event.body!);

  let article = content;
  if (isURL(content)) {
    article = await getArticleAsMarkdown(content);
  }

  try {
    const messages = [
        new SystemMessage({
          content: [
            {
              type: "text",
              text: SUMMARY_ARTICLE_SYSTEM_PROMPT,
              cache_control: { type: "ephemeral" },
            },
          ],
        }),
        new HumanMessage({
          content: [
            {
              type: "text",
              text: createArticlePrompt(article),
            },
          ],
        }),
      ];
    const summary = await generateResponse(messages); // Calls the AI

    return jsonResponse(200, { summary });

  } catch (error) {
    return jsonResponse(500, { error: "Failed to generate summary" });
  }
};

async function generateResponse(messages) {
  const anthropic = createAnthropicClient()
  const stream = await anthropic.stream(messages);
  let buffer = "";
  for await (const chunk of stream) { 
    buffer += chunk.content;
  }
  return buffer.replace(/<[^>]*>?/gm, "");
}

(Note: The full code includes setup for the Anthropic client, error handling, etc., which are important but omitted here for brevity)

4. Sending the Summary Back to Telegram!

Telegram Send Message node

We’re almost there! The Lambda function sends the summary back to the n8n HTTP Request node. The final step is easy:

  • Add a Telegram Send Message node connected after the HTTP Request node.
  • Configure it to send the summary field received from the Lambda function back to the original chat (chatId from the trigger).

Send response to telegram

And… that’s it! Your workflow is complete! 🎉

Wrapping Up: You Built an AI Agent!

How cool is that? You’ve just wired up Telegram, n8n, and a powerful AI model to create a genuinely useful tool. No more dreading long articles – just send them to your bot and get the highlights delivered right to your chat.

What’s Next?

  • Customize the Prompt: Play around with the SUMMARY_ARTICLE_SYSTEM_PROMPT in your Lambda function. Want shorter summaries? Bullet points? A specific tone? Tell the AI!
  • Add More Features: Maybe translate the summary? Save summaries to a spreadsheet? Extract keywords? n8n has nodes for almost everything!
  • Explore More n8n: This is just scratching the surface. Check out other triggers, nodes, and templates n8n offers. The possibilities are endless!

Building automations like this is incredibly empowering. You took different services and made them work together seamlessly. Go ahead, give yourself a pat on the back, and enjoy your new summarization superpower!

Happy automating!