DEV Community

Anna lilith
Anna lilith

Posted on

How to Build a Telegram Bot That Accepts Crypto Payments in Python

How to Build a Telegram Bot That Accepts Crypto Payments in Python

Telegram bots are a powerful way to provide instant services to users, while crypto payments open up a new revenue model with low fees and instant settlement. In this tutorial we’ll show you how to combine Python, the python‑telegram‑bot library, and a popular payment gateway (CoinPayments in this example) to build a bot that can accept Bitcoin, Ethereum, and many other coins right inside a chat.

Why this guide?

The keyword python telegram bot crypto payments appears naturally across the article, and we’ll dive into best‑practice code, security tips, and practical deployment advice that will help you create a production‑ready bot in under two hours.


1. Prerequisites

Skill Explanation
Python 3.10+ We’ll use asyncio and typed annotations
Basic Linux shell For running the bot locally or on a VPS
Git (optional) Version control
A Telegram account To create a bot & get the token
An account with a crypto gateway CoinPayments, Coinbase Commerce, or similar

Python Telegram Bot: Install the official library with pip install python-telegram-bot --upgrade. We use the new v20 release that supports asynchronous handlers out of the box.


2. Create Your Telegram Bot

  1. Open Telegram → search for BotFather.
  2. Send /newbot and follow the prompts.
  3. Copy the bot token – you’ll use it in your code.
  4. (Optional) Enable privacy mode to restrict commands to group chats only.

Tip: Keep the token in a .env file and load it with python-dotenv to avoid hard‑coding secrets.

# .env
TELEGRAM_TOKEN="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
Enter fullscreen mode Exit fullscreen mode

Example of loading the token:

import os
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv("TELEGRAM_TOKEN")
Enter fullscreen mode Exit fullscreen mode

3. Choose a Crypto Payment Gateway

Several providers support instant payment notifications (IPN), which your bot can listen to:

Provider Supported Coins Fees API Docs
CoinPayments 200+ 0.5‑1% https://www.coinpayments.net/_documentation
Coinbase Commerce 30+ 0.50% https://commerce.coinbase.com/docs
BitPay 25+ 1% https://bitpay.com/docs

For this tutorial we’ll use CoinPayments because it offers a simple PHP‑style IPN webhook that we’ll emulate with Python.

Requirements for CoinPayments

  • Create an account → Go to API → Create a new API key with “IPN” and “Allow withdrawals” disabled.
  • Set your IPN URL to the endpoint that will validate payments (we’ll build this with Flask, see later).
  • Save Public Key & Private Key – you’ll need them to sign requests and verify incoming IPNs.

4. Project Structure

crypto-telegram-bot/
├─ .env
├─ main.py              
├─ handlers.py
├─ payment.py
├─ utils.py
├─ requirements.txt
├─ Dockerfile      (optional)
Enter fullscreen mode Exit fullscreen mode
  • main.py starts the bot.
  • handlers.py contains command handlers.
  • payment.py talks to CoinPayments.
  • utils.py centralizes helpers (e.g., IPN signature verification).

5. The Bot Logic – Code Walkthrough

5.1. Setting Up the Async Bot

# main.py
from telegram.ext import ApplicationBuilder, CommandHandler
from handlers import start, deposit
from payment import create_payment_request

import logging
import os

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO,
)

TOKEN = os.getenv("TELEGRAM_TOKEN")

app = (
    ApplicationBuilder()
    .token(TOKEN)
    .read_timeout(10)
    .connect_timeout(10)
    .build()
)

# Commands
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("deposit", deposit))

# Optional: add a message handler for payment replies
# app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

app.run_polling()
Enter fullscreen mode Exit fullscreen mode

5.2. Handlers – start & deposit


python
# handlers.py
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes
from payment import create_payment_request
import datetime

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "Welcome! I can accept crypto payments. "
        "Send `/deposit` to see how to pay with Bitcoin or Ethereum."
    )

async def deposit(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user

    # Create a unique order ID per user
    order_id = f"{user.id}-{datetime.datetime.utcnow().timestamp()}"

    # Create a payment request via CoinPayments
    payload = await create_payment_request(
        amount=0.01,  # USD equivalent
        currency="BTC",
        item_name="Telegram Bot Service",
        ipn_url="https://yourdomain.com/ip

---

## Get the Production-Ready Version

Don't want to build it yourself? We have production-ready versions of these tools at [https://petroleum-board-hawaii-lol.trycloudflare.com](https://petroleum-board-hawaii-lol.trycloudflare.com).

**What you get:**
- Complete, tested Python code
- Documentation and setup guides
- Instant delivery after crypto payment
- Free updates

[Browse the collection →](https://petroleum-board-hawaii-lol.trycloudflare.com)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)