Merge remote-tracking branch 'origin/master'

This commit is contained in:
Dronminator
2023-05-01 20:06:50 +03:00
21 changed files with 803 additions and 35 deletions
+1 -1
View File
@@ -4,7 +4,7 @@
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" /> <excludeFolder url="file://$MODULE_DIR$/venv" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="jdk" jdkName="Python 3.9 (venv)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
</module> </module>
+1 -1
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11" project-jdk-type="Python SDK" /> <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (venv)" project-jdk-type="Python SDK" />
</project> </project>
+71 -2
View File
@@ -4,7 +4,13 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="e5615680-c090-497d-a104-1337ed85f850" name="Changes" comment="Дз парсинг" /> <list default="true" id="e5615680-c090-497d-a104-1337ed85f850" name="Changes" comment="Дз парсинг">
<change afterPath="$PROJECT_DIR$/Задания/task1/Prokhorova/tgbot.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/22712.iml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/22712.iml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Задания/task1/Prokhorova/dz.py" beforeDir="false" afterPath="$PROJECT_DIR$/Задания/task1/Prokhorova/dz.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
@@ -33,12 +39,45 @@
<option name="hideEmptyMiddlePackages" value="true" /> <option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" /> <option name="showLibraryContents" value="true" />
</component> </component>
<<<<<<< HEAD
<component name="PropertiesComponent">{ <component name="PropertiesComponent">{
&quot;keyToString&quot;: { &quot;keyToString&quot;: {
&quot;last_opened_file_path&quot;: &quot;C:/Users/Honor/c22712&quot; &quot;last_opened_file_path&quot;: &quot;C:/Users/Honor/c22712&quot;
} }
}</component> }</component>
<component name="RunManager" selected="Python.zaparsil"> <component name="RunManager" selected="Python.zaparsil">
=======
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"last_opened_file_path": "C:/Users/Honor/Desktop/учеба/прога/c22712",
"settings.editor.selected.configurable": "com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable"
}
}]]></component>
<component name="RunManager" selected="Python.tgbot">
<configuration name="dz" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
<module name="22712" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="C:\Users\Honor\PycharmProjects\pythonProject\venv\Scripts\python.exe" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/Задания/task1/Prokhorova" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/Задания/task1/Prokhorova/dz.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
>>>>>>> d1c29f6 (телеграмм бот)
<configuration name="main" type="PythonConfigurationType" factoryName="Python" nameIsGenerated="true"> <configuration name="main" type="PythonConfigurationType" factoryName="Python" nameIsGenerated="true">
<module name="22712" /> <module name="22712" />
<option name="INTERPRETER_OPTIONS" value="" /> <option name="INTERPRETER_OPTIONS" value="" />
@@ -61,6 +100,27 @@
<option name="INPUT_FILE" value="" /> <option name="INPUT_FILE" value="" />
<method v="2" /> <method v="2" />
</configuration> </configuration>
<configuration name="tgbot" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
<module name="22712" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="C:\Users\Honor\PycharmProjects\pythonProject\venv\Scripts\python.exe" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/../тг бот" />
<option name="IS_MODULE_SDK" value="false" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/../тг бот/tgbot.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
<configuration name="zaparsil" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true"> <configuration name="zaparsil" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
<module name="22712" /> <module name="22712" />
<option name="INTERPRETER_OPTIONS" value="" /> <option name="INTERPRETER_OPTIONS" value="" />
@@ -84,6 +144,8 @@
</configuration> </configuration>
<recent_temporary> <recent_temporary>
<list> <list>
<item itemvalue="Python.tgbot" />
<item itemvalue="Python.dz" />
<item itemvalue="Python.zaparsil" /> <item itemvalue="Python.zaparsil" />
</list> </list>
</recent_temporary> </recent_temporary>
@@ -147,7 +209,14 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1680206771744</updated> <updated>1680206771744</updated>
</task> </task>
<option name="localTasksCounter" value="8" /> <task id="LOCAL-00008" summary="Дз парсинг">
<created>1680207517708</created>
<option name="number" value="00008" />
<option name="presentableId" value="LOCAL-00008" />
<option name="project" value="LOCAL" />
<updated>1680207517708</updated>
</task>
<option name="localTasksCounter" value="9" />
<servers /> <servers />
</component> </component>
<component name="TypeScriptGeneratedFilesManager"> <component name="TypeScriptGeneratedFilesManager">
@@ -0,0 +1,63 @@
#Небольшое предисловие: кнопки item1, item2 и item3 похожи по своему функционалу, однако между ними есть разница в реализации - item3 реализована через функцию, прописанную в доп.файле
import telebot
import psycopg2
from telebot import types
import random
from wwfuncs import select #импорт функции из другого файла
connection = psycopg2.connect(host='localhost', dbname='FHWDB', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor()
try:
s_query = """SELECT * FROM public.parse"""
cursor.execute(s_query)
except psycopg2.errors.UndefinedTable: #рассматриваем случай, когда таблицы нет
connection.rollback() #возвращаемся "на действие назад"
import FHWDB #создаём и заполняем таблицу, если её не существовало ранее
connection = psycopg2.connect(host='localhost', dbname='FHWDB', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor()
s_query = '''SELECT * FROM public.parse'''
cursor.execute(s_query)
finally:
arr = list(cursor.fetchall())
bot = telebot.TeleBot('5980905704:AAH2qIP4Gy60nhuKNAojOGpmI6zwNoJK1Iw')
@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("Хочу информацию о предложении дня, пожалуйста")
item4 = types.KeyboardButton("Общая информация о сведениях, находящихся в базе данных")
markup.add(item1)
markup.add(item2)
markup.add(item3)
markup.add(item4)
bot.send_message(m.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(arr)
a1 = f'Название: {i[1]};\nЦена: {i[2]};\nСкидка(в процентах): {i[3]};\n'
bot.send_message(message.chat.id, a1)
elif (message.text.strip() == "Хочу картинку любых цветов, пожалуйста"):
i = random.choice(arr)
bot.send_photo(message.chat.id, open(i[4], 'rb'))
elif (message.text.strip() == "Хочу информацию о предложении дня, пожалуйста"):
j = random.randint(1, 61)
i = list(select(j))
a1 = f'Название: {i[1]};\nЦена: {i[2]};\nСкидка(в процентах): {i[3]};\n'
bot.send_message(message.chat.id, "Предложение дня:\n")
bot.send_message(message.chat.id, a1)
bot.send_photo(message.chat.id, open(i[4], 'rb'))
else:
bot.send_message(message.chat.id, "С помощью данного бота вы можете получить информацию о 60-и цветах одного из московских магазинов по их продаже, в частности их: название, цену, скидку(в процентах) и фото. Вы можете это осуществить, взаимодействуя с ботом. Попробуйте! ")
bot.polling(none_stop=True, interval=0)
cursor.close()
connection.close()
+22
View File
@@ -0,0 +1,22 @@
import psycopg2
connection = psycopg2.connect(host='localhost', dbname='FHWDB', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor()
def edit(Col, N, NN, value):#Функция внесения изменений и сортировки
upd_query = f'''UPDATE Parse SET {Col} = '{NN}' WHERE {Col} = '{N}' '''
cursor.execute(upd_query)
ord_query = f'''SELECT * FROM public.parse order by {value};'''
cursor.execute(ord_query)
connection.commit()
edit('Name', 'Ирисы небесно-голубого цвета', 'Ирисы', 'ID')
#print(cursor.fetchall()) - для проверки
def select(ID):
s_query = f'''SELECT * FROM public.Parse where ID = {ID}'''
cursor.execute(s_query)
return cursor.fetchone()
#print(select(44)) - для проверки
+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)
+37
View File
@@ -0,0 +1,37 @@
import telebot
import psycopg2
from telebot import types
# Создаем экземпляр бота
bot = telebot.TeleBot('5898574743:AAF2y_y3U2IfWwQVJ_lF6mmiDPlx1YgU9-Q')
# Функция, обрабатывающая команду /start
@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()
m = int(n)
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 = {m}")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
bot.polling()
+121
View File
@@ -0,0 +1,121 @@
import telebot
import psycopg2
from telebot import types
# Создаем экземпляр бота
bot = telebot.TeleBot('5898574743:AAF2y_y3U2IfWwQVJ_lF6mmiDPlx1YgU9-Q')
# Функция, обрабатывающая команду /start
@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()
m = int(n)
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4t5')
cursor = connection.cursor()
if (m==1):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(1)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 2):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(2)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 3):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(3)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 4):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(4)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 5):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(5)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 6):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(6)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 7):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(7)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 8):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(8)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 9):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(9)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
if (m == 10):
cursor.execute("select place, contacts, imagelink from Distilleries where id in(10)")
for place, contacts, imagelink in cursor.fetchall():
answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink
bot.send_message(put.chat.id, answer)
cursor.close()
connection.close()
bot.polling()
@@ -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)
+28
View File
@@ -0,0 +1,28 @@
import psycopg2
import wget
from Задания.task1.Garanyan import parser
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))'''
try:
cursor.execute(create_q)
connection.commit()
except psycopg2.errors.DuplicateTable:
print("duplicate error")
for j in range(15):
url = parser.Image[j].find('img').attrs['src']
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}') '''
cursor.execute(insert_query)
connection.commit()
except:
connection.rollback()
cursor.close()
connection.close()
+44
View File
@@ -0,0 +1,44 @@
import telebot
import psycopg2
from telebot import types
import random
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor()
try:
sel_query = """SELECT * FROM public.food"""
cursor.execute(sel_query)
except psycopg2.errors.UndefinedTable:
connection.rollback()
import problems
sel_query = """SELECT * FROM public.food"""
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("Цена товара")
markup.add(item1)
markup.add(item2)
bot.send_message(m.chat.id,
'"Хот-доги и не только!" - для получения случайного товара из нашей хотдожной\n'
' "Цена товара" - для вывода цены', reply_markup=markup)
i = random.choice(array)
@bot.message_handler(content_types=["text"])
def handle_text(message):
global i
if (message.text.strip() == 'Хот-доги и не только!'):
i = random.choice(array)
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() == 'Цена товара'):
ans = f'Цена: {i[2]}\n'
bot.send_message(message.chat.id, ans)
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()
@@ -0,0 +1,37 @@
import telebot
import psycopg2
def execute_request(request):
connection = psycopg2.connect(host='localhost', dbname='dbdata',
user='postgres', password='Q1w2e3r4')
cursor = connection.cursor()
cursor.execute(request)
result = cursor.fetchall()
cursor.close()
connection.close()
return result
min_id = int(execute_request("select min(id) from parsing")[0][0])
max_id = int(execute_request("select max(id) from parsing")[0][0])
bot = telebot.TeleBot('6060681334:AAHASvjmAEn_DF_NjymP1MMpq14kYx_2cZw')
@bot.message_handler(commands=["start"])
def start(m, res=False):
bot.send_message(m.chat.id, f'Привет. Введите идентификатор от {min_id} до {max_id}, чтобы получить данные: ')
@bot.message_handler(content_types=["text"])
def from_bd(message):
try:
current_id = int(message.text)
except BaseException:
bot.send_message(message.chat.id, "Вы неправильно ввели ID. Попробуйте снова:")
return
if current_id > max_id or current_id < min_id:
bot.send_message(message.chat.id, "ID больше, чем количество товаров. Попробуйте снова:")
return
else:
data = execute_request(f"select * from parsing where id = {current_id}")[0][1:]
names_of_columns = ["name", "link"]
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))
bot.send_message(message.chat.id, f"Введите следующий ID от {min_id} до {max_id}:")
bot.polling(none_stop=True, interval=0)
#for commit
@@ -0,0 +1,54 @@
from bs4 import BeautifulSoup
from selenium.webdriver import Chrome
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
import wget
import psycopg2
import re
s = Service('C:\Users\Alex\PycharmProjects\pythonProject\chromedriver.exe')
browser = webdriver.Chrome(service=s)
browser.get('https://music.yandex.ru/chart')
time.sleep (1)
html_text = browser.page_source
soup = BeautifulSoup(html_text, 'lxml')
Трек=soup.find_all('a', class_='d-track__title deco-link deco-link_stronger')
Длительность=soup.find_all('div', class_='d-track__info d-track__nohover')
Автор=soup.find_all('span', class_='d-track__artists')
Картинки=soup.find_all('img', class_='entity-cover__image deco-pane')
str_Картинки=[]
for i in range(len(Картинки)):
str_Картинки.append(Картинки[i])
str_Картинки=str(str_Картинки)
str_Картинки=re.findall(r'src="(.*?)"',str_Картинки)
for i in range(len(str_Картинки)):
str_Картинки[i]='https:'+str_Картинки[i]
#for i in range(len(str_cartinki)):
#wget.download(str_cartinki[i], 'TOP'+str((i+1))+'.jpeg')
connection = psycopg2.connect(dbname = 'dbdata',
user='postgres', password='Q1w2e3r4',
host='localhost')
cursor=connection.cursor()
creat_table="""CREATE TABLE music
(id serial primary key, "Трек" varchar(100),
"Длительность" varchar(100),
"Автор" varchar(100),
"Картинки" varchar(100))"""
cursor.execute(creat_table)
connection.commit()
for Трек, Длительность, Автор, Картинки in zip(Трек, Автор, Длительность, Картинки):
qwery=f"""INSERT INTO public.music(
Трек, Длительность, Автор, Картинки)
VALUES
('{Трек.text}','{Длительность.text}','{Автор.text}', '{Картинки.text}' )"""
cursor.execute(qwery)
connection.commit()
for i in range(1,len(str_Картинки)+1):
puti = r'C:\papkta' + str(i) + '.jpeg'
qwery=f"""UPDATE public.music
SET Картинки='{puti}'
WHERE id={i}"""
cursor.execute(qwery)
connection.commit()
@@ -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)
+11 -2
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()
@@ -19,12 +20,20 @@ browser.get('https://www.ozon.ru/category/platya-zhenskie-7502/')
html_code = browser.page_source html_code = browser.page_source
soup = BeautifulSoup(html_code, 'lxml') soup = BeautifulSoup(html_code, 'lxml')
name = soup.find_all('span', class_="m2e e3m m3e m5e tsBodyL k7l l7k") names = []
sale = soup.find_all('div', class_="eg1 g3e") sale = soup.find_all('div', class_="eg1 g3e")
price = soup.find_all('span', class_="a2a-a2") price = soup.find_all('span', class_="a2a-a2")
info = soup.find_all('span', class_="je4") info = soup.find_all('span', class_="je4")
picture = soup.find_all('div', class_="k1m") picture = soup.find_all('div', class_="k1m")
products = soup.find_all("div", class_="k7o o7k")
for product in products:
names.append(soup.find('span', class_="m2e e3m m3e m5e tsBodyL k7l l7k").text.strip())
print(names)
exit(0)
for i in range(20): for i in range(20):
url = picture[i].find('img').attrs['src'] url = picture[i].find('img').attrs['src']
file_name = f"C:\\Users\\Honor\\Desktop\\учеба\\прога\\pictures\\{i}.jpg" file_name = f"C:\\Users\\Honor\\Desktop\\учеба\\прога\\pictures\\{i}.jpg"
+37
View File
@@ -0,0 +1,37 @@
import telebot
import random
from telebot import types
f = open('C:\\Users\\Honor\\Desktop\\учеба\\прога\\тг_бот\\бот\\факт.txt', 'r', encoding='UTF-8')
facts = f.read().split('\n')
f.close()
f = open('C:\\Users\\Honor\\Desktop\\учеба\\прога\\тг_бот\\бот\\поговорка.txt', 'r', encoding='UTF-8')
thinks = f.read().split('\n')
f.close()
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Факт'
' для получения интересного факта\nПоговорка '
'— для получения мудрой цитаты ', reply_markup=markup)
@bot.message_handler(content_types=["text"])
def handle_text(message):
if message.text.strip() == 'Факт' :
answer = random.choice(facts)
elif message.text.strip() == 'Поговорка':
answer = random.choice(thinks)
bot.send_message(message.chat.id, answer)
bot.polling(none_stop=True, interval=0)
+22 -22
View File
@@ -1,39 +1,39 @@
import telebot import telebot
import random import psycopg2
import config
from telebot import types from telebot import types
import random
f = open('C:\\Users\\71332\\Desktop\\p\\факт.txt', 'r', encoding='UTF-8') connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
facts = f.read().split('\n')
f.close()
f = open('C:\\Users\\71332\\Desktop\\p\\поговорка.txt', 'r', encoding='UTF-8') cursor = connection.cursor()
thinks = f.read().split('\n')
f.close()
sel_query = """SELECT * FROM public.parser"""
cursor.execute(sel_query)
array = list(cursor.fetchall())
bot = telebot.TeleBot('6293063008:AAEFscB5LEjxC_4irrcgT-z6Eb0NXYOxZng') bot = telebot.TeleBot('6293063008:AAEFscB5LEjxC_4irrcgT-z6Eb0NXYOxZng')
@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, 'Нажми: \nФакт' bot.send_message(m.chat.id,
' для получения интересного факта\nПоговорка ' '"Рандомный продукт" - для получения карточки товара\n "Повтори!" - для повторения сообщений.',
'— для получения мудрой цитаты ', reply_markup=markup) reply_markup=markup)
@bot.message_handler(content_types=["text"]) @bot.message_handler(content_types=["text"])
def handle_text(message): def handle_text(message):
if message.text.strip() == 'Факт': if (message.text.strip() == 'Рандомный продукт'):
answer = random.choice(facts) i = random.choice(array)
elif message.text.strip() == 'Поговорка': ans = f'Название: {i[1]}\nЦена: {i[2]}\nРейтинг: {i[3]}\n'
answer = random.choice(thinks) bot.send_message(message.chat.id, ans)
bot.send_message(message.chat.id, answer) bot.send_photo(message.chat.id, open(i[4], 'rb'))
elif (message.text.strip() == 'Повтори!'):
bot.send_message(message.chat.id, 'Ввод: ' + message.text)
bot.polling(none_stop=True, interval=0)
bot.infinity_polling(none_stop=True, interval=0)
+36
View File
@@ -0,0 +1,36 @@
import telebot
import psycopg2
import config
from telebot import types
import random
import tableCreator
connection = psycopg2.connect(host='localhost', dbname='parc', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor()
ins_query = """SELECT * FROM public.Notebooks"""
cursor.execute(ins_query)
array = list(cursor.fetchall())
bot = telebot.TeleBot('6205726630:AAF4zfV_P2b0f7bClm__sWuRmoZ1XpiC_xo')
@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Выбери ноутбук'
' для просмотра товара\nЕще! '
'— для повтора', reply_markup=markup)
@bot.message_handler(content_types=["text"])
def handle_text(message):
if message.text.strip() == 'Выбери ноутбук' :
q = random.choice(array)
answer = f'Название: {q[1]}\nОписание: {q[2]}\nКод: {q[3]}\nЦена: {q[4]}\n'
bot.send_message(message.chat.id, answer)
bot.send_picture(message.chat.id, open(q[5], 'rb'))
elif message.text.strip() == 'Еще!':
bot.send_message(message.chat.id, 'Ввод: '+ message.text)
bot.polling(none_stop=True, interval=0)
+37
View File
@@ -0,0 +1,37 @@
from time import time, sleep
from random import random
class Car:
def __init__(self, model: str = "Aston Martin",
color: str = "Black",
volume: int = 30,
consp: int = 1):
self.model = model
self.color = color
self.all_volume = volume
self.volume = volume
self.consumption = consp
def start(self) -> int:
self.start_time = int(time())
return self.volume // self.consumption
def stop(self) -> int:
self.volume -= self.consumption * (int(time()) - self.start_time)
return self.volume
def show_info(self) -> None:
print(
f"model: {self.model}; color: {self.color}; all volume: {self.all_volume}; volume left: {self.volume}")
car = Car(volume=10)
time_sleep = int(car.start() * random())
print(f"time for working: {time_sleep} seconds")
sleep(time_sleep)
car.stop()
car.show_info()