How do I connect my telegram bot (telebot) to PostgreSQL url

Question:

I would like to learn how to connect my telegram bot to database url so that I store bot users, date of join and user information. Help me through that tutorial. How to connect a my telegram bot to PostgreSQL/database url.

#code
from telebot import*

from telebot.types import*

from telebot.apihelper import ApiTelegramException

bot = telebot.TeleBot("590—-86:AAF9_DU9F_6—-rvls26HgJMzHyJJpY")

CHAT_ID = ‘@pristbank’ #replace your channel id

admin = ‘https://t.mepristlegacy’

Asked By: PRIST LEGACY

||

Answers:

To connect your Telegram bot to a PostgreSQL database, you can use the psycopg2 library. First, you need to install the library using pip:

pip install psycopg2

Then, you can use the following code to connect your bot to the database:

import psycopg2
from telebot import TeleBot
from telebot.types import Message
bot = TeleBot("590----86:AAF9_DU9F_6----rvls26HgJMzHyJJpY")
# Replace these with your own PostgreSQL credentials
DATABASE_URL = "postgres://user:password@host:port/dbname"
def connect_to_db():
    conn = psycopg2.connect(DATABASE_URL, sslmode='require')
    return conn
def insert_user_data(user_id, join_date, user_info):
    conn = connect_to_db()
    cursor = conn.cursor()
    query = "INSERT INTO users (user_id, join_date, user_info) VALUES (%s, %s, %s)"
    cursor.execute(query, (user_id, join_date, user_info))
    conn.commit()
    cursor.close()
    conn.close()
@bot.message_handler(commands=['start'])
def handle_start(message: Message):
    user_id = message.from_user.id
    join_date = message.date
    user_info = f"{message.from_user.first_name} {message.from_user.last_name}"
    insert_user_data(user_id, join_date, user_info)
    bot.reply_to(message, "User information has been stored in the database.")
bot.polling()

Replace DATABASE_URL with your own PostgreSQL credentials. The connect_to_db function is used to establish a connection to the PostgreSQL database, and insert_user_data function is used to insert user data into the users table.
When the user sends the /start command to your bot, the handle_start function is called, which extracts the user’s data and stores it in the database using the insert_user_data function. Hope this helps 🙂

Answered By: Leo