· 5 years ago · Aug 15, 2020, 02:40 PM
1from sqlite3 import connect
2
3from aiogram.dispatcher import FSMContext
4from aiogram.dispatcher.filters import Command
5from aiogram import Bot, Dispatcher, types, executor
6from aiogram.utils.callback_data import CallbackData
7from aiogram.contrib.fsm_storage.memory import MemoryStorage
8from aiogram.dispatcher.filters.state import StatesGroup, State
9
10BOT_TOKEN = '<TOKEN>'
11
12bot = Bot(token=BOT_TOKEN)
13storage = MemoryStorage()
14dp = Dispatcher(bot, storage=storage)
15
16db = None
17
18action_callback = CallbackData('post', 'action', 'item_id')
19
20
21class Form(StatesGroup):
22 name = State()
23 photo = State()
24
25
26class DataBase:
27
28 def __init__(self):
29 self.create_connect()
30 self.cursor.execute(''' CREATE TABLE IF NOT EXISTS products (
31 id INTEGER PRIMARY KEY AUTOINCREMENT,
32 name TEXT,
33 rating INTEGER,
34 photo TEXT
35 )
36 ''')
37 self.break_connection()
38
39 def create_connect(self):
40 self.conn = connect('db.sqlite3', check_same_thread = False)
41 self.cursor = self.conn.cursor()
42
43 def break_connection(self):
44 self.cursor.close()
45 self.conn.close()
46
47 def write(self, name, photo):
48 self.create_connect()
49 self.cursor.execute(f''' INSERT INTO products (name, rating, photo)
50 VALUES ("{name}", 0, "{photo}") ''')
51 self.conn.commit()
52 self.break_connection()
53
54 def return_products(self):
55 self.create_connect()
56 self.cursor.execute(''' SELECT * FROM products ''')
57 products = self.cursor.fetchall()
58 self.break_connection()
59 return products
60
61 def get_product(self, id):
62 self.create_connect()
63 self.cursor.execute(f''' SELECT * FROM products WHERE id={id} ''')
64 product = self.cursor.fetchall()
65 self.break_connection()
66
67 try:
68 return product[0]
69
70 except IndexError:
71 return None
72
73 def update_rating(self, id, rating):
74 self.create_connect()
75 self.cursor.execute(
76 f''' UPDATE products SET rating="{rating}" WHERE id="{id}" '''
77 )
78 self.conn.commit()
79 self.break_connection()
80
81
82async def get_keyboard(id: int):
83 keyboard = types.InlineKeyboardMarkup(row_width=2,
84 inline_keyboard=[
85 [
86 types.InlineKeyboardButton(
87 text="Купить",
88 callback_data=action_callback.new(
89 action="buy",
90 item_id=id
91 )
92 )
93
94 ],
95
96 [
97 types.InlineKeyboardButton(
98 text="Лайк",
99 callback_data=action_callback.new(
100 action="like",
101 item_id=id
102 )
103 ),
104
105 types.InlineKeyboardButton(
106 text="Дизлайк",
107 callback_data=action_callback.new(
108 action="dislike",
109 item_id=id
110 )
111 )
112 ],
113
114 [
115 types.InlineKeyboardButton(
116 text="Поделиться с другом",
117 switch_inline_query=id
118 )
119 ]
120 ])
121 return keyboard
122
123
124@dp.message_handler(Command('item'))
125async def enter_form(message: types.Message):
126 for product in db.return_products():
127 try:
128 await message.answer_photo(
129 photo=product[3],
130 caption=f'{product[1]} RATING:{product[2]}',
131 reply_markup=await get_keyboard(product[0])
132 )
133
134 except Exception:
135 pass
136
137
138@dp.message_handler(Command('start'))
139async def enter_form(message: types.Message):
140 keyboard = types.InlineKeyboardMarkup(row_width=2)
141 keyboard.row(types.InlineKeyboardButton(text="/item", callback_data="start"))
142 await bot.send_message(message.chat.id, 'Hello', reply_markup=keyboard)
143
144
145#########################################
146#-------------- CALLBACK ---------------#
147#########################################
148@dp.callback_query_handler(action_callback.filter(action=["buy"]))
149async def buy_product(call: types.CallbackQuery, callback_data: dict):
150 await call.answer(cache_time=60)
151
152 await call.message.edit_caption(
153 f"Покупай товар номер {callback_data['item_id']}"
154 )
155
156
157@dp.callback_query_handler(action_callback.filter(action=["like"]))
158async def like_product(call: types.CallbackQuery, callback_data: dict):
159 product = db.get_product(callback_data['item_id'])
160 rating = product[2] + 1
161 db.update_rating(product[0], rating)
162
163 await call.message.edit_caption(
164 f'{product[1]} RATING:{rating}',
165 reply_markup=await get_keyboard(product[0])
166 )
167
168 await bot.answer_callback_query(call.id, text="Like")
169
170
171@dp.callback_query_handler(action_callback.filter(action=["dislike"]))
172async def like_product(call: types.CallbackQuery, callback_data: dict):
173 product = db.get_product(callback_data['item_id'])
174 rating = product[2] - 1
175 db.update_rating(product[0], rating)
176
177 await call.message.edit_caption(
178 f'{product[1]} RATING:{rating}',
179 reply_markup=await get_keyboard(product[0])
180 )
181
182 await bot.answer_callback_query(call.id, text="Dislike")
183
184
185@dp.callback_query_handler(text="start")
186async def buy_product(call: types.CallbackQuery):
187 await bot.send_message(call['from']['id'], call['message']['reply_markup']['inline_keyboard'][0][0]['text'])
188
189
190#######################################
191#---------------- FSM ----------------#
192#######################################
193@dp.message_handler(Command("form"), state=None)
194async def enter_form(message: types.Message):
195 await message.answer("Input product name")
196 await Form.name.set()
197
198
199@dp.message_handler(state=Form.name)
200async def take_photo(message: types.Message, state: FSMContext):
201 await state.update_data(name=message.text)
202
203 await message.answer("Link to product photo")
204
205 await Form.next()
206
207
208@dp.message_handler(state=Form.photo)
209async def write_result(message: types.Message, state: FSMContext):
210 await state.update_data(photo=message.text)
211
212 data = await state.get_data()
213
214 db.write(data['name'], data['photo'])
215
216 await message.answer('--FINISHED--')
217
218 await state.reset_state(with_data=True)
219
220
221async def on_start(dp):
222 global db
223 db = DataBase()
224
225
226if __name__ == '__main__':
227 executor.start_polling(dp, on_startup=on_start)
228
229