Телеграм Бот и Функции с ошибками

This commit is contained in:
Dronminator
2023-05-01 20:06:30 +03:00
parent 8d96d62299
commit c992f22749
3 changed files with 69 additions and 22 deletions
+3
View File
@@ -49,6 +49,7 @@ for i in range(len(productst)):
u.append(features[10*i+j].text) u.append(features[10*i+j].text)
wget.download(url, filename) wget.download(url, filename)
t = pricest[i].text.replace("\xa0", " ") t = pricest[i].text.replace("\xa0", " ")
try:
insert = f"""INSERT INTO public.laptops( insert = f"""INSERT INTO public.laptops(
Product, Price, Diagonal, Resolution, CPU, RAM, Graphics_Controller, Volume, src) Product, Price, Diagonal, Resolution, CPU, RAM, Graphics_Controller, Volume, src)
VALUES VALUES
@@ -56,5 +57,7 @@ for i in range(len(productst)):
'{u[2]}', '{u[4]+" "+u[5]}', '{u[6]}', '{u[8]}', '{filename}');""" '{u[2]}', '{u[4]+" "+u[5]}', '{u[6]}', '{u[8]}', '{filename}');"""
cursor.execute(insert) cursor.execute(insert)
connection.commit() connection.commit()
except:
connection.rollback()
cursor.close() cursor.close()
connection.close() connection.close()
@@ -0,0 +1,27 @@
import psycopg2
import config
def edit(request):
try:
connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user, password=config.password)
cursor = connection.cursor()
cursor.execute(request)
print("Done")
except Exception as error:
print(f"Что-то не так. Ошибка:{error}")
finally:
cursor.close()
connection.close()
def select(request):
try:
connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user,
password=config.password)
cursor = connection.cursor()
cursor.execute(request)
result = cursor.fetchall()
except Exception as error:
result = f"Ошибка: {error}"
finally:
cursor.close()
connection.close()
return result
+23 -6
View File
@@ -1,15 +1,23 @@
import telebot import telebot
import psycopg2 import psycopg2
import config import config
def execute_request(request): bot = telebot.TeleBot(config.bot_token)
connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user, password=config.password)
def select(request):
try:
connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user,
password=config.password)
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(request) cursor.execute(request)
result = cursor.fetchall() result = cursor.fetchall()
except:
result = "Ошибка"
finally:
cursor.close() cursor.close()
connection.close() connection.close()
return result return result
max_id = int(execute_request("select count(*) from laptops")[0][0])
max_id = int(select("select max(id) from laptops")[0][0])
bot = telebot.TeleBot(config.bot_token) bot = telebot.TeleBot(config.bot_token)
@bot.message_handler(commands=["start"]) @bot.message_handler(commands=["start"])
def start(m, res=False): def start(m, res=False):
@@ -26,12 +34,21 @@ def from_bd(message):
bot.send_message(message.chat.id, "ID больше, чем количество товаров. Попробуйте снова:") bot.send_message(message.chat.id, "ID больше, чем количество товаров. Попробуйте снова:")
return return
else: else:
data = execute_request(f"select * from laptops where id = {current_id}")[0][1:-1] try:
names_of_columns = ["Товар", "Цена", "Диагональ", "Разрешение", "Процессор", "Оперативная память", "Графический контроллер", "Объём диска"] data = select(f"select * from laptops where id = {current_id}")[0][1:]
if type(data) == str:
bot.send_message(message.chat.id, "Ошибка на сервере")
return
s = data[:-1]
names_of_columns = ["Товар", "Цена", "Диагональ", "Разрешение", "Процессор", "Оперативная память",
"Графический контроллер", "Объём диска"]
everydata = [] everydata = []
for data_name, column_name in zip(data, names_of_columns): for data_name, column_name in zip(s, names_of_columns):
everydata.append(column_name.capitalize() + ": " + data_name) everydata.append(column_name.capitalize() + ": " + data_name)
bot.send_message(message.chat.id, "\n\n".join(everydata)) bot.send_message(message.chat.id, "\n\n".join(everydata))
bot.send_photo(message.chat.id, open(data[-1], 'rb'))
except:
bot.send_message(message.chat.id, "Ошибка на сервере")
bot.send_message(message.chat.id, f"Введите следующий ID от 1 до {max_id}:") bot.send_message(message.chat.id, f"Введите следующий ID от 1 до {max_id}:")
bot.polling(none_stop=True, interval=0) bot.polling(none_stop=True, interval=0)