From b0738b27ec7810a7c108777cc65d1d2af608b232 Mon Sep 17 00:00:00 2001 From: inweems Date: Wed, 26 Apr 2023 22:00:09 +0300 Subject: [PATCH 01/19] botparsing --- Задания/task1/Prokhorova/botpars.py | 37 +++++++++++++++++++++++++++++ Задания/task1/Prokhorova/dz.py | 3 ++- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 Задания/task1/Prokhorova/botpars.py diff --git a/Задания/task1/Prokhorova/botpars.py b/Задания/task1/Prokhorova/botpars.py new file mode 100644 index 0000000..2063830 --- /dev/null +++ b/Задания/task1/Prokhorova/botpars.py @@ -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) \ No newline at end of file diff --git a/Задания/task1/Prokhorova/dz.py b/Задания/task1/Prokhorova/dz.py index 2dfcb87..1a47e12 100644 --- a/Задания/task1/Prokhorova/dz.py +++ b/Задания/task1/Prokhorova/dz.py @@ -1,8 +1,9 @@ -import psycopg2 + import psycopg2 import wget from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.service import Service + connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') cursor = connection.cursor() From e4f0ef9af29efd35925ee52078cb7a65a77b34f3 Mon Sep 17 00:00:00 2001 From: Harutyun Date: Wed, 26 Apr 2023 23:03:28 +0300 Subject: [PATCH 02/19] maybe last version --- Задания/task1/Garanyan/parser.py | 7 +++---- Задания/task1/Garanyan/problems.py | 10 ++++------ Задания/task1/Garanyan/tgbot.py | 27 ++++++++++++--------------- 3 files changed, 19 insertions(+), 25 deletions(-) diff --git a/Задания/task1/Garanyan/parser.py b/Задания/task1/Garanyan/parser.py index 8e6da15..e4432ec 100644 --- a/Задания/task1/Garanyan/parser.py +++ b/Задания/task1/Garanyan/parser.py @@ -14,15 +14,14 @@ Image = soup.find_all(attrs={"class": "holder-img"}) connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') cursor = connection.cursor() -create_q = '''CREATE TABLE Food - (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))''' +create_q = '''CREATE TABLE Food (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))''' cursor.execute(create_q) connection.commit() #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'] - tempf = f"C:\\Users\\Harutyun\\Desktop\\prog\\food{j}.jpg" + tempf = f"img\\food{j}.jpg" wget.download(url, tempf) insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{Name[j].text}', '{Price[j].text}', '{tempf}') ''' cursor.execute(insert_query) diff --git a/Задания/task1/Garanyan/problems.py b/Задания/task1/Garanyan/problems.py index 018fd04..9cfb872 100644 --- a/Задания/task1/Garanyan/problems.py +++ b/Задания/task1/Garanyan/problems.py @@ -3,21 +3,19 @@ import wget from Задания.task1.Garanyan import parser -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() -create_q = '''CREATE TABLE Food - (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))''' +create_q = '''CREATE TABLE Food (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))''' try: cursor.execute(create_q) connection.commit() except psycopg2.errors.DuplicateTable: - print("s") + print("duplicate error") for j in range(15): 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) try: insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{parser.Name[j].text}', '{parser.Price[j].text}', '{tempf}') ''' diff --git a/Задания/task1/Garanyan/tgbot.py b/Задания/task1/Garanyan/tgbot.py index 4bc1be5..f02959a 100644 --- a/Задания/task1/Garanyan/tgbot.py +++ b/Задания/task1/Garanyan/tgbot.py @@ -3,8 +3,7 @@ import psycopg2 from telebot import types import random -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() try: sel_query = """SELECT * FROM public.food""" @@ -16,32 +15,30 @@ except psycopg2.errors.UndefinedTable: cursor.execute(sel_query) array = list(cursor.fetchall()) - bot = telebot.TeleBot('841097550:AAFc5MoFRivTEfv-gOSJctqH53NfYMTKpCc') - @bot.message_handler(commands=["start"]) def start(m, res=False): markup = types.ReplyKeyboardMarkup(resize_keyboard=True) - item1 = types.KeyboardButton("Хот-доги и соусы!") - item2 = types.KeyboardButton("Случайная фотография нашего товара!") + item1 = types.KeyboardButton("Хот-доги и не только!") + item2 = types.KeyboardButton("Цена товара") markup.add(item1) markup.add(item2) bot.send_message(m.chat.id, - '"Хот-доги и соусы!" - для получения случайного товара из нашей хотдожной\n' - ' "Случайная фотография нашего товара!" - для вывода фотографий', - reply_markup=markup) + '"Хот-доги и не только!" - для получения случайного товара из нашей хотдожной\n' + ' "Цена товара" - для вывода цены', reply_markup=markup) +i = random.choice(array) @bot.message_handler(content_types=["text"]) def handle_text(message): - if (message.text.strip() == 'Хот-доги и соусы!'): + global i + if (message.text.strip() == 'Хот-доги и не только!'): 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_photo(message.chat.id, open(i[3], 'rb')) - elif (message.text.strip() == 'Случайная фотография нашего товара!'): - i = random.choice(array) - bot.send_photo(message.chat.id, open(i[3], 'rb')) - + elif (message.text.strip() == 'Цена товара'): + ans = f'Цена: {i[2]}\n' + bot.send_message(message.chat.id, ans) bot.polling(none_stop=True, interval=0) \ No newline at end of file From a65c741e40c20b6435fe0746b3c8ac648f82bc5a Mon Sep 17 00:00:00 2001 From: TatianaFilcheva <124861990+TatianaFilcheva@users.noreply.github.com> Date: Thu, 27 Apr 2023 21:52:20 +0300 Subject: [PATCH 03/19] Add files via upload --- Задания/task1/Filcheva/Subot.py | 70 +++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Задания/task1/Filcheva/Subot.py diff --git a/Задания/task1/Filcheva/Subot.py b/Задания/task1/Filcheva/Subot.py new file mode 100644 index 0000000..9149111 --- /dev/null +++ b/Задания/task1/Filcheva/Subot.py @@ -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) From ce4490974de95890dd078925c93fddff13ebc988 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 18:27:48 +0300 Subject: [PATCH 04/19] Add files via upload parsing DATABASE --- Задания/task1/Gasanova/parsing.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Задания/task1/Gasanova/parsing.py diff --git a/Задания/task1/Gasanova/parsing.py b/Задания/task1/Gasanova/parsing.py new file mode 100644 index 0000000..ffecd72 --- /dev/null +++ b/Задания/task1/Gasanova/parsing.py @@ -0,0 +1,30 @@ +# парсер к полусему 8 неделя +from bs4 import BeautifulSoup +from selenium import webdriver +from selenium.webdriver.chrome.service import Service +from wget import download +import psycopg2 as psyc + +# 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" +brow = webdriver.Chrome() +brow.get(URL) + +html = brow.page_source + +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"}) + +with psyc.connect(host = "localhost", dbname="work", user="dialuna", password = "Timka07") as conn: + with conn.cursor() as cursor: + for i, product in enumerate(penny[1:]): + image_link = product.find("img").attrs.get("src") + image_name = product.find("img").attrs.get("alt") + 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 bot(link, name, price, file) + values ('{image_link}', '{image_name}', '{price}', 'images/{i}.jpg')""") + + conn.commit() From 53ee82311c827e3d7aa6631dfe8fa4ff9db51219 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 18:28:09 +0300 Subject: [PATCH 05/19] Delete penny.py --- Задания/task1/Gasanova/penny.py | 29 ----------------------------- 1 file changed, 29 deletions(-) delete mode 100644 Задания/task1/Gasanova/penny.py diff --git a/Задания/task1/Gasanova/penny.py b/Задания/task1/Gasanova/penny.py deleted file mode 100644 index 686e539..0000000 --- a/Задания/task1/Gasanova/penny.py +++ /dev/null @@ -1,29 +0,0 @@ -# парсер к полусему 8 неделя -from bs4 import BeautifulSoup -from selenium import webdriver -from selenium.webdriver.chrome.service import Service -from wget import download -import psycopg2 as psyc - -# 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" -brow = webdriver.Chrome() -brow.get(URL) - -html = brow.page_source - -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"}) - -with psyc.connect(dbname="db_for_parse", user="dialuna") as conn: - with conn.cursor() as cursor: - for i, product in enumerate(penny[1:]): - image_link = product.find("img").attrs.get("src") - image_name = product.find("img").attrs.get("alt") - price = product.find("p", attrs={"class": "price"}).text.strip() - - cursor.execute(f"""insert into test(link, name, price, file) - values ('{image_link}', '{image_name}', '{price}', 'images/{i}.jpg')""") - - conn.commit() From d3f8c95fd87ea5f0e7676ed19fe8e5ad9e5f4fd3 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 18:31:31 +0300 Subject: [PATCH 06/19] Add files via upload Telegram Bot --- Задания/task1/Gasanova/bot_database.py | 62 ++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Задания/task1/Gasanova/bot_database.py diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py new file mode 100644 index 0000000..572268a --- /dev/null +++ b/Задания/task1/Gasanova/bot_database.py @@ -0,0 +1,62 @@ +import telebot +import psycopg2 +from telebot import types +import random + +connection = psycopg2.connect(host='localhost', dbname='work', user='dialuna', password='Timka07') +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())) + +#@bot.message_handler(content_types=['text']) +#def get_text_messages(message): + 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) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + elif (message.text.strip() == "Предложение дня"): + i = random.choice(array) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + elif (message.text.strip() == "Выбор редакции нашей компании"): + i = random.choice(array) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + else: + bot.send_message(message.chat.id, "Наш бот поможет подобрать вам или близким скейтборд мечты. Скорее пробуйте! ") + + +bot.polling(none_stop=True, interval=0) From 1f773148bd8c7665624f29f0675ff7b8952016cf Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 18:32:38 +0300 Subject: [PATCH 07/19] Update bot_database.py --- Задания/task1/Gasanova/bot_database.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py index 572268a..cb5b4aa 100644 --- a/Задания/task1/Gasanova/bot_database.py +++ b/Задания/task1/Gasanova/bot_database.py @@ -3,7 +3,7 @@ import psycopg2 from telebot import types import random -connection = psycopg2.connect(host='localhost', dbname='work', user='dialuna', password='Timka07') +connection = psycopg2.connect(host='localhost', dbname='work', user='dialuna', password='Timka07') # да-да :) cursor = connection.cursor() try: sel_query = """SELECT * FROM bot""" From acd613b2295282f599f10c32c5f4c2144b4b7984 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 18:33:12 +0300 Subject: [PATCH 08/19] Update bot_database.py --- Задания/task1/Gasanova/bot_database.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py index cb5b4aa..25fcaba 100644 --- a/Задания/task1/Gasanova/bot_database.py +++ b/Задания/task1/Gasanova/bot_database.py @@ -13,9 +13,8 @@ except psycopg2.errors.UndefinedTable: import problems sel_query = """SELECT * FROM bot""" cursor.execute(sel_query) - -array = list(cursor.fetchall()) +array = list(cursor.fetchall()) bot = telebot.TeleBot('secret') @@ -36,8 +35,7 @@ def start(message): 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() == "Лучший скейтборд этого сезона"): From e3a0c3429b2ec570256e37f4f132eae4211472f2 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 18:33:44 +0300 Subject: [PATCH 09/19] Update bot_database.py --- Задания/task1/Gasanova/bot_database.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py index 25fcaba..eca2f21 100644 --- a/Задания/task1/Gasanova/bot_database.py +++ b/Задания/task1/Gasanova/bot_database.py @@ -25,8 +25,6 @@ def start(message): bot.send_message(message.chat.id, "ЙОУ, {0.first_name}!\n Я твой помощник в мире скейтбординга😎".format(message.from_user, bot.get_me())) -#@bot.message_handler(content_types=['text']) -#def get_text_messages(message): markup = types.ReplyKeyboardMarkup(resize_keyboard=True) #создание кнопок btn1 = types.KeyboardButton("Лучший скейтборд этого сезона") btn2 = types.KeyboardButton("Предложение дня") From b07ba7438603a44b2b63acea7c710028a3b93078 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:07:01 +0300 Subject: [PATCH 10/19] Delete bot_database.py --- Задания/task1/Gasanova/bot_database.py | 58 -------------------------- 1 file changed, 58 deletions(-) delete mode 100644 Задания/task1/Gasanova/bot_database.py diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py deleted file mode 100644 index eca2f21..0000000 --- a/Задания/task1/Gasanova/bot_database.py +++ /dev/null @@ -1,58 +0,0 @@ -import telebot -import psycopg2 -from telebot import types -import random - -connection = psycopg2.connect(host='localhost', dbname='work', user='dialuna', password='Timka07') # да-да :) -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) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - bot.send_photo(message.chat.id, open(i[4], 'rb')) - elif (message.text.strip() == "Предложение дня"): - i = random.choice(array) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - bot.send_photo(message.chat.id, open(i[4], 'rb')) - elif (message.text.strip() == "Выбор редакции нашей компании"): - i = random.choice(array) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - bot.send_photo(message.chat.id, open(i[4], 'rb')) - else: - bot.send_message(message.chat.id, "Наш бот поможет подобрать вам или близким скейтборд мечты. Скорее пробуйте! ") - - -bot.polling(none_stop=True, interval=0) From dcc37d31827e058bc4d4a81131d0e649a78f02cb Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:07:36 +0300 Subject: [PATCH 11/19] DATABASE AND TELEGRAM BOT !!! DATABASE AND TELEGRAM BOT !!! --- Задания/task1/Gasanova/bot_database.py | 71 ++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Задания/task1/Gasanova/bot_database.py diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py new file mode 100644 index 0000000..632eae1 --- /dev/null +++ b/Задания/task1/Gasanova/bot_database.py @@ -0,0 +1,71 @@ +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())) + +#@bot.message_handler(content_types=['text']) +#def get_text_messages(message): + 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) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + 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) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + cat = open('kotik.webm', 'rb') + bot.send_sticker(message.chat.id, cat) + elif (message.text.strip() == "Выбор редакции нашей компании"): + i = random.choice(array) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + 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) From e36751190150f8e2bd3496cc56f2e2953e3eb9c4 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:08:29 +0300 Subject: [PATCH 12/19] Delete bot_database.py --- Задания/task1/Gasanova/bot_database.py | 71 -------------------------- 1 file changed, 71 deletions(-) delete mode 100644 Задания/task1/Gasanova/bot_database.py diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py deleted file mode 100644 index 632eae1..0000000 --- a/Задания/task1/Gasanova/bot_database.py +++ /dev/null @@ -1,71 +0,0 @@ -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())) - -#@bot.message_handler(content_types=['text']) -#def get_text_messages(message): - 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) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - 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) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - bot.send_photo(message.chat.id, open(i[4], 'rb')) - cat = open('kotik.webm', 'rb') - bot.send_sticker(message.chat.id, cat) - elif (message.text.strip() == "Выбор редакции нашей компании"): - i = random.choice(array) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - 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) From 0920877351a3fee1d74ce3307a1f0527ead94298 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:09:39 +0300 Subject: [PATCH 13/19] TELEGRAM_BOT/DATABASE !!! --- Задания/task1/Gasanova/bot_database.py | 67 ++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Задания/task1/Gasanova/bot_database.py diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py new file mode 100644 index 0000000..00e27dc --- /dev/null +++ b/Задания/task1/Gasanova/bot_database.py @@ -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) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + 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) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + cat = open('kotik.webm', 'rb') + bot.send_sticker(message.chat.id, cat) + elif (message.text.strip() == "Выбор редакции нашей компании"): + i = random.choice(array) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + 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) From 6aca2deea716597f25b62ee2ca223321693119ba Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:25:33 +0300 Subject: [PATCH 14/19] Update bot_database.py --- Задания/task1/Gasanova/bot_database.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py index 00e27dc..11dd716 100644 --- a/Задания/task1/Gasanova/bot_database.py +++ b/Задания/task1/Gasanova/bot_database.py @@ -51,7 +51,7 @@ def handle_text(message): bot.send_message(message.chat.id, ans) bot.send_photo(message.chat.id, open(i[4], 'rb')) cat = open('kotik.webm', 'rb') - bot.send_sticker(message.chat.id, cat) + bot.send_video(message.chat.id, cat) elif (message.text.strip() == "Выбор редакции нашей компании"): i = random.choice(array) ans = f'Название: {i[2]}\nЦена: {i[3]}\n' From 4db76bd795e1f3a38088d423d1e8bfbdd575c11c Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:25:57 +0300 Subject: [PATCH 15/19] Delete bot_database.py --- Задания/task1/Gasanova/bot_database.py | 67 -------------------------- 1 file changed, 67 deletions(-) delete mode 100644 Задания/task1/Gasanova/bot_database.py diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py deleted file mode 100644 index 11dd716..0000000 --- a/Задания/task1/Gasanova/bot_database.py +++ /dev/null @@ -1,67 +0,0 @@ -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) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - 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) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - 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) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) - 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) From 3abdc8993bd294060c2ee022bdf89e5399770e94 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:26:40 +0300 Subject: [PATCH 16/19] TELEGRAM_BOT / DATABASE !!! --- Задания/task1/Gasanova/bot_database.py | 67 ++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Задания/task1/Gasanova/bot_database.py diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py new file mode 100644 index 0000000..11dd716 --- /dev/null +++ b/Задания/task1/Gasanova/bot_database.py @@ -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) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + 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) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + 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) + ans = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, ans) + 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) From e5609ed074dd75bcf087d9fbb825539dc62e4e29 Mon Sep 17 00:00:00 2001 From: Lady Di <93448337+dialuna@users.noreply.github.com> Date: Sun, 30 Apr 2023 10:05:32 +0300 Subject: [PATCH 17/19] bot_database.py --- Задания/task1/Gasanova/bot_database.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py index 11dd716..1c3d867 100644 --- a/Задания/task1/Gasanova/bot_database.py +++ b/Задания/task1/Gasanova/bot_database.py @@ -40,22 +40,22 @@ def start(message): def handle_text(message): if (message.text.strip() == "Лучший скейтборд этого сезона"): i = random.choice(array) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) + 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) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) + 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) - ans = f'Название: {i[2]}\nЦена: {i[3]}\n' - bot.send_message(message.chat.id, ans) + 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) From c992f227492df872126ae5b376a9e611d4e40d9c Mon Sep 17 00:00:00 2001 From: Dronminator Date: Mon, 1 May 2023 20:06:30 +0300 Subject: [PATCH 18/19] =?UTF-8?q?=D0=A2=D0=B5=D0=BB=D0=B5=D0=B3=D1=80?= =?UTF-8?q?=D0=B0=D0=BC=20=D0=91=D0=BE=D1=82=20=D0=B8=20=D0=A4=D1=83=D0=BD?= =?UTF-8?q?=D0=BA=D1=86=D0=B8=D0=B8=20=D1=81=20=D0=BE=D1=88=D0=B8=D0=B1?= =?UTF-8?q?=D0=BA=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Задания/task1/Lahin/postgres.py | 17 +++++---- Задания/task1/Lahin/select_and_edit'.py | 27 ++++++++++++++ Задания/task1/Lahin/telegrambot.py | 47 +++++++++++++++++-------- 3 files changed, 69 insertions(+), 22 deletions(-) create mode 100644 Задания/task1/Lahin/select_and_edit'.py diff --git a/Задания/task1/Lahin/postgres.py b/Задания/task1/Lahin/postgres.py index fe8a029..c0620eb 100644 --- a/Задания/task1/Lahin/postgres.py +++ b/Задания/task1/Lahin/postgres.py @@ -49,12 +49,15 @@ for i in range(len(productst)): u.append(features[10*i+j].text) wget.download(url, filename) t = pricest[i].text.replace("\xa0", " ") - insert = f"""INSERT INTO public.laptops( - Product, Price, Diagonal, Resolution, CPU, RAM, Graphics_Controller, Volume, src) - VALUES - ('{productst[i].text.strip()}', '{t.strip()}', '{u[0][:u[0].find("/")]}', '{u[0][u[0].find("/")+1:]}', - '{u[2]}', '{u[4]+" "+u[5]}', '{u[6]}', '{u[8]}', '{filename}');""" - cursor.execute(insert) - connection.commit() + try: + insert = f"""INSERT INTO public.laptops( + Product, Price, Diagonal, Resolution, CPU, RAM, Graphics_Controller, Volume, src) + VALUES + ('{productst[i].text.strip()}', '{t.strip()}', '{u[0][:u[0].find("/")]}', '{u[0][u[0].find("/")+1:]}', + '{u[2]}', '{u[4]+" "+u[5]}', '{u[6]}', '{u[8]}', '{filename}');""" + cursor.execute(insert) + connection.commit() + except: + connection.rollback() cursor.close() connection.close() \ No newline at end of file diff --git a/Задания/task1/Lahin/select_and_edit'.py b/Задания/task1/Lahin/select_and_edit'.py new file mode 100644 index 0000000..298ef0b --- /dev/null +++ b/Задания/task1/Lahin/select_and_edit'.py @@ -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 \ No newline at end of file diff --git a/Задания/task1/Lahin/telegrambot.py b/Задания/task1/Lahin/telegrambot.py index 3031c38..57d6121 100644 --- a/Задания/task1/Lahin/telegrambot.py +++ b/Задания/task1/Lahin/telegrambot.py @@ -1,15 +1,23 @@ import telebot import psycopg2 import config -def execute_request(request): - connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user, password=config.password) - cursor = connection.cursor() - cursor.execute(request) - result = cursor.fetchall() - cursor.close() - connection.close() - return result -max_id = int(execute_request("select count(*) from laptops")[0][0]) +bot = telebot.TeleBot(config.bot_token) + +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: + result = "Ошибка" + finally: + cursor.close() + connection.close() + return result + +max_id = int(select("select max(id) from laptops")[0][0]) bot = telebot.TeleBot(config.bot_token) @bot.message_handler(commands=["start"]) def start(m, res=False): @@ -26,12 +34,21 @@ def from_bd(message): bot.send_message(message.chat.id, "ID больше, чем количество товаров. Попробуйте снова:") return else: - data = execute_request(f"select * from laptops where id = {current_id}")[0][1:-1] - names_of_columns = ["Товар", "Цена", "Диагональ", "Разрешение", "Процессор", "Оперативная память", "Графический контроллер", "Объём диска"] - everydata = [] - for data_name, column_name in zip(data, names_of_columns): - everydata.append(column_name.capitalize() + ": " + data_name) - bot.send_message(message.chat.id, "\n\n".join(everydata)) + try: + 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 = [] + for data_name, column_name in zip(s, names_of_columns): + everydata.append(column_name.capitalize() + ": " + data_name) + 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.polling(none_stop=True, interval=0) From 4dcd6465c984be5d31da8cd9b1dcdda447cccd64 Mon Sep 17 00:00:00 2001 From: bumajkaa <124861973+bumajkaa@users.noreply.github.com> Date: Mon, 1 May 2023 20:44:06 +0300 Subject: [PATCH 19/19] Add files via upload --- Задания/task1/Kuranova/bot_beer.py | 85 ++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Задания/task1/Kuranova/bot_beer.py diff --git a/Задания/task1/Kuranova/bot_beer.py b/Задания/task1/Kuranova/bot_beer.py new file mode 100644 index 0000000..844fd7e --- /dev/null +++ b/Задания/task1/Kuranova/bot_beer.py @@ -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) \ No newline at end of file