Create Telegram Bot Discord Bot Using Python [Easy to Understand Sample Code]

Tạo Telegram Bot Discord Bot Bằng Python [Code Mẫu Dễ Hiểu]

When I first started coding, I often had to do repetitive chores on Discord servers or Telegram channels for the team. From sending notifications, reminding meeting schedules, to filtering spam messages. After a while of groping, I realized that Python is the "true love" to completely solve those boring tasks. This article is Pham Hai's more than 10 years of practical experience, summarizing how to create a Telegram bot Discord bot with Python in the fastest way. I have prepared easy-to-understand sample code so you can copy-paste and test it immediately.

Create your first Telegram and Discord bot in 5 minutes [Sample Code]

Creating a basic bot now only takes a few minutes with available Python bot source code. You just need to install the library, paste the API Token and run the script and the bot can "say hi" to the world.

Code mẫu bot Telegram "Hello World" với thư viện python-telegram-bot

Thư viện python-telegram-bot là lựa chọn hàng đầu hiện nay để làm việc với Telegram Bot API. Nó hỗ trợ hoàn hảo lập trình bất đồng bộ Python, giúp bot xử lý hàng ngàn tin nhắn cùng lúc mà không bị nghẽn.

Cách tạo Telegram bot bằng Python thực ra rất đơn giản. Trước tiên, bạn mở terminal và gõ lệnh Pip cài đặt thư viện: pip install python-telegram-bot. Đây là thư viện Python để tạo Telegram bot cực kỳ mạnh mẽ và liên tục được cập nhật. Dưới đây là code mẫu tạo Telegram bot Python dễ hiểu dành cho bạn:

from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

async def hello(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(f'Hello {update.effective_user.first_name}')

if __name__ == '__main__':
    # Thay 'YOUR_TOKEN' bằng API Token thật của bạn
    app = ApplicationBuilder().token("YOUR_TOKEN").build()
    app.add_handler(CommandHandler("hello", hello))
    app.run_polling()

Đoạn code trên định nghĩa một Lệnh bot Telegram cơ bản. Khi người dùng gõ /hello, bot sẽ chào lại bằng tên của họ. Nếu bạn nhìn vào cú pháp async def và cảm thấy hơi bỡ ngỡ, việc xem lại Học Python cơ bản cho người mới bắt đầu sẽ là bước đệm tuyệt vời để bạn hiểu rõ hơn về cấu trúc ngôn ngữ này.

Code mẫu bot Discord phản hồi tin nhắn với thư viện discord.py

Tương tự như Telegram, discord.py là thư viện Python để tạo Discord bot phổ biến và ổn định nhất. Nó giúp bạn tương tác sâu với Discord API thông qua các event (sự kiện).

Hướng dẫn tạo Discord bot bằng Python bắt đầu bằng việc cài đặt thư viện qua lệnh pip install discord.py. Dưới đây là code mẫu Discord bot Python cho người mới, giúp bot tự động trả lời khi có người chat từ "ping":

import discord


intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'Bot đã đăng nhập thành công với tên {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('ping'):
        await message.channel.send('Pong! Phạm Hải xin chào!')


client.run('YOUR_DISCORD_TOKEN')

Building a Discord bot to manage a Python server with the above code helps you grasp the most basic bot event handling flow. Its applications are very wide, from moderating words to welcoming new members. To upgrade these workflows to full enterprise automation, you can learn more about Python workflow automation.

So sánh nhanh 2 thư viện: python-telegram-botdiscord.py

Cả hai thư viện đều dùng lập trình bất đồng bộ (async/await) nhưng cấu trúc có chút khác biệt. discord.py nặng về lắng nghe sự kiện (event-driven), trong khi Telegram thiên về xử lý luồng tin nhắn thông qua các Handler.

At Pham Hai, we find that programming automatic Telegram bots with Python is often more accessible at the initial setup stage. The chat interface of Telegram Channel is quite simple and direct. In contrast, the Discord API allows extremely deep customization of the Discord Guild structure, Discord Channels and Discord Servers (permissions, voice channels, roles).

Criteria python-telegram-bot discord.py
Cấu trúc chính Handlers (CommandHandler, MessageHandler) Events (@client.event)
Độ phức tạp API Average, easy to grasp High, many concepts (Guild, Role, Intents)
Thế mạnh Send quick notifications, 1-1 chatbot Manage a large, moderated Discord community

Prepare necessary "tools" before coding

Before writing the first lines of code, you need to apply for permission from the platform. It's about getting the API Token identifier and setting up a standard Python programming environment just to avoid minor errors.

With Telegram: Get API Token from "Godfather" BotFather in 1 minute.

BotFather is Telegram's "official" tool used to create and manage all bots. You just need to chat with it with a few simple commands to receive a secret API Token string.

Cách lấy API token BotFather Telegram rất trực quan. Bạn mở app Telegram, gõ vào thanh tìm kiếm @BotFather (nhớ chọn đúng tài khoản có dấu tích xanh). Bấm Start, sau đó gõ lệnh /newbot. BotFather sẽ hỏi bạn muốn đặt tên bot là gì và username ra sao (bắt buộc phải kết thúc bằng chữ bot, ví dụ: phamhai_test_bot). Xong xuôi, nó sẽ trả về cho bạn một đoạn mã dài (API Token). Hãy lưu nó lại cẩn thận, vì bất cứ ai có mã nguồn bot Python và token này đều có thể điều khiển bot của bạn.

With Discord: Create Application and get Token in Discord Developer Portal.

Discord requires slightly stricter security. You must create an application on the developer portal before you can generate a Token for the bot.

How to create a Discord Developer Portal application includes the following steps:

  1. Visit the Discord Developer Portal page and log in.
  2. Click the New Application button in the right corner and name the project.
  3. Switch to the Bot menu on the left sidebar, click Add Bot.
  4. Here, click Reset Token and copy the code string that appears.

Sau khi có token, bạn cần tạo link mời bot vào Server Discord của bạn thông qua tab OAuth2 -> URL Generator (tích chọn bot và các quyền cần thiết). Nếu bạn đang xây dựng các hệ thống backend phức tạp hơn để cấp nguồn dữ liệu cho bot, bài viết hướng dẫn Tạo API backend bằng AI trong 10 phút sẽ là một tài liệu tham khảo rất đáng giá.

Setting up the environment and libraries: Advice on using a virtual environment

The Python virtual environment helps isolate one project's libraries from another. This ensures that when you update the library in project A, it will not break the code in project B.

Với kinh nghiệm xử lý lỗi lập trình bot cho rất nhiều dự án, mình luôn khuyên anh em dùng venv. Mở terminal tại thư mục dự án và chạy python -m venv myenv. Sau đó kích hoạt nó (trên Windows là myenvScriptsactivate, trên Mac/Linux là source myenv/bin/activate). Cuối cùng mới dùng Pip cài đặt thư viện. Việc thiết lập môi trường chuẩn ngay từ đầu cũng giống như việc bạn xây dựng nền móng vững chắc cho các hệ thống tự động hóa; hiểu rõ RPA là gì tự động hóa quy trình sẽ cho bạn tư duy tổ chức hệ thống tốt hơn rất nhiều.

Upgrade bot with useful features

Bots don't just say "Hello World". You can completely turn it into a powerful assistant by adding complex commands, automating notification delivery, and optimizing performance with asynchronous programming.

Commands: Teach the bot how to "listen" and respond to specific requests

Lệnh bot Telegram thường bắt đầu bằng dấu gạch chéo / (ví dụ /start, /help), trong khi Lệnh bot Discord có thể tùy biến prefix thoải mái (ví dụ !play, ?info).

Tạo bot Discord xử lý lệnh Python trở nên cực kỳ nhàn hạ nếu bạn dùng module discord.ext.commands. Thay vì dùng on_message và kiểm tra chuỗi rườm rà, bạn chỉ cần dùng decorator @bot.command(). Tương tự, Telegram có các Handler chuyên dụng. Hiện nay, xu hướng tạo chatbot AI Telegram bằng Python đang lên ngôi. Bạn có thể tích hợp thư viện Chatterbot, framework Flask để làm webhook, hoặc mạnh mẽ hơn là gọi API của OpenAI để xử lý ngôn ngữ tự nhiên (NLP). Nếu bạn hứng thú với việc đưa AI vào ứng dụng thực tế, hãy xem ngay cách Tạo chatbot AI cho website bằng ChatGPT API.

Send automatic notifications: Integrate bots to send alerts from servers or websites

Sending automatic messages in Python helps your team update real-time system status right on the group chat without having to open email or dashboard.

Tạo bot Telegram gửi thông báo Python khi server có dấu hiệu quá tải, hoặc khi có đơn hàng mới trên website là use-case (trường hợp sử dụng) phổ biến nhất. Bạn chỉ cần lấy chat_id của nhóm, sau đó dùng hàm bot.send_message(chat_id, text) chạy dưới dạng một tác vụ ngầm (cronjob). Quản lý cộng đồng Discord cũng nhàn hơn hẳn khi bạn setup bot tự động chào mừng người mới hoặc cảnh báo khi có link spam.

Asynchronous Programming (Asyncio): Why is it important for both Telegram and Discord bots?

Python asynchronous programming (async/await) helps the bot not "freeze" when waiting for a response from a third-party API or waiting for a database query. It allows the bot to handle thousands of users at the same time.

Từ các bản cập nhật gần đây (tính đến năm 2026), cả hai thư viện discord.pypython-telegram-bot đều bắt buộc sử dụng kiến trúc asyncio. Nghĩa là bạn không thể dùng hàm time.sleep() thông thường nữa (nó sẽ chặn toàn bộ luồng chạy của bot). Thay vào đó, bạn phải làm quen với await asyncio.sleep(). Việc nắm vững Tự động hóa tác vụ Python bằng kiến trúc bất đồng bộ là bắt buộc nếu bạn muốn bot của mình chạy mượt mà trên môi trường production.

Deploy a bot that runs 24/7 and issues to note

After coding on your personal computer, the bot will only be online when you turn on the computer. In order for the bot to "live" 24/7 to serve the community, you need to put it on a server and pay attention to security issues.

Instructions for deploying a bot to a free server (eg Heroku, PythonAnywhere)

Putting code on the cloud (Deploy) helps the bot operate continuously without stopping. Currently, there are many platforms that support running Python scripts 24/7 at extremely low cost or for free.

Deploying a Telegram Python bot on a server or deploying a free Discord Python bot can be done easily via platforms such as Render, Railway or PythonAnywhere. Previously, Deploy bot Heroku was very popular with the free package. Although they now charge a fee, the basic packages are still very cheap and worth using. You just need to push the code to GitHub, connect the repository to the cloud platform and set up the command to run. If you want to combine self-coding bots with drag-and-drop workflows without complicated programming, n8n free workflow automation is a great tool for data synchronization.

Polling vs. Webhooks: Which method should I choose for my Telegram bot?

Polling bot is a bot mechanism that continuously "asks" the Telegram server if there are new messages (asking every few seconds). Telegram webhooks are the opposite, the Telegram server will proactively "notify" the bot as soon as an event occurs.

Trong giai đoạn dev (phát triển) trên máy local, bạn cứ dùng Polling (app.run_polling()) cho đơn giản. Nhưng khi đã đưa lên server thật, mình khuyên bạn bắt buộc phải setup Webhook Telegram. Nó giúp tiết kiệm tài nguyên mạng, giảm độ trễ và bot phản hồi gần như tức thì. Để hiểu sâu hơn về cách các ứng dụng giao tiếp realtime với nhau thông qua webhook, bài viết về Make (Integromat) tự động hóa nâng cao sẽ cung cấp cho bạn một góc nhìn hệ thống rất sắc bén.

Manage environment variables (.env) to secure API Tokens.

Tuyệt đối không bao giờ gõ trực tiếp (hardcode) API Token vào trong các file mã nguồn .py. Hãy dùng file .env để bảo vệ an toàn cho "chìa khóa" của bot.

Bạn cần cài đặt thư viện python-dotenv để đọc dữ liệu từ file Biến môi trường (.env). Nếu bạn lỡ đẩy file code chứa token lên GitHub ở chế độ Public, các con bot dò quét của hacker sẽ đánh cắp token đó chỉ trong vài giây và dùng bot của bạn để đi spam lừa đảo. Trong các hệ thống tự động, bảo mật kết nối là yếu tố sống còn; bạn có thể tham khảo Zapier hướng dẫn tự động hóa cho người mới để biết cách các nền tảng lớn quản lý key an toàn như thế nào.

What are Discord Intents and why do you need to declare them?

Discord Intents is Discord's granular permissions system. You must clearly declare in the code and on the Developer Portal that the bot needs to read message content or follow members for Discord to grant permission.

Rất nhiều bạn mới học code nhắn hỏi mình: "Anh ơi sao bot Discord của em online nhưng chat nó không thèm rep?". 99% lỗi là do quên bật Message Content Intent. Bạn phải vào tab Bot trên Discord Developer Portal, gạt công tắc xanh ở phần Privileged Gateway Intents, đồng thời khai báo intents.message_content = True trong code.

Recently, finding a solution to replace Telegram in Vietnam with Discord bot Python has been of interest to many businesses and communities due to some issues with platform censorship. Although messaging applications such as Signal, WhatsApp, Viber, Zalo are also very popular and secure, Discord's API is still open, rich in documentation and much easier to program and automate. That's why Discord is becoming a new destination for many technology teams.

In short, creating a Telegram bot Discord bot using Python is not as complicated as you might think at first. With just a few steps to prepare the API, set up the environment and a few dozen lines of basic code, you can automate countless daily tasks. Don't be afraid to experiment, copy the sample code in the article, customize them to add or remove features and create your own powerful "virtual assistant". The possibilities of bots are limitless, it only depends on your creativity and actual needs.

Have you created your own bot yet? Show off your results immediately or if you have any problems at any step (from library errors to deployment), don't hesitate to leave a comment below, Pham Hai will help answer as best as possible!

Lưu ý: Các thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.

Categories: Lập Trình Web Python

mrhai

Để lại bình luận