How to Build a Referral Bot on Telegram with Python

How to Build a Referral Bot on Telegram with Python

Boost Your Referral System: Rewards and Database Integration

Importance of Telegram Referral Bot

Many people are using Telegram bots for personal branding, business and team management. In every cases, referral system plays one of the most crucial roles to increase your network. You should allow this hectic and repetitive tasks such as referral management to be a time waster for you. Let your Telegram bot handle this task.

Python is becoming one of the most useful languages in case of any automated systems like chatbots nowadays. Building a referral Telegram bot using python is as easy as making a tea now with lucid libraries and robust API by Telegram all just at a cost of zero.

As we dedicate to make this easy for every telegram user, whether a good developer or not, we make this tutorial super easy along with easiest programming language and simple libraries.

Step by Step Guide to Create and Deploy Your Referral Bot

Here we will use a Telegram API provided. Before starting this tutorial, we assume that you already have Python 3.10+ installed, any code editor (VS Code recommended) and the API key provided by @BotFather.

Step 1 : Install Required Libraries

We will use pyTelegramBotAPI and sqlite3 as the main libraries here. Go to the terminal and write the following commands.

pip install pyTelegramBotAPI --upgrade
pip install db-sqlite3 --upgrade

Step 2 : Write and Run Code

Open the code editor and create a bot.py file inside it. Open the file and run the following code.

from telebot import TeleBot
from telebot.types import *
import sqlite3

conn = sqlite3.connect('users.db', check_same_thread=False, timeout=20)
#In this case, we assume that for every referral you award the user with 1 coin when the referred user commands /start in your bot. Customise it according to your needs
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS users (
user_id INTEGER,
referrer_id INTEGER,
coin INTEGER
)""")
#In this case, we assume that the API key is 183627nsufjc79uf7. Replace it with your API
bot = TeleBot("183627nsufjc79uf7")

@bot.message_handler(['start'])
def start_bot(message):
    if message.chat.type != "private":
        return
    user_id = int(message.chat.id)
    markup = InlineKeyboardMarkup()
    b1 = InlineKeyboardButton("Refer", callback_data="refer")
    b2 = InlineKeyboardButton("Balance", callback_data="balance")
    markup.add(b1, b2)
    c = conn.cursor()
    c.execute("SELECT user_id FROM users WHERE user_id = ?", (user_id))
    result = c.fetchone()
    if result is None:    
        if len(message.text.split(' ')) > 1:
            referrer_id = message.text.split(' ')[1]
            c = conn.cursor()
            c.execute("INSERT INTO users (user_id, coin) VALUES (?, ?)", (user_id, 0))
            conn.commit()
            if referrer_id.isDigit():
                c = conn.cursor()
                c.execute("UPDATE users SET referrer_id = ? WHERE user_id = ?", (referrer_id, user_id))
                conn.commit()
                bot.send_message(chat_id=int(referrer_id), text=f"@{message.chat.username} has successfully started me with your referral ID. You have won 1 coin.")
            else:
                print('Referrer not found')
        bot.send_message(message.chat.id, """Welcome to referral bot. Here you can refer to earn exciting rewards.
Just share your referal links to any user. If he/she starts the bot your referral link, you will earn 1 coin.
Remember, the user must not be already a subscriber of the bot, or else you will miss the reward.""", reply_markup=markup)
    else:
        bot.send_message(message.chat.id, "Welcome back. Hope you are enjoying my services. Please tell how can I help you?", reply_markup=markup)
@bot.callback_query_handler(func=lambda call: True)
def call_back_query(call):
    user_id = call.chat.id
    if call.data == "refer":
        bot.delete_message(call.chat.id, call.message.id)
        bot.send_message(call.chat.id, f"Your referral link is https://t.me/{bot.get_me().username}?start={user_id}.")
    elif call.data == "balance":
        c = conn.cursor()
        c.execute("SELECT coin FROM users WHERE user_id = ?", (user_id))
        result = c.fetchone()[0]
        bot.delete_message(call.chat.id, call.message.id)
        bot.send_message(call.chat.id, f"You have {result[0]} coins left.")
#Start the bot
bot.infinity_polling(skip_pending=True)

For more convenience, you can prefer reading the official documentation of pyTelegramBotAPI and sqlite3.

Step 3 : Deploy the Bot

Finally deploy the bot in any cloud platform so that your bot never stops running even if you close your code editor. Heroku and Pythonanywhere are the best choice. However, if you have budget constraint, Pythonanywhere will give you a free tier to use.

This is a very basic yet a powerful bot to handle the most crucial part of your referral system. If you want to make any Telegram Bot with advanced features and customized admin control within your affordable budget, contact Subham Saha in Telegram, Fiverr or Email.