我想学习如何将我的电报机器人连接到数据库url,以便我存储机器人用户,加入日期和用户信息。帮助我完成这个教程。如何连接我的电报机器人到PostgreSQL/数据库的url。
#代码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'
要将Telegram bot连接到PostgreSQL数据库,可以使用psycopg2库。首先,您需要使用pip安装库:
pip install psycopg2
然后,您可以使用以下代码将bot连接到数据库:
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()
用你自己的PostgreSQL凭证替换DATABASE_URL。connect_to_db函数用于连接PostgreSQL数据库,insert_user_data函数用于向users表中插入用户数据。当用户向bot发送/start命令时,将调用handle_start函数,该函数提取用户的数据并使用insert_user_data函数将其存储在数据库中。希望这对你有帮助:)