проблемы с работой aiogram
У меня есть функция
@dp.message_handler(commands="start")
async def start(message: types.Message):
cursor.execute(f"SELECT * FROM Users WHERE chatid = {message.chat.id}")
row = cursor.fetchone()
conn.commit()
if row == None:
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
buttons = [
types.InlineKeyboardButton(text="⏭Пропустить⏭", callback_data="notref")
]
keyboard.add(*buttons)
cursor.execute(f"INSERT INTO Users(chatid, ref) VALUES ({message.chat.id}, '0')")
conn.commit()
await bot.send_message(message.chat.id, f"?Добро Пожаловать {message.chat.first_name}?\nКто тебя пригласил:\n(Пример ввода: @andrey22)", reply_markup=keyboard)
@dp.message_handler(content_types=["text"])
async def ref(message: types.Message):
cursor.execute(f"UPDATE Users SET ref = '{message.text}' WHERE chatid = {message.chat.id}")
conn.commit()
await bot.send_photo(message.chat.id, photo=open(f'photo/1.gif', 'rb'), caption=f'<b>Введите ссылку:</b>', parse_mode='html', reply_markup=types.ReplyKeyboardRemove())
pass
Вторая функция
dp.message_handler(content_types=["text"])
async def ref(message: types.Message):
if code in message.text:
keyboard = types.InlineKeyboardMarkup()
buttons = [
types.InlineKeyboardButton(text=f"функ1 - {price[0]} руб", callback_data="f1"),
types.InlineKeyboardButton(text=f"функ2 - {price[1]} руб", callback_data="f2"),
types.InlineKeyboardButton(text=f"функ3 - {price[2]} руб", callback_data="f3"),
types.InlineKeyboardButton(text=f"функ4 - {price[3]} руб", callback_data="f4")
]
keyboard.add(*buttons)
await bot.send_photo(message.chat.id, photo=open(f'photo/func.gif', 'rb'), caption=f"Выберите действие:", reply_markup=keyboard)
pass
else:
await bot.send_message(message.chat.id, f"Ссылка неверного формата!")
pass
Я раньше писал на телеботе, и вот тут возникла проблема. Когда пользователь прожимает старт, и вводит реферала, срабатывает вторая функция а первая просто перестает работу. Как решить эту проблему? есть что то типо next step?
Ответы (1 шт):
Автор решения: oleksandrigo
→ Ссылка
Штош. Вот.
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import StatesGroup, State
import config
bot = Bot(token=config.BOT_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
class InputRef(StatesGroup):
input_ref = State()
@dp.message_handler(commands="start")
async def start(message: types.Message):
cursor.execute(f"SELECT * FROM Users WHERE chatid = {message.chat.id}")
row = cursor.fetchone()
conn.commit()
# слудет использовать is при сравнение с None, False, True
if row is None:
# Шо это за бред? Вы делаете ReplyKeyboardMarkup а внутрь пихаете инлайн кнопку
# markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
cursor.execute(f"INSERT INTO Users(chatid, ref) VALUES ({message.chat.id}, '0')")
conn.commit()
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
markup.add("⏭Пропустить⏭")
# нет смысла юзать bot.send_message если вы отправляете в этот же чат, юзайте answer()
await message.answer(
f"?Добро Пожаловать {message.chat.first_name}?\n"
f"Кто тебя пригласил:\n"
f"(Пример ввода: @andrey22)",
reply_markup=markup)
# запускаем стейт
await InputRef.input_ref.set()
# хендлер который ловит Пропуск ввода реферала
@dp.message_handler(state=InputRef.input_ref, text="⏭Пропустить⏭")
async def ref_skip(message: types.Message, state: FSMContext):
# закрываем стейт и все данные в нем
await state.finish()
# хендлер который ловит ввод реф пользователя
@dp.message_handler(state=InputRef.input_ref)
async def ref_input(message: types.Message):
cursor.execute(f"UPDATE Users SET ref = '{message.text}' WHERE chatid = {message.chat.id}")
conn.commit()
if not message.text.startswith("@"):
await message.answer("Вы ввели неверную ссылку на юзера.\nПопробуйте снова")
return
markup = types.InlineKeyboardMarkup()
markup.add(
types.InlineKeyboardButton(text=f"функ1 - {price[0]} руб", callback_data="f1"),
types.InlineKeyboardButton(text=f"функ2 - {price[1]} руб", callback_data="f2"),
types.InlineKeyboardButton(text=f"функ3 - {price[2]} руб", callback_data="f3"),
types.InlineKeyboardButton(text=f"функ4 - {price[3]} руб", callback_data="f4")
)
await message.answer_photo(
photo=open(f'photo/func.gif', 'rb'),
caption=f"Выберите действие:",
reply_markup=markup)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)