import asyncio
import os
from aiogram import Bot, Dispatcher
from aiogram.types import Message
from aiogram.utils import executor
bot = Bot(token=os.environ['token'])
dp = Dispatcher(bot)
async def long_task():
for i in range(10):
print(i)
await asyncio.sleep(1)
@dp.message_handler(commands=['start'])
async def dp_start(message: Message):
await message.answer('Test')
@dp.message_handler(commands=['long_task'])
async def run_long_task(message: Message):
print('Старт')
await long_task() # Функция, которая долго исполняется
print('Финиш')
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
import asyncio
import os
import schedule
from aiogram import Bot, Dispatcher
from aiogram.types import Message
from aiogram.utils import executor
bot = Bot(token=os.environ['token'])
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def dp_start(message: Message):
await message.answer('Test')
async def run_schedule():
while True:
schedule.run_pending()
await asyncio.sleep(1) # Раз в секунду проверяем, не настал ли момент выполнять задание
async def long_task():
print('Старт')
await asyncio.sleep(10) # Функция, которая долго исполняется
print('Финиш')
def do_task():
asyncio.ensure_future(long_task())
if __name__ == '__main__':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(run_schedule()) # Добавляем планировщик в петлю
# schedule.every(15).seconds.do(do_task) # Тестовый вариант каждые 15 секунд
schedule.every(5).minutes.do(do_task)
executor.start_polling(dp, loop=loop, skip_updates=True) # Добавляем петлю к боту и запускаем его
from collections import Counter
user = ['one', 'one', 'one', 'four']
glob = [('two',), ('two',), ('three',)]
def combine(user, glob):
suggestions_user = [item[0] for item in Counter(user).most_common()]
suggestions_global = [item[0] for item in Counter(i[0] for i in glob).most_common()]
return {
'suggestions_user': suggestions_user,
'suggestions_global': suggestions_global,
'combined_suggestions': suggestions_user + suggestions_global
}
from aiogram import Bot, Dispatcher, executor, types
bot = Bot('token')
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def get_phone(message: types.Message):
keyboard = types.InlineKeyboardMarkup()
key_1 = types.InlineKeyboardButton(text='button 1', callback_data='b1')
keyboard.add(key_1)
key_2 = types.InlineKeyboardButton(text='button 2', callback_data='b2')
keyboard.add(key_2)
await bot.send_message(message.from_user.id, text='Выберите, нажав одну из кнопок:', reply_markup=keyboard)
@dp.callback_query_handler(lambda call: True)
async def get_storage(callback: types.CallbackQuery):
if callback.data == 'b1':
await callback.message.answer('Вы нажали на button 1')
if callback.data == 'b2':
await callback.message.answer('Вы нажали на button 2')
# Заглушка, чтобы кнопка не мигала после нажатия
await callback.answer()
executor.start_polling(dp)
import random
import time
def func(arr, el):
for i in arr[::-1]:
if i == el:
arr.remove(el)
return len(arr)
def remove_reverse(arr, el):
for i in reversed(arr):
if i == el:
arr.remove(el)
return len(arr)
def del_by_index_reverse(arr, el):
for i in reversed(range(len(arr))):
if arr[i] == el:
del arr[i]
return len(arr)
def del_by_index_while(arr, el):
i = 0
while i < len(arr):
if arr[i] == el:
# Удаляем значение по индексу и не сдвигаем указатель i
del arr[i]
else:
i += 1
return len(arr)
# Создаем массив из 100000 случайных цифр от 0 до 9 и сделаем по копии для каждой функции
arr1 = [random.randint(0, 9) for num in range(100_000)]
arr2 = arr1[:]
arr3 = arr1[:]
arr4 = arr1[:]
el = 5
start = time.perf_counter()
print(func(arr1, el))
print(time.perf_counter() - start)
start = time.perf_counter()
print(remove_reverse(arr2, el))
print(time.perf_counter() - start)
start = time.perf_counter()
print(del_by_index_reverse(arr3, el))
print(time.perf_counter() - start)
start = time.perf_counter()
print(del_by_index_while(arr4, el))
print(time.perf_counter() - start)
# Функция для подставления номера стороны и номера треугольника для отображения
def enter_length(side_num: str, triangle_num: str):
return f'Enter the length of {side_num} side of triangle {triangle_num} (cm): '
error_msg = 'Error! Please enter an integer or fractional number for the program to work correctly.'
repeat_msg = "Enter 'Y' for one more triangle or any key to exit: "
# Номер треугольника
triangle_num = 1
while True:
try:
sides = []
# Номер стороны из 3
for side_num in range(1, 4):
sides.append(
float(input(enter_length(str(side_num), str(triangle_num)))))
area_of_triangle(*sides)
except ValueError:
print(error_msg)
else:
response = input(repeat_msg)
if response == 'Y':
triangle_num += 1
else:
break
with open('text_file', encoding='utf-8') as file:
sorted_list = sorted(word.rstrip() for word in file.readlines())
with open('text_file', encoding='utf-8') as file:
sorted_dict = {i: word.rstrip() for i, word in enumerate(file.readlines())}
with open('text_file', encoding='utf-8') as file:
sorted_list_with_index = sorted(
{i: word.rstrip() for i, word in enumerate(file.readlines())}.items(),
key=lambda x: x[1]
)