AI Agents: What They Are and How to Build a Telegram Bot with Claude Code
This guide clarifies that AI agents are not a category but a spectrum from simple chat to autonomous loops, defined by tools, memory, and a loop. It then provides a no-code, step-by-step tutorial on building a Telegram bot agent with Claude Code, including system prompt templates, systemd deployment, persistent memory, cost tracking, and practical skills. Also addresses the common memory problem and offers concrete fixes. Suitable for engineers who want a practical agent without writing code themselves.
Everyone is talking about AI agents. But if you ask most people what an agent actually is, you get a vague answer about "AI that does things autonomously."
The real picture is more useful than that. Agents are not a category. They are a spectrum.
This guide explains where on that spectrum different AI tools sit, what separates a basic LLM interaction from a true agentic workflow, and how to build your own agent with Claude Code and connect it to Telegram, without writing code yourself.
人人都在谈论 AI 代理(AI Agent)。但若你问大多数人代理到底是什么,得到的回答通常是模糊的一句“能自主做事的 AI”。
实际情况比这要有用得多——代理不是一个类别,而是一个频谱。
本指南将说明不同 AI 工具在这个频谱上所处的位置,基本的大模型交互与真正的代理式工作流之间的差别,以及如何用 Claude Code 构建你自己的代理并接入 Telegram,全程不需要自己写代码。
Asking Claude "what should I post today?" is not an agent. That is a chat.
Telling Claude "find the three topics trending in AI right now, pick the one with the most engagement potential, draft a post in my style, and save it to a file" and having it do all of that without you touching anything, that is an agent.
The difference is not the model. It is the structure around it.
An agent has three things a regular chat does not. Tools it can call on its own: search, file systems, code execution, external APIs. Memory that persists across tasks, not just within one session. And a loop that keeps running until the task is finished, not until it generates one response.
The more of those three things you add, the less you are involved. That is the idea.
问 Claude“我今天该发什么?”——这不是代理,这是聊天。
告诉 Claude“找出当前 AI 领域最热的三个话题,选一个互动潜力最高的,按我的风格写一篇帖子,然后保存到文件”,然后让它全部自动完成,无需你触碰任何东西——这才是代理。
差别不在模型本身,而在模型外围的结构。
普通聊天所不具备的,代理拥有三个要素:
- 工具:它能自主调用搜索、文件系统、代码执行、外部 API;
- 记忆:能跨任务持久化,而不仅限于单次会话;
- 循环:持续运行直到任务完成,而非在生成一次回复后就结束。
这三者越完善,你的介入就越少——这就是核心理念。
At one end you have a basic chat. You ask, Claude answers, the session ends. No tools, no ongoing goal, no ability to act in the world.
One step up: Claude with tools enabled. When Claude searches the web before answering, reads an attached file, or generates an image, it is already slightly agentic. You did not tell it to do those things step by step, it decided on its own that it needed to.
Further up: multi-step workflows. You give a goal, Claude breaks it into steps, executes each one, checks the result, and delivers a finished output. You are not involved between steps.
At the top: fully autonomous agents. The agent runs on a schedule, monitors inputs, calls external services, and completes complex tasks without a human in the loop. You set the goal once and check the output.
The difference between the bottom and the top is not a different model. It is what surrounds the model, tools it can call, memory that carries context, and a loop that keeps running until the task is done.
频谱的一端是基础聊天——你提问,Claude 作答,会话结束。没有工具、没有持续的目标、没有在现实世界中行动的能力。
再上一级:开启了工具的 Claude。当 Claude 在回答前搜索网络、读取附件或生成图片时,它已经具备了一点代理性——你并没有一步步告诉它去做这些,它自己判断需要这么做。
再往上:多步骤工作流。你给出一个目标,Claude 将其拆解为步骤,逐一执行,检查结果,并交付最终产出。你在步骤之间无需参与。
最顶端则是全自主代理:代理按计划自动运行,监控输入,调用外部服务,完成复杂任务,全程无需人类介入。你只需设定一次目标,然后检查最终输出。
从底层到顶层的区别,不在于使用了不同的模型,而在于模型周围的一切——它能调用的工具、承载上下文的记忆、以及持续运行直到任务完成的循环。
To give you a sense of what agents can actually look like today, I put together a few examples below. These are not limits you can build whatever fits your specific situation.
Research agent: gathers information on a topic, reads multiple sources, pulls out what matters, and delivers a structured summary. You give it a question. It gives you an answer that would have taken hours to compile manually.
Writing agent: writes content according to a system you define. Give it your tone, format, audience, and topic. It handles drafts, rewrites, and edits without you managing every sentence.
Code agent: writes code, runs it, reads the errors, fixes them, and keeps going. You describe what the code should do. The agent handles the implementation and debugging loop.
Business agent: Handles repetitive business tasks: drafting emails, processing customer requests, qualifying leads, generating reports. Runs on autopilot once you define the rules.
Personal agent: Manages your schedule, organizes tasks, prepares briefings, and handles the planning work you do manually every day.
为了让你对当下代理的真实形态有个概念,这里给出几个示例。它们并非局限——你可以构建任何符合你具体情况的代理。
- 研究代理:搜集某一主题的信息,阅读多个来源,提取关键内容,给出结构化的总结。你提出问题,它给出答案——这些答案换作人工整理可能要花数小时。
- 写作代理:按照你定义的体系创作内容。你给出语气、格式、受众和主题,它负责起草、重写和编辑,无需你逐句过问。
- 代码代理:编写代码、运行代码、读取错误、修复错误,如此循环。你描述代码要实现的功能,代理负责实现和调试的循环。
- 业务代理:处理重复性业务任务——起草邮件、处理客户请求、筛选潜在客户、生成报告。一旦你定义了规则,它就能自动运行。
- 个人代理:管理日程、组织任务、准备简报,处理你每天手动完成的规划工作。
You will use Claude Code to build a Telegram bot that runs on a remote server and uses Claude as its brain. Claude Code writes all the code for you, you just describe what you want in plain English. Once it is set up, all communication with the bot happens directly through Telegram.
The whole setup takes about 10-20 minutes. You do not need to know how to code.
你将使用 Claude Code 来构建一个在远程服务器上运行的 Telegram 机器人,以 Claude 作为其“大脑”。Claude Code 会为你编写所有代码,你只需用纯英文描述你想要什么即可。设置完成后,与机器人的所有交互都直接通过 Telegram 进行。
整个过程大约需要 10–20 分钟,你不需要会写代码。
When you run Prompt 2 from the setup below, you need to describe what kind of agent you want. These are ready-made templates, copy the one that fits, paste it into Prompt 2 where it says "The agent should be:", and Claude Code will build that specific agent. Adjust any details to match your situation.
Research Agent
You are a research agent. Your job is to gather, analyze, and synthesize information on any topic I give you.
When given a research task:
1. Identify the 3-5 most important sub-questions to answer
2. Search for information on each one
3. Evaluate the quality and relevance of each source
4. Extract only what directly answers the question
5. Deliver a structured summary with: key findings, supporting evidence, and gaps you could not fill
Format: Use headers, bullet points, and clear sections.
If you are uncertain about something, say so explicitly.
Do not add filler. Every sentence should contain information.
Writing Agent
You are a writing agent. You write content in my voice and style.
My style:
- Conversational, direct, no corporate language
- Short sentences and paragraphs
- Specific numbers and examples over vague claims
- Always end with something the reader should do or think about
When given a writing task:
1. Ask for the topic, audience, and desired length if not provided
2. Write a first draft
3. Review it against my style rules
4. Deliver the final version ready to publish
Never add unnecessary introductions. Start with the most important point.
Code Agent
You are a code agent. Your job is to write, debug, and improve code.
When given a coding task:
1. Confirm your understanding of what the code should do
2. Write the solution with clear comments
3. Identify any edge cases or potential failures
4. If there are errors, debug them systematically before asking for help
Rules:
- Write clean, readable code with meaningful variable names
- Always include error handling
- Explain what each major section does in plain language
- If you are unsure about requirements, ask one clarifying question before proceeding
Business Email Agent
You are a business email agent. You write professional emails on my behalf.
My communication style:
- Direct and respectful
- No unnecessary formalities
- Gets to the point in the first sentence
- Closes with a clear next step
When given an email task:
1. Identify the goal of the email (inform, request, follow up, confirm)
2. Write a subject line that reflects the email's purpose
3. Draft the email in 3-5 short paragraphs maximum
4. End with one clear action item or next step
Always write ready-to-send emails, not templates with blanks to fill in.
Personal Planning Agent
You are my personal planning agent. You help me organize my work, prioritize tasks, and plan my week.
When I share my tasks or goals:
1. Identify what is urgent vs. important
2. Suggest a realistic sequence based on dependencies
3. Estimate time required for each task
4. Flag anything that could be delegated or eliminated
When I describe a project:
- Break it into concrete next actions
- Identify the single most important thing to do first
- Create a simple checklist I can follow
Keep everything practical. No motivational filler. Just the plan.
当你运行下面步骤中 Prompt 2 时,需要描述你想要的代理类型。以下这些是现成的模板,复制适合你的那个,粘贴到 Prompt 2 中“The agent should be:”的位置,Claude Code 就会构建对应的代理。你可以根据需要调整任何细节。
研究代理
你是一名研究代理。你的工作是收集、分析和综合我给出的任何主题的信息。
当接到研究任务时:
1. 识别出 3-5 个最重要的子问题
2. 针对每个子问题搜索信息
3. 评估每个来源的质量和相关性
4. 只提取直接回答问题的内容
5. 提供结构化的总结,包含:关键发现、支撑证据以及未能填补的空白
格式要求:使用标题、列表和清晰的分段。
如果对某事不确定,请明确说明。
不要添加废话。每个句子都应包含信息。
写作代理
你是一名写作代理。你使用我的语气和风格来创作内容。
我的风格:
- 口语化、直接,没有公文腔
- 短句和短段落
- 用具体数字和例子替代模糊的说法
- 结尾总要给读者一个行动或思考的引导
当接到写作任务时:
1. 如果没有提供,请询问主题、目标读者和期望长度
2. 写第一稿
3. 对照我的风格规则审查
4. 交付可直接发布的最终版本
不要添加不必要的开场白。从最重要的点开始。
代码代理
你是一名代码代理。你的工作是编写、调试和改进代码。
当接到编程任务时:
1. 确认你理解了代码需要做什么
2. 编写带有清晰注释的解决方案
3. 识别任何边界情况或潜在失败点
4. 如果出现错误,在求助之前系统性地调试
规则:
- 编写干净、可读的代码,使用有意义的变量名
- 始终包含错误处理
- 用通俗语言解释每个主要部分的功能
- 如果对需求不确定,在继续之前先问一个澄清性问题
商务邮件代理
你是一名商务邮件代理。你代表我撰写专业邮件。
我的沟通风格:
- 直接且尊重
- 没有不必要的繁文缛节
- 第一句话就切入主题
- 以明确的下一步行动收尾
当接到邮件任务时:
1. 确定邮件的目的(告知、请求、跟进、确认)
2. 编写能反映邮件目的的主题行
3. 将邮件正文控制在最多 3-5 个短段落
4. 以一个清晰的操作项或下一步结束
始终撰写可以直接发送的邮件,而不是留有空白等待填充的模板。
个人规划代理
你是我的个人规划代理。你帮助我组织工作、确定任务优先级并规划一周。
当我分享我的任务或目标时:
1. 识别紧急任务与重要任务
2. 根据依赖关系建议合理的执行顺序
3. 估算每项任务所需时间
4. 标出任何可以委托或取消的事项
当我描述一个项目时:
- 将其拆解为具体的下一步行动
- 确定最优先做的最重要的一件事
- 创建一份可以遵循的简单清单
一切保持实用。不要打鸡血。只要计划。
1 - a Claude API key from console.anthropic.com. This is a developer key, you pay per usage, not a fixed monthly fee. For a personal bot sending 50 messages a day, the cost is $1-5 per month depending on which model you choose.
2- a Telegram bot token from BotFather.
3 - a VPS running Linux. For a personal Telegram bot you do not need anything powerful - 1 CPU, 1GB RAM, and 20GB of storage is more than enough. Any basic plan from DigitalOcean, Hetzner, or Vultr will work, and costs around $4 to $6 per month. Once you have the server, install Claude Code by running npm i -g @anthropic-ai/claude-code in your terminal.
- 从 console.anthropic.com 获取 Claude API 密钥。这是开发者密钥,按使用量付费,而非固定月费。对于每天发送 50 条消息的个人机器人,根据所选模型,每月费用约为 1–5 美元。
- 从 BotFather 获取 Telegram 机器人 token。
- 一台运行 Linux 的 VPS(虚拟专用服务器)。对于个人 Telegram 机器人,不需要强大配置——1 核 CPU、1GB 内存和 20GB 存储就绰绰有余。DigitalOcean、Hetzner 或 Vultr 的任何基础套餐即可,月费约 4–6 美元。获得服务器后,在终端运行
npm i -g @anthropic-ai/claude-code安装 Claude Code。
For most personal bots Sonnet 4.6 is the right choice, strong enough for any task and affordable for daily use. Use Haiku 4.5 if you want to minimize cost. Opus 4.8 only makes sense for a complex analytical agent where answer quality is critical.
对于大多数个人机器人,Sonnet 4.6 是合适的选择——它足以胜任任何任务,且日常使用成本可接受。如果想要最低成本,可以使用 Haiku 4.5。Opus 4.8 仅在你需要复杂分析型代理且回答质量至关重要时才值得选择。
Open your VPS terminal and launch Claude Code. Paste this prompt and let it build everything.
Build me a Telegram bot that uses the Claude API as its brain.
Requirements:
- Language: Python
- Library for Telegram: python-telegram-bot
- Claude model: claude-sonnet-4-6
- The bot receives a message, sends it to Claude API, and returns Claude's response to Telegram
- Maintain conversation history per user — each user has their own context within the session
- Add a /start command that introduces the bot
- Add a /clear command that resets conversation history for that user
Create all necessary files: main bot file, requirements.txt, and a .env file template for API keys.
Do not hardcode any API keys — read them from environment variables.
打开你的 VPS 终端,启动 Claude Code。粘贴以下提示,让它为你构建所有代码:
请为我构建一个以 Claude API 为大脑的 Telegram 机器人。
需求:
- 语言:Python
- Telegram 库:python-telegram-bot
- Claude 模型:claude-sonnet-4-6
- 机器人接收消息,发送给 Claude API,并将 Claude 的响应返回给 Telegram
- 为每个用户维护对话历史——每个用户在会话中拥有自己的上下文
- 添加 /start 命令介绍机器人
- 添加 /clear 命令重置该用户的对话历史
创建所有必需的文件:主机器人文件、requirements.txt 以及用于 API 密钥的 .env 文件模板。
不要硬编码任何 API 密钥——从环境变量中读取。
Create a systemd service file so this bot runs automatically on my Linux VPS and restarts if it crashes.
The service should:
- Start automatically when the server boots
- Restart automatically if it crashes
- Load environment variables from the .env file in the project folder
- Save logs to a file I can check later
Also write me the exact terminal commands to install the service, start it, check if it is running, and view the logs.
创建一个 systemd 服务文件,使这个机器人在我的 Linux VPS 上自动运行,并在崩溃时自动重启。
该服务应:
- 在服务器启动时自动启动
- 在崩溃时自动重启
- 从项目文件夹中的 .env 文件加载环境变量
- 将日志保存到我可以稍后查看的文件中
同时提供确切的终端命令,用于安装服务、启动服务、检查服务是否在运行以及查看日志。
The bot loses conversation history when it restarts. Fix this.
Save each user's conversation history to a JSON file on disk after every message. Load it back automatically when the bot starts.
Add a maximum history length — keep only the last 20 messages per user so the context window never gets too long.
机器人在重启后会丢失对话历史。修复这个问题。
每次消息后,将每个用户的对话历史保存到磁盘上的 JSON 文件中。当机器人启动时自动加载回来。
添加最大历史长度限制——每个用户只保留最近 20 条消息,这样上下文窗口就不会过长。
Add web search capability to the bot using the Tavily API.
When the user asks something that requires current information — news, prices, recent events — the bot automatically searches the web and includes the results in its response.
The bot should decide on its own when to search and when to answer from memory. Add TAVILY_API_KEY to the .env file template.
Use Claude's tool use feature to implement this cleanly.
使用 Tavily API 为机器人添加网络搜索能力。
当用户询问需要实时信息的内容(如新闻、价格、近期事件)时,机器人自动搜索网络并将结果纳入回复。
机器人应自行判断何时需要搜索、何时可以从记忆中回答。将 TAVILY_API_KEY 添加到 .env 文件模板中。
使用 Claude 的 tool use(工具调用)功能干净地实现此特性。
Add a note-saving feature to the bot.
When the user says "save this", "remember this", or "note:", the bot saves the content to a notes.txt file with a timestamp.
Add a /notes command that returns the last 10 saved notes.
Add a /clearnotes command that deletes all saved notes.
为机器人添加笔记保存功能。
当用户说“保存这个”、“记住这个”或“note:”时,机器人将内容连同时间戳保存到 notes.txt 文件中。
添加 /notes 命令,返回最近保存的 10 条笔记。
添加 /clearnotes 命令,删除所有已保存的笔记。
Add user restriction to the bot so only I can use it.
Add my Telegram user ID to the .env file as ALLOWED_USER_ID.
If anyone else messages the bot, it responds with "This bot is private." and ignores all further messages from that user.
Also add how I can find my own Telegram user ID — either through the bot itself or another method.
为机器人添加用户限制,使其仅限我本人使用。
将我的 Telegram 用户 ID 添加到 .env 文件中,作为 ALLOWED_USER_ID。
如果有其他人向机器人发送消息,机器人回复“此机器人为私有”并忽略该用户的所有后续消息。
同时添加如何找到自己 Telegram 用户 ID 的方法——可以通过机器人本身或其他方式。
Add basic cost tracking to the bot.
After each Claude API response, log the number of input tokens and output tokens used.
Keep a running total in a costs.json file.
Add a /costs command that shows: total tokens used today, total tokens used all time, and an estimated cost in USD based on claude-sonnet-4-6 pricing.
为机器人添加基础费用追踪功能。
每次 Claude API 响应后,记录使用的输入 token 和输出 token 数量。
在 costs.json 文件中维护累计总数。
添加 /costs 命令,显示:今日使用的总 token 数、历史总 token 数,以及基于 claude-sonnet-4-6 定价估算的美元费用。
Add a scheduled daily briefing to the bot.
Every day at 8:00am, the bot sends me a message with:
1. A motivational one-liner (short, not cheesy)
2. A reminder to check my top priority for the day
3. One random useful fact about productivity or AI
Send it to my Telegram user ID from the .env file.
Use the schedule or APScheduler library to implement this.
为机器人添加定时每日简报功能。
每天上午 8:00,机器人给我发送一条包含以下内容的消息:
1. 一句励志短句(简短,不油腻)
2. 提醒我检查当天的最高优先事项
3. 一个关于效率或 AI 的实用冷知识
消息发送到 .env 文件中配置的我的 Telegram 用户 ID。
使用 schedule 或 APScheduler 库来实现。
How to update your agent's personality. Open the main bot file, find the system prompt variable at the top, change it, save the file, and restart the service with sudo systemctl restart your-bot-name. The new personality is live immediately.
How to check if the bot is running. Run sudo systemctl status your-bot-name in your terminal. If it says "active (running)" it is working. If it says "failed" check the logs.
How to read logs. Run journalctl -u your-bot-name -n 50 to see the last 50 lines. This is where you find error messages if something breaks.
How to add a new skill. Open Claude Code in your project folder and describe what you want: "Add X feature to the bot." Claude Code reads your existing code, adds the new feature cleanly, and tells you if a restart is needed.
如何更新代理的性格:打开主机器人文件,找到顶部的 system prompt 变量,修改后保存文件,然后运行 sudo systemctl restart your-bot-name 重启服务。新性格即刻生效。
如何检查机器人是否在运行:在终端运行 sudo systemctl status your-bot-name。如果显示“active (running)”,说明它在正常工作;如果显示“failed”,则去检查日志。
如何读取日志:运行 journalctl -u your-bot-name -n 50 查看最近 50 行日志。如果出问题,这里会显示错误信息。
如何添加新技能:在项目文件夹中启动 Claude Code,描述你想要的功能:“为机器人添加 X 功能。”Claude Code 会读取你现有的代码,干净地添加新功能,并告知是否需要重启。
This is the most common problem people run into. The agent loses context between sessions, across long tasks, after too many messages and starts making mistakes or repeating work it already did.
There are three ways this happens:
Long tasks eventually exceed Claude's context limit, and the agent starts losing the beginning of the conversation: the original goal, decisions already made, constraints you set.
When you close a session and open a new one, the agent starts from zero.
If the agent is interrupted mid-task, it has no way to know where it stopped.
这是人们最常遇到的问题。代理会在会话之间、跨长任务时、以及收到过多消息后丢失上下文,然后开始犯错或重复已经做过的工作。
问题出现在三种情形中:
- 长任务最终超出 Claude 的上下文限制,代理会丢失对话起始部分——原始目标、已做的决策、你设置的限制条件。
- 关闭一个会话并开启新会话时,代理从零开始。
- 代理在任务中途被中断时,它无法知道自己停在了哪里。
Four things can fix this:
Tell the agent to write a progress note after every major step: what was done, what was decided, what still needs to happen. Paste that note at the start of the next session to restore full context.
Every ten to fifteen messages, ask the agent to summarize where it is. This forces it to compress context before it overflows.
Before the conversation gets too long, ask the agent to compress everything into a short summary and continue from there. The thread stays intact.
Add the key facts your agent always needs directly to the system prompt in your bot code. Claude reads this at the start of every conversation, so that information is always in context no matter how long things get.
有四种方法可以解决这个问题:
- 进度笔记法:告诉代理在每个主要步骤后写一份进度笔记——做了什么、决定了什么、还需要做什么。在下一个会话开始前粘贴这篇笔记,即可恢复完整上下文。
- 定期总结法:每 10–15 条消息,要求代理总结当前进度。这迫使它在上下文溢出之前进行压缩。
- 压缩续写法:在对话变得过长之前,让代理将所有内容压缩成简短摘要,并从此继续。会话线程保持完整。
- 系统提示固化法:将代理始终需要的关键事实直接添加到机器人代码的 system prompt 中。Claude 在每次对话开始时都会读取它,因此无论对话进行多久,这些信息始终在上下文中。
Checkpoint Prompt
Before we continue, write a brief checkpoint:
1. What have you completed so far?
2. What are the key decisions or findings from this session?
3. What still needs to be done?
4. What context would you need to continue this task in a new session?
Keep it under 200 words.
Memory File Prompt
After completing each major step, write a memory note in this format:
STEP COMPLETED: [what was done]
KEY DECISIONS: [choices made and why]
CURRENT STATE: [where the task stands now]
NEXT STEP: [what should happen next]
This note will be used to resume the task in a new session without losing context.
Context Recovery Prompt
We are resuming a task from a previous session. Here is the context:
[paste your memory note here]
Based on this:
1. Confirm your understanding of where we are
2. Identify the next step
3. Ask any questions needed to continue
Do not repeat work that has already been completed.
Rolling Summary Prompt
The conversation is getting long. Compress everything important into a summary:
1. Original goal
2. What has been done and what was found
3. Key decisions made
4. What still needs to happen
After writing the summary, continue from there. Treat this summary as the new starting point.
检查点提示词
在我们继续之前,请写一份简要检查:
1. 你到目前为止完成了什么?
2. 本次会话的关键决策或发现是什么?
3. 还需要做什么?
4. 在新会话中继续此任务,你需要什么上下文?
控制在 200 字以内。
记忆文件提示词
完成每个主要步骤后,按以下格式写一条记忆笔记:
步骤完成:[做了什么]
关键决策:[做出的选择及原因]
当前状态:[任务现在进行到哪一步]
下一步:[接下来应该做什么]
这条笔记将用于在新会话中恢复任务,而不会丢失上下文。
上下文恢复提示词
我们从之前的会话中恢复一个任务。以下是上下文:
[在此粘贴你的记忆笔记]
基于此:
1. 确认你对我们当前进度的理解
2. 确定下一步骤
3. 提出继续所需的任何问题
不要重复已完成的工作。
滚动摘要提示词
对话变长了。将所有重要内容压缩成一份摘要:
1. 原始目标
2. 已完成的内容及发现
3. 已做的关键决策
4. 还需要做什么
写下摘要后,从那里继续。将此摘要视为新的起点。