olgram/bot.py

67 lines
1.8 KiB
Python
Raw Normal View History

2021-06-11 21:56:03 +03:00
import asyncio
2021-07-01 19:51:59 +03:00
import aiogram.types
import tortoise.transactions
from aiogram import Bot as AioBot, Dispatcher
2021-06-11 21:56:03 +03:00
from aiogram.contrib.fsm_storage.memory import MemoryStorage
2021-07-01 19:51:59 +03:00
from olgram.settings import BotSettings
2021-06-11 21:56:03 +03:00
from olgram.bot.bots import router as bots_router
from olgram.bot.start import router as start_router
from olgram.bot.bot import router as bot_router
2021-06-11 21:56:03 +03:00
from olgram.utils.database import init_database
2021-07-01 19:51:59 +03:00
from olgram.models.models import Bot, GroupChat
from instance.bot import BotInstance
import typing as ty
async def invite_callback(identify: int, message: aiogram.types.Message):
bot = await Bot.get(id=identify)
chat, _ = await GroupChat.get_or_create(chat_id=message.chat.id,
defaults={"name": message.chat.full_name})
if chat not in await bot.group_chats.all():
await bot.group_chats.add(chat)
def run_bot(bot: BotInstance, loop: ty.Optional[asyncio.AbstractEventLoop] = None):
loop = loop or asyncio.get_event_loop()
loop.create_task(bot.start_polling())
async def run_all_bots(loop: asyncio.AbstractEventLoop):
bots = await Bot.all()
for bot in bots:
run_bot(BotInstance(bot.token,
bot.super_chat_id,
bot.start_text,
invite_callback=invite_callback,
identify=bot.id), loop)
2021-06-11 21:56:03 +03:00
def main():
"""
Classic polling
"""
2021-07-01 19:51:59 +03:00
loop = asyncio.get_event_loop()
loop.run_until_complete(init_database())
2021-06-11 21:56:03 +03:00
2021-07-01 19:51:59 +03:00
bot = AioBot(BotSettings.token())
2021-06-11 21:56:03 +03:00
dp = Dispatcher(bot, storage=MemoryStorage())
start_router.setup(dp)
bots_router.setup(dp)
bot_router.setup(dp)
2021-06-11 21:56:03 +03:00
2021-07-01 19:51:59 +03:00
loop.run_until_complete(run_all_bots(loop))
loop.create_task(dp.start_polling())
loop.run_forever()
2021-06-11 21:56:03 +03:00
if __name__ == '__main__':
main()