django test by perfecto

This commit is contained in:
pErfEcto2
2023-05-04 11:31:48 +03:00
12 changed files with 353 additions and 51 deletions
+70
View File
@@ -0,0 +1,70 @@
import telebot
import psycopg2
from telebot import types
# Создаем экземпляр бота
bot = telebot.TeleBot('5898574743:AAF2y_y3U2IfWwQVJ_lF6mmiDPlx1YgU9-Q')
# Функция, обрабатывающая команду /start
def reply_to_user(message, bot):
query = f"insert into Distilleries(name, place, contacts) values ('{message.text.strip()}', "
bot.send_message(message.chat.id, "Введите адрес винокурни")
bot.register_next_step_handler(message, f2, bot, query)
def f2(message, bot, query):
query += f"'{message.text.strip()}', "
bot.send_message(message.chat.id, "Введите контакты")
bot.register_next_step_handler(message, f3, bot, query)
def f3(message, bot, query):
query += f"'{message.text.strip()}')"
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4t5')
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
cursor.close()
connection.close()
bot.send_message(message.chat.id, "Done")
@bot.message_handler(commands=["start"])
def start_messanger(messanger):
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4t5')
cursor = connection.cursor()
cursor.execute("select id, name from Distilleries")
first_step = []
for id, name in cursor.fetchall():
f_s = str(id) + '. ' + name
first_step.append(f_s)
my_str = '\n'.join(first_step)
bot.send_message(messanger.chat.id, 'Я на связи. Выберите интересующую вас Винокурню, введите ее номер\n' + my_str.strip())
cursor.close()
connection.close()
@bot.message_handler(content_types=["text"])
def output(put):
n = put.text.strip()
if n.isalpha():
if n == 'Да':
bot.send_message(put.chat.id, 'Введите название винокурни')
bot.register_next_step_handler(put, reply_to_user, bot)
elif n == 'Нет':
bot.send_message(put.chat.id, 'Хорошего дня')
else:
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4t5')
cursor = connection.cursor()
cursor.execute(f"select place, contacts, imagelink from Distilleries where id = {n}")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton('Да')
item2 = types.KeyboardButton('Нет')
markup.add(item1)
markup.add(item2)
bot.send_message(put.chat.id, 'Хотите ли добавить еще одну винокурнею Крыма?', reply_markup=markup )
bot.polling(none_stop=True, interval=0)
+3 -4
View File
@@ -14,15 +14,14 @@ Image = soup.find_all(attrs={"class": "holder-img"})
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor() cursor = connection.cursor()
create_q = '''CREATE TABLE Food create_q = '''CREATE TABLE Food (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))'''
(ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))'''
cursor.execute(create_q) cursor.execute(create_q)
connection.commit() connection.commit()
#https://smartomato.ams3.cdn.digitaloceanspaces.com/uploads/media/photo/769221/dish_large__1.jpg #https://smartomato.ams3.cdn.digitaloceanspaces.com/uploads/media/photo/769221/dish_large__1.jpg
for j in range(15): for j in range(19):
url = Image[j].find('img').attrs['src'] url = Image[j].find('img').attrs['src']
tempf = f"C:\\Users\\Harutyun\\Desktop\\prog\\food{j}.jpg" tempf = f"img\\food{j}.jpg"
wget.download(url, tempf) wget.download(url, tempf)
insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{Name[j].text}', '{Price[j].text}', '{tempf}') ''' insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{Name[j].text}', '{Price[j].text}', '{tempf}') '''
cursor.execute(insert_query) cursor.execute(insert_query)
+4 -6
View File
@@ -3,21 +3,19 @@ import wget
from Задания.task1.Garanyan import parser from Задания.task1.Garanyan import parser
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
password='Q1w2e3r4')
cursor = connection.cursor() cursor = connection.cursor()
create_q = '''CREATE TABLE Food create_q = '''CREATE TABLE Food (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))'''
(ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))'''
try: try:
cursor.execute(create_q) cursor.execute(create_q)
connection.commit() connection.commit()
except psycopg2.errors.DuplicateTable: except psycopg2.errors.DuplicateTable:
print("s") print("duplicate error")
for j in range(15): for j in range(15):
url = parser.Image[j].find('img').attrs['src'] url = parser.Image[j].find('img').attrs['src']
tempf = f"C:\\Users\\Harutyun\\Desktop\\prog\\food{j}.jpg" tempf = f"img\\food{j}.jpg"
wget.download(url, tempf) wget.download(url, tempf)
try: try:
insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{parser.Name[j].text}', '{parser.Price[j].text}', '{tempf}') ''' insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{parser.Name[j].text}', '{parser.Price[j].text}', '{tempf}') '''
+12 -15
View File
@@ -3,8 +3,7 @@ import psycopg2
from telebot import types from telebot import types
import random import random
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
password='Q1w2e3r4')
cursor = connection.cursor() cursor = connection.cursor()
try: try:
sel_query = """SELECT * FROM public.food""" sel_query = """SELECT * FROM public.food"""
@@ -16,32 +15,30 @@ except psycopg2.errors.UndefinedTable:
cursor.execute(sel_query) cursor.execute(sel_query)
array = list(cursor.fetchall()) array = list(cursor.fetchall())
bot = telebot.TeleBot('841097550:AAFc5MoFRivTEfv-gOSJctqH53NfYMTKpCc') bot = telebot.TeleBot('841097550:AAFc5MoFRivTEfv-gOSJctqH53NfYMTKpCc')
@bot.message_handler(commands=["start"]) @bot.message_handler(commands=["start"])
def start(m, res=False): def start(m, res=False):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True) markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Хот-доги и соусы!") item1 = types.KeyboardButton("Хот-доги и не только!")
item2 = types.KeyboardButton("Случайная фотография нашего товара!") item2 = types.KeyboardButton("Цена товара")
markup.add(item1) markup.add(item1)
markup.add(item2) markup.add(item2)
bot.send_message(m.chat.id, bot.send_message(m.chat.id,
'"Хот-доги и соусы!" - для получения случайного товара из нашей хотдожной\n' '"Хот-доги и не только!" - для получения случайного товара из нашей хотдожной\n'
' "Случайная фотография нашего товара!" - для вывода фотографий', ' "Цена товара" - для вывода цены', reply_markup=markup)
reply_markup=markup)
i = random.choice(array)
@bot.message_handler(content_types=["text"]) @bot.message_handler(content_types=["text"])
def handle_text(message): def handle_text(message):
if (message.text.strip() == 'Хот-доги и соусы!'): global i
if (message.text.strip() == 'Хот-доги и не только!'):
i = random.choice(array) i = random.choice(array)
ans = f'Название: {i[1]}\nЦена: {i[2]}\n' ans = f'Название: {i[1]}\n'
bot.send_message(message.chat.id, ans) bot.send_message(message.chat.id, ans)
bot.send_photo(message.chat.id, open(i[3], 'rb')) bot.send_photo(message.chat.id, open(i[3], 'rb'))
elif (message.text.strip() == 'Случайная фотография нашего товара!'): elif (message.text.strip() == 'Цена товара'):
i = random.choice(array) ans = f'Цена: {i[2]}\n'
bot.send_photo(message.chat.id, open(i[3], 'rb')) bot.send_message(message.chat.id, ans)
bot.polling(none_stop=True, interval=0) bot.polling(none_stop=True, interval=0)
@@ -0,0 +1,67 @@
import telebot
import psycopg2
from telebot import types
import random
connection = psycopg2.connect(host='localhost', dbname='work', user='dialuna', password='Timka07') # да-да :D
cursor = connection.cursor()
try:
sel_query = """SELECT * FROM bot"""
cursor.execute(sel_query)
except psycopg2.errors.UndefinedTable:
connection.rollback()
import problems
sel_query = """SELECT * FROM bot"""
cursor.execute(sel_query)
array = list(cursor.fetchall())
bot = telebot.TeleBot('secret')
@bot.message_handler(commands=['start'])
def start(message):
sti = open('st.webp', 'rb')
bot.send_sticker(message.chat.id, sti)
bot.send_message(message.chat.id, "ЙОУ, {0.first_name}!\nЯ твой помощник в мире скейтбординга😎".format(message.from_user, bot.get_me()))
markup = types.ReplyKeyboardMarkup(resize_keyboard=True) #создание кнопок
btn1 = types.KeyboardButton("Лучший скейтборд этого сезона")
btn2 = types.KeyboardButton("Предложение дня")
btn3 = types.KeyboardButton("Выбор редакции нашей компании")
markup.add(btn1, btn2, btn3)
bot.send_message(message.chat.id,
'Лучший скейтборд этого сезона - это именно то, что тебе нужно, если хочешь быть самым крутым.\nПредложение дня - то, что актуально на сегодняшний день.\nВыбор редакции - просто доверься выбору наших сотрудников и тебе понравится :)\n',
reply_markup=markup)
@bot.message_handler(content_types=['text'])
def handle_text(message):
if (message.text.strip() == "Лучший скейтборд этого сезона"):
i = random.choice(array)
inf = f'Название: {i[2]}\nЦена: {i[3]}\n'
bot.send_message(message.chat.id, inf)
bot.send_photo(message.chat.id, open(i[4], 'rb'))
cat = open('kotik.webm', 'rb')
bot.send_video(message.chat.id, cat)
elif (message.text.strip() == "Предложение дня"):
i = random.choice(array)
inf = f'Название: {i[2]}\nЦена: {i[3]}\n'
bot.send_message(message.chat.id, inf)
bot.send_photo(message.chat.id, open(i[4], 'rb'))
cat = open('kotik.webm', 'rb')
bot.send_video(message.chat.id, cat)
elif (message.text.strip() == "Выбор редакции нашей компании"):
i = random.choice(array)
inf = f'Название: {i[2]}\nЦена: {i[3]}\n'
bot.send_message(message.chat.id, inf)
bot.send_photo(message.chat.id, open(i[4], 'rb'))
cat = open('kotik.webm', 'rb')
bot.send_video(message.chat.id, cat)
else:
bot.send_message(message.chat.id, "Наш бот поможет подобрать вам или близким скейтборд мечты. Скорее пробуйте! ")
bot.polling(none_stop=True, interval=0)
@@ -5,7 +5,7 @@ from selenium.webdriver.chrome.service import Service
from wget import download from wget import download
import psycopg2 as psyc import psycopg2 as psyc
# s = Service("chromedriver") на Ubuntu можно не указывать путь до драйвера :) # s = Service("chromedriver") на Ubuntu можно не указывать путь до драйвера если что :)
URL = "https://proskateshop.ru/skejtbordy/?utm_source=yandex&utm_medium=cpc&utm_campaign=cn%7Cskeyty_gz-1%7Ccid%7C51517250%7Csearch&utm_content=gid%7C4180310153%7Caid%7C8980588780%7C20506942844_20506942844%7Cmain&utm_term=%D0%9F%D0%B5%D0%BD%D0%BD%D0%B8%20%D0%B1%D0%BE%D1%80%D0%B4%20%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C&etext=2202.N39xvihj0F0Od_d4etv_6nh36sdlRP-T26wHLuCJfjo_JZtVI5O7HY5f8FOJnzuLZXB6eWZoZnp2dG1laHBlcA.aceac50a24e4832d82874cd59ca1f9a315d9b351&_openstat=ZGlyZWN0LnlhbmRleC5ydTs1MTUxNzI1MDs4OTgwNTg4NzgwO3lhbmRleC5ydTpndWFyYW50ZWU&yclid=1445113833197462400" URL = "https://proskateshop.ru/skejtbordy/?utm_source=yandex&utm_medium=cpc&utm_campaign=cn%7Cskeyty_gz-1%7Ccid%7C51517250%7Csearch&utm_content=gid%7C4180310153%7Caid%7C8980588780%7C20506942844_20506942844%7Cmain&utm_term=%D0%9F%D0%B5%D0%BD%D0%BD%D0%B8%20%D0%B1%D0%BE%D1%80%D0%B4%20%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C&etext=2202.N39xvihj0F0Od_d4etv_6nh36sdlRP-T26wHLuCJfjo_JZtVI5O7HY5f8FOJnzuLZXB6eWZoZnp2dG1laHBlcA.aceac50a24e4832d82874cd59ca1f9a315d9b351&_openstat=ZGlyZWN0LnlhbmRleC5ydTs1MTUxNzI1MDs4OTgwNTg4NzgwO3lhbmRleC5ydTpndWFyYW50ZWU&yclid=1445113833197462400"
brow = webdriver.Chrome() brow = webdriver.Chrome()
brow.get(URL) brow.get(URL)
@@ -16,14 +16,15 @@ soup = BeautifulSoup(html, "lxml")
penny = soup.find_all(attrs={"class": "product-layout product-grid col-lg-4 col-md-4 col-sm-6 col-xs-6"}) penny = soup.find_all(attrs={"class": "product-layout product-grid col-lg-4 col-md-4 col-sm-6 col-xs-6"})
with psyc.connect(dbname="db_for_parse", user="dialuna") as conn: with psyc.connect(host = "localhost", dbname="work", user="dialuna", password = "Timka07") as conn:
with conn.cursor() as cursor: with conn.cursor() as cursor:
for i, product in enumerate(penny[1:]): for i, product in enumerate(penny[1:]):
image_link = product.find("img").attrs.get("src") image_link = product.find("img").attrs.get("src")
image_name = product.find("img").attrs.get("alt") image_name = product.find("img").attrs.get("alt")
price = product.find("p", attrs={"class": "price"}).text.strip() price = product.find("p", attrs={"class": "price"}).text.strip()
download( product.find("img").attrs.get("src"), f"images/{i}.jpg")
cursor.execute(f"""insert into test(link, name, price, file) cursor.execute(f"""insert into bot(link, name, price, file)
values ('{image_link}', '{image_name}', '{price}', 'images/{i}.jpg')""") values ('{image_link}', '{image_name}', '{price}', 'images/{i}.jpg')""")
conn.commit() conn.commit()
+85
View File
@@ -0,0 +1,85 @@
import telebot
import random
from telebot import types
import psycopg2
bot = telebot.TeleBot('6279990552:AAHxC0hfpQcOrcGKHwvWT7AabQqdE3a5Tp8')
def request(a):
info = []
connection = psycopg2.connect(host='localhost', dbname='breweries', user='postgres', password='Q1w2e3r4t5')
cursor = connection.cursor()
cursor.execute(a)
res = cursor.fetchall()
for id, name, place, link in res:
s = [id, name, place, link]
info.append(s)
cursor.close()
connection.close()
return info
quote = ['В вине есть мудрость, в пиве есть свобода, в воде есть бактерии.\n\nБенджамин Франклин',
'Пиво — интеллектуальный напиток. Какая досада, что его пьет так много идиотов.\n\nРэй Брэдбери',
'Пьянство — особая форма самоубийства, позволяющая тебе оживать на следующий день. Я, кажется, уже прожил десять или '
'пятнадцать тысяч жизней.\n\nЧарльз Буковски',
'Я пью, чтобы окружающие меня люди становились интереснее.\n\nДжордж Жан Натан',
'— Уинстон, да вы пьяны!\n— Все верно. А вы уродина. Завтра утром я протрезвею. А вы так и останетесь уродиной.\n\nУинстон Черчилль',
'— Есть в мире вещи получше, чем алкоголь.\n— Да, сэр. Но алкоголь компенсирует их отсутствие.\n\nТерри Пратчетт',
'Если вы заметите человека, который пытается утопить свои горести в стакане, сообщите ему, что горести умеют плавать.\n\nПиттакус Лор',
'Алкоголь, возможно, опаснейший враг человека, но в Библии сказано: возлюби врага своего.\n\nФрэнк Синатра',
'Меня как-то спросили, мучит ли меня похмелье. Нет, ведь для того, чтобы случилось похмелье, нужно перестать пить.\n\nЛемми Килмистер',
'У меня нет проблем с алкоголем. За исключением тех случаев, когда я не могу достать выпивку.\n\nТом Уэйтс',
'Будь осторожен с крепкими напитками. Они могут заставить тебя выстрелить в сборщика налогов… и промахнуться.\n\nРоберт Хайнлайн',
'Плохого виски не бывает. Просто некоторые сорта виски лучше других.\n\nУильям Фолкнер',
'Не всякий, кто пьет, является поэтом. Многие пьют как раз из-за того, что они не поэты.\n\nДадли Мур',
'Компьютер позволяет совершить больше ошибок быстрее, чем какое-либо изобретение в человеческой истории, за исключением, '
'возможно, револьвера и текилы.\n\nМитч Рэдклифф',
'Я не доверяю верблюдам, и вообще всем, кто может неделю не пить.\n\nДжо Луис',
'Алкоголик — это тип, который тебе не нравится и который пьет столько же, сколько ты.\n\nДилан Томас',
'За алкоголь! Причину и решение всех проблем.\n\nГомер Симпсон']
c = request('select id, name, place, imagelink from Information')
def share(message):
a = message.text
b = a.split(',')
connection = psycopg2.connect(host='localhost', dbname='breweries', user='postgres', password='Q1w2e3r4t5')
cursor = connection.cursor()
p = """INSERT INTO Information(id,Name, Place, ImageLink) VALUES
( '"""+str(int(c[-1][0])+1)+"""', '"""+b[0]+"""', '"""+b[1]+"""', '"""+b[2]+"""');"""
cursor.execute(p)
connection.commit()
cursor.close()
connection.close()
bot.send_message(message.chat.id, 'Вы сделали неоценимую услугу! Спасибо вам большое!')
@bot.message_handler(commands=["start"])
def start(m, res=False):
markup=types.ReplyKeyboardMarkup(resize_keyboard=True)
item1=types.KeyboardButton("Где выпить?")
item2 = types.KeyboardButton("Знаешь еще места, где можно выпить? Поделись)")
item3 = types.KeyboardButton("Хочешь выпить, но нет повода или тоста? Не переживай, мы и такое предусмотрели;)")
markup.add(item1)
markup.add(item2)
markup.add(item3)
bot.send_message(m.chat.id, 'Если не хочешь заморачиваться, то просто нажми любую из предложенных кнопок\n'
f'А можешь ввести число от {c[0][0]} до {c[-1][0]}, мы тебе выведем номер самой '
f'лучшей пивоварни :)', reply_markup=markup)
@bot.message_handler(content_types=["text"])
def handle_text(message):
if message.text.strip() == 'Где выпить?':
choice = random.randint(1, len(c)-1)
bot.send_message(message.chat.id, f'{c[choice]}')
elif message.text.strip().isnumeric():
try:
bot.send_message(message.chat.id, f'{c[int(message.text) - 1]}')
except:
bot.send_message(message.chat.id, "Кажись, вы попали не в тот интервал. Попробуйте снова.")
elif message.text.strip() == 'Знаешь еще места, где можно выпить? Поделись)':
bot.send_message(message.chat.id, 'Пиши название, адрес, контакты через запятую!')
bot.register_next_step_handler(message, share)
elif message.text.strip() == 'Хочешь выпить, но нет повода или тоста? Не переживай, мы и такое предусмотрели;)':
bot.send_message(message.chat.id, 'Лови!')
choice1 = random.randint(1, len(quote)-1)
bot.send_message(message.chat.id, quote[choice1])
bot.polling(none_stop=True, interval=0)
+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)
@@ -0,0 +1,37 @@
import telebot
import psycopg2
from telebot import types
import random
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor()
BD = """SELECT * FROM public.food"""
cursor.execute(BD)
array = list(cursor.fetchall())
bot = telebot.TeleBot('5696445699:AAEPKQgUAs39DTLr_iyQvlaFAsJNFK8DMnc')
@bot.message_handler(commands=["start"])
def start(m, res=False):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Рандомный товар")
item2 = types.KeyboardButton("Повтор !")
markup.add(item1)
markup.add(item2)
bot.send_message(m.chat.id,
'"Рандомный товар" - для получения карточки товара\n "Повтори !" - для повторения сообщений.',
reply_markup=markup)
@bot.message_handler(content_types=["text"])
def handle_text(message):
if (message.text.strip() == 'Рандомный товар'):
i = random.choice(array)
ans = f'Название: {i[1]}\nЦена: {i[2]}\nГрамм: {i[3]}\nРэйтинг: {i[4]}\n'
bot.send_message(message.chat.id, ans)
elif (message.text.strip() == 'Повтори !'):
bot.send_message(message.chat.id, 'Ввод: ' + message.text)
bot.polling(none_stop=True, interval=0)
+2 -1
View File
@@ -1,8 +1,9 @@
import psycopg2 import psycopg2
import wget import wget
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from selenium import webdriver from selenium import webdriver
from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.service import Service
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor() cursor = connection.cursor()