1
0
mirror of https://github.com/civsocit/olgram.git synced 2025-12-17 07:56:16 +00:00

Instance в режиме Polling

This commit is contained in:
mihalin
2021-07-01 19:51:59 +03:00
parent d738da2fa9
commit 60bb00bcc9
6 changed files with 212 additions and 81 deletions

View File

@@ -12,10 +12,12 @@ router = Router()
# Пользователь выбрал бота
select_bot = CallbackData('bot_select', 'bot_id')
# Пользователь выбрал, что хочет сделать со своим ботом
bot_operation = CallbackData('bot_operation', 'operation')
bot_operation = CallbackData('bot_operation', 'bot_id', 'operation')
# Пользователь выбрал чат
select_bot_chat = CallbackData('chat_select', 'bot_id', 'chat_id')
@router.callback_query_handler(select_bot.filter())
@router.callback_query_handler(select_bot.filter(), state="*")
async def select_bot_callback(call: types.CallbackQuery, callback_data: dict, state: FSMContext):
"""
Пользователь выбрал бота для редактирования
@@ -23,20 +25,20 @@ async def select_bot_callback(call: types.CallbackQuery, callback_data: dict, st
bot_id = callback_data["bot_id"]
bot = await Bot.get_or_none(id=bot_id)
if not bot or (await bot.owner).telegram_id != call.from_user.id:
await call.answer("Такого бота нет", show_alert=True)
await call.answer("Такого бота нет, либо он принадлежит не вам", show_alert=True)
return
async with state.proxy() as proxy:
proxy["bot"] = bot
await try_delete_message(call.message)
keyboard = types.InlineKeyboardMarkup(row_width=2)
keyboard.insert(types.InlineKeyboardButton(text="Текст", callback_data=bot_operation.new(operation="text")))
keyboard.insert(types.InlineKeyboardButton(text="Чат", callback_data=bot_operation.new(operation="chat")))
keyboard.insert(types.InlineKeyboardButton(text="Удалить бот", callback_data=bot_operation.new(operation="delete")))
keyboard.insert(types.InlineKeyboardButton(text="Текст",
callback_data=bot_operation.new(bot_id=bot_id, operation="text")))
keyboard.insert(types.InlineKeyboardButton(text="Чат",
callback_data=bot_operation.new(bot_id=bot_id, operation="chat")))
keyboard.insert(types.InlineKeyboardButton(text="Удалить бот",
callback_data=bot_operation.new(bot_id=bot_id, operation="delete")))
keyboard.insert(types.InlineKeyboardButton(text="<<Вернуться к списку ботов",
callback_data=bot_operation.new(operation="back")))
callback_data=bot_operation.new(bot_id=bot_id, operation="back")))
await AioBot.get_current().send_message(call.message.chat.id, dedent(f"""
Управление ботом @{bot.name}.
@@ -44,3 +46,45 @@ async def select_bot_callback(call: types.CallbackQuery, callback_data: dict, st
Если у вас возникли вопросы по настройке бота, то посмотрите нашу справку /help.
"""), reply_markup=keyboard)
@router.callback_query_handler(bot_operation.filter(operation="delete"), state="*")
async def delete_bot_callback(call: types.CallbackQuery, callback_data: dict, state: FSMContext):
bot_id = callback_data["bot_id"]
bot = await Bot.get_or_none(id=bot_id)
if not bot or (await bot.owner).telegram_id != call.from_user.id:
await call.answer("Такого бота нет, либо он принадлежит не вам", show_alert=True)
return
await bot.delete()
await call.answer("Бот удалён")
await try_delete_message(call.message)
@router.callback_query_handler(bot_operation.filter(operation="chat"), state="*")
async def chats_bot_callback(call: types.CallbackQuery, callback_data: dict, state: FSMContext):
bot_id = callback_data["bot_id"]
bot = await Bot.get_or_none(id=bot_id)
if not bot or (await bot.owner).telegram_id != call.from_user.id:
await call.answer("Такого бота нет, либо он принадлежит не вам", show_alert=True)
return
await try_delete_message(call.message)
keyboard = types.InlineKeyboardMarkup(row_width=2)
chats = await bot.group_chats.all()
if not chats:
return await AioBot.get_current().send_message(call.message.chat.id, dedent(f"""
Этот бот не добавлен в чаты, поэтому все сообщения будут приходить вам в бот.
Чтобы подключить чат — просто добавьте бот @{bot.name} в чат.
"""), reply_markup=keyboard)
for chat in chats:
keyboard.insert(types.InlineKeyboardButton(text=chat.name,
callback_data=select_bot_chat.new(bot_id=bot_id, chat_id=chat.id)))
await AioBot.get_current().send_message(call.message.chat.id, dedent(f"""
В этом разделе вы можете привязать бота @{bot.name} к чату.
Выберите чат, куда бот будет пересылать сообщения.
"""), reply_markup=keyboard)

View File

@@ -1,6 +1,7 @@
from aiogram import types, Bot as AioBot
from aiogram.dispatcher import FSMContext
from aiogram.utils.exceptions import Unauthorized, TelegramAPIError
from tortoise.exceptions import IntegrityError
import re
from textwrap import dedent
@@ -40,9 +41,9 @@ async def add_bot(message: types.Message, state: FSMContext):
"""
Команда /addbot (добавить бота)
"""
bot_count = await Bot.filter(user__telegram_id=message.from_user.id).count()
if bot_count > OlgramSettings.max_bots_per_user():
await message.answer("У вас уже слишком много ботов")
bot_count = await Bot.filter(owner__telegram_id=message.from_user.id).count()
if bot_count >= OlgramSettings.max_bots_per_user():
await message.answer("У вас уже слишком много ботов.")
return
await message.answer(dedent("""
@@ -83,6 +84,11 @@ async def bot_added(message: types.Message, state: FSMContext):
Не удалось запустить этого бота: непредвиденная ошибка
"""))
async def on_duplication_bot():
await message.answer(dedent("""
Такой бот уже есть в базе данных
"""))
if not token:
return await on_invalid_token()
@@ -100,7 +106,11 @@ async def bot_added(message: types.Message, state: FSMContext):
return await on_unknown_error()
user, _ = await User.get_or_create(telegram_id=message.from_user.id)
bot = Bot(token=token, owner=user, name=test_bot_info.username)
await bot.save()
bot = Bot(token=token, owner=user, name=test_bot_info.username, super_chat_id=message.from_user.id)
try:
await bot.save()
except IntegrityError:
return await on_duplication_bot()
await message.answer("Бот добавлен!")
await state.reset_state()

View File

@@ -1,12 +1,21 @@
from tortoise.models import Model
from tortoise import fields
from textwrap import dedent
class Bot(Model):
id = fields.IntField(pk=True)
token = fields.CharField(max_length=50, unique=True)
owner = fields.ForeignKeyField("models.User", related_name="bots")
name = fields.CharField(max_length=33)
start_text = fields.TextField(default=dedent("""
Здравствуйте!
Напишите ваш вопрос и мы ответим Вам в ближайшее время.
"""))
super_chat_id = fields.IntField()
group_chats = fields.ManyToManyField("models.GroupChat", related_name="bots", on_delete=fields.relational.SET_NULL)
class Meta:
table = 'bot'
@@ -18,3 +27,12 @@ class User(Model):
class Meta:
table = 'user'
class GroupChat(Model):
id = fields.IntField(pk=True)
chat_id = fields.IntField(index=True, unique=True)
name = fields.CharField(max_length=50)
class Meta:
table = 'group_chat'

View File

@@ -1,5 +1,5 @@
from tortoise import Tortoise
from settings import DatabaseSettings
from olgram.settings import DatabaseSettings
async def init_database():