Answer the question
In order to leave comments, you need to log in
How to set Individual variables for each user in a bot?
These variables
are type.key = random.choice(list(type.words.keys()))
type.length = "-"*len(type.key)
type.wrong = 0
type.used = []
Whole code
logging.basicConfig(level = logging.INFO)
storeg = MemoryStorage()
bot = Bot(token=config.TOKEN, parse_mode="HTML")
dp = Dispatcher(bot, storage=storeg)
class Test(StatesGroup):
Q1 = State()
@dp.message_handler(commands=['start'],state=None)
async def start_game(message: types.Message):
type.key = random.choice(list(type.words.keys()))
type.length = "-"*len(type.key)
type.wrong = 0
type.used = []
await bot.send_message(message.from_user.id,
fmt.text(
fmt.text('ДОБРО ПОЖАЛОВАТЬ В ИГРУ ВИСЕЛЬНИЦА!!!'),
fmt.text('======================='),
fmt.text('Вы использовали эти буквы:', *type.used),
fmt.text("Ошибок:", fmt.hbold(type.wrong)),
fmt.text('======================='),
fmt.text('Загадака звучит так:', type.words[type.key]),
sep="\n"
), parse_mode="HTML")
await bot.send_message(message.from_user.id, fmt.text('Слово:', type.length))
await bot.send_message(message.from_user.id, 'Напишите "Отмена", если перехотели играть')
await bot.send_message(message.from_user.id, 'Введите букву или слово')
type.input_let_id.clear()
type.bot_id.clear()
await Test.Q1.set()
@dp.message_handler(state=Test.Q1)
async def game(message: types.Message, state: FSMContext):
try:
answer = message.text.upper()
await state.update_data(Q1 = answer)
if answer == type.key:
type.length = type.key
if answer in type.key:
new = ""
type.used.append(answer)
for i in range(len(type.key)):
if answer == type.key[i]:
new += answer
else:
new += type.length[i]
type.length = new
if type.length == type.key:
await bot.send_message(message.from_user.id, fmt.text("Вы победили!!! Загаданное слово было:", type.key))
await state.finish()
for i in type.bot_id:
await bot.delete_message(message.chat.id, i)
for i in type.input_let_id:
await bot.delete_message(message.chat.id, i)
elif answer != 'ОТМЕНА':
type.used.append(answer)
type.wrong += 1
await bot.send_message(message.from_user.id, HANGMAN[type.wrong])
if type.wrong == len(HANGMAN) - 1:
await bot.send_message(message.from_user.id, fmt.text('Вас повесили :('))
await bot.send_message(message.from_user.id, fmt.text('загаданное слово было:', type.key))
await state.finish()
for i in type.bot_id:
await bot.delete_message(message.chat.id, i)
for i in type.input_let_id:
await bot.delete_message(message.chat.id, i)
elif type.wrong != len(HANGMAN) - 1 and type.length != type.key and answer != 'ОТМЕНА':
msg = await bot.send_message(message.from_user.id,
fmt.text(
fmt.text('Вы использовали эти буквы:', *type.used),
fmt.text("Ошибок:", fmt.hbold(type.wrong)),
fmt.text('======================='),
fmt.text('Загадака звучит так:', type.words[type.key]),
fmt.text('======================='),
fmt.text('Слово:', type.length),
sep="\n"
), parse_mode="HTML")
input_let = await message.answer('Введите букву')
type.bot_id.append(msg.message_id)
type.bot_id.append(input_let.message_id)
elif answer == 'ОТМЕНА':
await bot.send_message(message.from_user.id,'Досвидание!')
await state.finish()
except:
asyncio.sleep(0.1)
@dp.message_handler()
async def set_default_commands(dp):
await dp.bot.set_my_commands([
types.BotCommand("start", "Начать игру"),
])
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
import random
words = {"УРОКИ":"Что можно приготовить, но нельзя съесть?",
"ШАХМАТИСТ":"Кто ходит сидя?",
"ДВЕРЬ":"Кто приходит, кто уходит, все ее за ручку водят.",
"ДОРОГА":"Если б встала, до неба достала б.",
"ДЕНЬ":"К вечеру умирает, по утру оживает.",
"РАДИО":"В Москве говорят, а у нас слышно.",
"ВРЕМЯ":"Без ног и без крыльев оно, быстро летит, не догонишь его.",
"ТУАЛЕТНАЯ":"Самая популярная бумага",
"СЕКРЕТОМ":"Чем можно поделиться только один раз?"}
key = random.choice(list(words.keys()))
length = "-"*len(key)
wrong = 0
used = []
bot_id = []
input_let_id = []
Answer the question
In order to leave comments, you need to log in
You open a db and there you create. The simplest is sqlite3. I'm embarrassed to say, but at first I just used .txt files. If you do not know how to work with the database, You can try my method too! Here is the template
with open(f'DataBase\\{message.from_user.id}') as f:
f.write('some_text')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question