def __init__( self, redis_host, redis_port, redis_db, redis_password, config: TelegramBotServiceConfig = default_telegram_bot_service_config, loop: Optional[asyncio.AbstractEventLoop] = None): self._config = config self.loop = loop or asyncio.get_event_loop() self.redis_host = redis_host self.redis_port = int(redis_port) self.redis_db = int(redis_db) self.redis_password = redis_password self._storage = RedisStorage(host=self.redis_host, port=self.redis_port, db=self.redis_db, password=self.redis_password) self._bot = Bot(token=self._config.token, proxy=self._config.proxy, loop=self.loop) self._dispatcher = Dispatcher(self._bot, loop=self.loop, storage=self._storage) self._executor = Executor(self._dispatcher, skip_updates=True, loop=self.loop)
def __init__(self, bot: NazurinBot): super().__init__(bot) self.middleware.setup(AuthMiddleware()) self.filters_factory.bind(URLFilter, event_handlers=[self.message_handlers]) self.server = NazurinServer(bot) self.server.on_startup.append(self.on_startup) self.executor = Executor(self)
async def _start_polling(self): executor = Executor(self._dispatcher, skip_updates=False) executor._prepare_polling() loop: asyncio.AbstractEventLoop = executor.loop try: await executor._startup_polling() await self._dispatcher.start_polling() except (KeyboardInterrupt, SystemExit): loop.stop() pass finally: await executor._shutdown_polling()
class NazurinDispatcher(Dispatcher): def __init__(self, bot: NazurinBot): super().__init__(bot) self.middleware.setup(AuthMiddleware()) self.filters_factory.bind(URLFilter, event_handlers=[self.message_handlers]) self.server = NazurinServer(bot) self.server.on_startup.append(self.on_startup) self.executor = Executor(self) def init(self): self.bot.init() self.register_message_handler( self.update_collection, URLFilter(), content_types=[ContentType.TEXT, ContentType.PHOTO]) def register_message_handler(self, callback, *args, **kwargs): return super().register_message_handler(self.async_task(callback), *args, **kwargs) async def on_startup(self, dp): await self.bot.set_webhook(config.WEBHOOK_URL + config.TOKEN, allowed_updates=AllowedUpdates.MESSAGE) def start(self): self.init() if config.ENV == 'production': logger.info('Set webhook') self.executor.set_webhook(webhook_path='/' + config.TOKEN, web_app=self.server) # Tell aiohttp to use main thread event loop instead of creating a new one # otherwise bot commands will run in a different loop # from main thread functions and classes like Mongo and Mega.api_upload, # resulting in RuntimeError: Task attached to different loop self.executor.run_app(host="0.0.0.0", port=config.PORT, loop=asyncio.get_event_loop()) else: # self.server.start() executor.start_polling(self, skip_updates=True) async def update_collection(self, message: Message, urls: List[str]): await self.bot.updateCollection(urls, message) await message.reply('Done!')
def main(socket_path, port): from alarmbot.views import app from alarmbot.receptionist import dp logger.level = logbook.DEBUG logging.basicConfig(level=logging.INFO) loop = asyncio.get_event_loop() executor = Executor(dp, skip_updates=True, loop=loop) logger.info('{}', executor) executor.set_webhook(web_app=app) if not socket_path: executor.run_app(port=port) else: executor.run_app(path=socket_path)
class NazurinDispatcher(Dispatcher): def __init__(self, bot: NazurinBot): super().__init__(bot) self.middleware.setup(AuthMiddleware()) self.filters_factory.bind(URLFilter, event_handlers=[self.message_handlers]) self.server = NazurinServer(bot) self.server.on_startup.append(self.on_startup) self.executor = Executor(self) def init(self): self.bot.init() self.register_message_handler( self.update_collection, URLFilter(), content_types=[ContentType.TEXT, ContentType.PHOTO]) def register_message_handler(self, callback, *args, **kwargs): return super().register_message_handler(self.async_task(callback), *args, **kwargs) async def on_startup(self, dp): await self.bot.set_webhook(config.WEBHOOK_URL + config.TOKEN, allowed_updates=AllowedUpdates.MESSAGE) def start(self): self.init() if config.ENV == 'production': logger.info('Set webhook') self.executor.set_webhook(webhook_path='/' + config.TOKEN, web_app=self.server) self.executor.run_app(host="0.0.0.0", port=config.PORT) else: # self.server.start() executor.start_polling(self, skip_updates=True) async def update_collection(self, message: Message, urls: List[str]): await self.bot.updateCollection(urls, message) await message.reply('Done!')
def setup() -> tp.Tuple[Dispatcher, Executor]: logging.basicConfig(level=logging.INFO) engine = create_engine(config.get_postgres_uri()) session = orm.Session(engine) proxy, proxy_auth = setup_proxy() bot = Bot(token=config.get_telegram_token(), proxy=proxy, proxy_auth=proxy_auth) dispatcher = Dispatcher(bot) filters.register(dispatcher) middlewares.register(dispatcher, session) handlers.register(dispatcher, session) executor = Executor(dispatcher, skip_updates=True) return dispatcher, executor
class TelegramBotService: def __init__( self, redis_host, redis_port, redis_db, redis_password, config: TelegramBotServiceConfig = default_telegram_bot_service_config, loop: Optional[asyncio.AbstractEventLoop] = None): self._config = config self.loop = loop or asyncio.get_event_loop() self.redis_host = redis_host self.redis_port = int(redis_port) self.redis_db = int(redis_db) self.redis_password = redis_password self._storage = RedisStorage(host=self.redis_host, port=self.redis_port, db=self.redis_db, password=self.redis_password) self._bot = Bot(token=self._config.token, proxy=self._config.proxy, loop=self.loop) self._dispatcher = Dispatcher(self._bot, loop=self.loop, storage=self._storage) self._executor = Executor(self._dispatcher, skip_updates=True, loop=self.loop) async def run_bot_task(self): logger.info('Bot polling started') self._dispatcher.register_message_handler(self._bot_start, commands=['start']) self._dispatcher.register_message_handler(self._show_menu, commands=['menu'], state='*') self._dispatcher.register_message_handler(self._registration_step_1, state=Registration.step_1) self._dispatcher.register_callback_query_handler(self._show_links, text='links') self._dispatcher.register_callback_query_handler(self._book, text='book') # self._dispatcher.register_callback_query_handler(self._edit_order, text='show_orders') self._dispatcher.register_callback_query_handler(self._book_step_1, state=Book.step_1) self._dispatcher.register_callback_query_handler(self._book_step_2_1, text='done', state=Book.step_2) self._dispatcher.register_callback_query_handler(self._book_step_2_2, text='cancel', state=Book.step_2) self._executor._prepare_polling() await self._executor._startup_polling() self.loop.create_task( self._dispatcher.start_polling(reset_webhook=True)) async def _bot_start(self, message: Message): telegram_id = message.chat.id check_admin = await Admin.query.where( Admin.telegram_id == str(telegram_id)).gino.first() if check_admin: await message.answer(f'Здравствуй, {check_admin.name}') await self._bot.send_message( telegram_id, 'Введите команду /menu посмотреть список доступных функций') return check_user = await User.query.where( User.telegram_id == str(telegram_id)).gino.first() if check_user: await message.answer(f'Здравствуйте, {check_user.name}') await self._bot.send_message( telegram_id, 'Введите команду /menu посмотреть список доступных функций') if all([(not check_user), (not check_admin)]): await message.answer( 'Здравствуйте, мы с Вами не знакомы. \n' 'Введите ваше ФИО, номер телефона, рост и вес.') example_registration = ' '.join([ 'Пример:', 'Иванов Иван Иванович', '+79020007126', '175', '80' ]) await self._bot.send_message(chat_id=telegram_id, text=example_registration) await Registration.step_1.set() async def _show_menu(self, message: Message): telegram_id = message.chat.id state = self._dispatcher.current_state(user=telegram_id) await state.reset_state() check_admin = await Admin.query.where( Admin.telegram_id == str(telegram_id)).gino.first() if check_admin: inline_menu = await get_kb_menu_for_admin() await message.answer( 'Здравствуйте, админстратор. Выберите интересующий вас пункт из меню ниже:', reply_markup=inline_menu) check_customer = await User.query.where( User.telegram_id == str(telegram_id)).gino.first() if check_customer: inline_menu = await get_kb_menu_for_customer() await message.answer( 'Выберите интересующий вас пункт из меню ниже:', reply_markup=inline_menu) if all([(not check_customer), (not check_admin)]): await message.answer( 'Здравствуйте, мы с Вами не знакомы. \n' 'Введите ваше ФИО, номер телефона, рост и вес.') example_registration = ' '.join([ 'Пример:', 'Иванов Иван Иванович', '+79020007126', '175', '80' ]) await self._bot.send_message(chat_id=telegram_id, text=example_registration) await Registration.step_1.set() # async def _edit_order(self, callback_query: CallbackQuery): # telegram_id = callback_query.id # # await callback_query.answer(cache_time=60) # await self._bot.answer_callback_query(callback_query.id) # await callback_query.message.edit_reply_markup(reply_markup=None) # # inline_menu = await get_kb_orders_menu() # await self._bot.send_message(telegram_id, 'Выберите интересующую вас заявку:', # reply_markup=inline_menu) async def _registration_step_1(self, message: Message, state: FSMContext): telegram_id = message.chat.id message_user = message.text.split(' ') if len(message_user) != 6: await message.answer('Введите как показано в примере') return name_message_user = message_user[0] + ' ' + message_user[ 1] + ' ' + message_user[2] phone_number_message_user = message_user[3] height_message_user = message_user[4] weight_message_user = message_user[5] new_user = await User.create(name=name_message_user, phone_number=phone_number_message_user, height=height_message_user, weight=weight_message_user, telegram_id=str(telegram_id)) result = f""" Данные успешно сохранены! Ваше ФИО: {new_user.name} Ваш номер телефона: {new_user.phone_number} Ваш вес: {new_user.weight} кг Ваш рост: {new_user.height} см""" await self._bot.send_message(telegram_id, result) await self._bot.send_message( telegram_id, 'Введите команду /menu посмотреть список доступных функций') await state.finish() async def _show_links(self, callback_query: CallbackQuery): telegram_id = callback_query.from_user.id await callback_query.answer(cache_time=60) await self._bot.answer_callback_query(callback_query.id) await callback_query.message.edit_reply_markup(reply_markup=None) inline_kb = await get_kb_out_links() await self._bot.send_message(telegram_id, 'Мы в соцсетях!', reply_markup=inline_kb) async def _book(self, callback_query: CallbackQuery): telegram_id = callback_query.from_user.id await callback_query.answer(cache_time=60) await self._bot.answer_callback_query(callback_query.id) await callback_query.message.edit_reply_markup(reply_markup=None) inline_kb = await get_kb_items_to_book() await self._bot.send_message(telegram_id, 'Выберите интересующий вас инвентарь:', reply_markup=inline_kb) await Book.step_1.set() async def _book_step_1(self, callback_query: CallbackQuery): call = callback_query.data telegram_id = callback_query.from_user.id await callback_query.answer(cache_time=60) await self._bot.answer_callback_query(callback_query.id) await callback_query.message.edit_reply_markup(reply_markup=None) inline_kb = await get_kb_order() item_data = await Item.query.where(Item.data == str(call)).gino.first() item_name = item_data.name item_price = item_data.price await Order.create(telegram_id=str(telegram_id), ordered_item=item_name, status='in treatment') await self._bot.send_message( telegram_id, f'Вы выбрали: {item_name}.\n' f'Стоимость бронирования этого инвентаря: {item_price}.\n' f'Хотите подать заявку?', reply_markup=inline_kb) await Book.step_2.set() async def _book_step_2_1(self, callback_query: CallbackQuery, state: FSMContext): telegram_id = callback_query.from_user.id await callback_query.answer(cache_time=60) await self._bot.answer_callback_query(callback_query.id) await callback_query.message.edit_reply_markup(reply_markup=None) right_order = await Order.query.where( Order.telegram_id == str(telegram_id)).gino.first() user_data = await User.query.where(User.telegram_id == str(telegram_id) ).gino.first() await self._bot.send_message(telegram_id, 'Заявка подана. Ожидайте звонка!') order_text = f""" Поступила заявка. Информация о заказчике: Имя: {user_data.name}. Номер телефона: {user_data.phone_number}. Заявка на следующий инвентарь: {right_order.ordered_item}. Заказчик ждет вашего звонка!""" await self._bot.send_message(227448700, order_text) await state.finish() async def _book_step_2_2(self, callback_query: CallbackQuery, state: FSMContext): telegram_id = callback_query.from_user.id await callback_query.answer(cache_time=60) await self._bot.answer_callback_query(callback_query.id) await callback_query.message.edit_reply_markup(reply_markup=None) await self._bot.send_message(telegram_id, 'Заявка сброшена.') await self._bot.send_message( telegram_id, 'Введите команду /menu посмотреть список доступных функций') wrong_order = await Order.query.where( Order.telegram_id == str(telegram_id)).gino.first() wrong_order.delete() await state.finish()
from app.core.config import ( TOKEN, MONGO_URL, MONGO_PORT, SKIP_UPDATES, MONGO_DB, MONGO_USER, MONGO_PSWD, REDIS_URI ) from app.core.utils import RedisCache logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) console_handler = logging.StreamHandler() console_handler.setLevel(logging.ERROR) formatter = logging.Formatter("[%(asctime)s] %(levelname)s - %(message)s") console_handler.setFormatter(formatter) logger.addHandler(console_handler) # Just some tricks to speed-up bot uvloop.install() loop = asyncio.get_event_loop() redis_cache = RedisCache(uri=REDIS_URI) api_client = ApiClient(redis_cache) bot = ClearBot(token=TOKEN, loop=loop) storage = MongoStorage(host=MONGO_URL, port=MONGO_PORT, db_name=MONGO_DB, username=MONGO_USER, password=MONGO_PSWD) dp = Dispatcher(bot, storage=storage) runner = Executor(dp, skip_updates=SKIP_UPDATES)
def vk_broadcaster_setup(runner: Executor): runner.on_startup(on_startup) runner.on_shutdown(on_shutdown)
import asyncio import logging from aiogram.contrib.fsm_storage.redis import RedisStorage2 from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.utils.executor import Executor from bot.config import BOT_TOKEN from bot.middleware import ThrottlingMiddleware storage = MemoryStorage() loop = asyncio.get_event_loop() storage = RedisStorage2(db=5) bot = Bot(token=BOT_TOKEN, parse_mode='HTML') dp = Dispatcher(bot, storage=storage) dp.middleware.setup(ThrottlingMiddleware()) executor = Executor(dp)
def setup(runner: Executor): runner.on_startup(on_startup) runner.on_shutdown(on_shutdown)
from tortoise import Tortoise from alarmbot.loghandlers import ColorizedStderrHandler from alarmbot.models import init_db from alarmbot.receptionist import dp # Configure logging logger = Logger(__name__) logger.handlers.append(ColorizedStderrHandler()) async def init_orm(dispatcher): await init_db() async def close_orm(dispatcher): await Tortoise.close_connections() if __name__ == '__main__': logger.level = logbook.DEBUG logging.basicConfig(level=logging.INFO) loop = asyncio.get_event_loop() executor = Executor(dp, skip_updates=True, loop=loop) logger.info('{}', executor) executor.on_startup(init_orm, polling=True) executor.on_shutdown(close_orm, polling=True) # executor.set_webhook(web_app=app) # executor.run_app(port=8000) executor.start_polling()
import logging from aiogram import Bot, Dispatcher from aiogram.utils.executor import Executor from aiogram.contrib.fsm_storage.memory import MemoryStorage from config import BOT_TOKEN logging.basicConfig(level=logging.INFO) logging.getLogger('gino').setLevel(logging.WARNING) bot = Bot(BOT_TOKEN, parse_mode='html') dp = Dispatcher(bot, storage=MemoryStorage()) executor = Executor(dp, skip_updates=True)
from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.contrib.middlewares.logging import LoggingMiddleware from aiogram.types import ParseMode from aiogram.utils.executor import Executor import sentry_sdk from core import config from core.packages import PackagesLoader from mixpanel import Mixpanel logging.basicConfig(level=logging.INFO) log = logging.getLogger('{{cookiecutter.bot_name}}') loop = asyncio.get_event_loop() bot = Bot(config.bot_token, parse_mode=ParseMode.HTML, validate_token=False) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage, loop=loop) runner = Executor(dp, skip_updates=config.skip_updates) loader = PackagesLoader() dp.middleware.setup(LoggingMiddleware('bot')) mp = Mixpanel(config.mixpanel_key) if config.sentry_url: sentry_sdk.init(config.sentry_url)
if not self.reciving_channel: print("Channel Not Found") sys.exit() print("The message is sending to:") print("\tChannel:\t", self.reciving_channel) print("\tGuild:\t\t", self.reciving_channel.guild) async def forward_message(self,message): await self.reciving_channel.send(message) loop = asyncio.new_event_loop() dc = custom_DC_client(loop=loop) tg_bot = Bot(TG_TOKEN,loop=loop) tg = Dispatcher(tg_bot,loop=loop) tg_exec = Executor(tg, skip_updates=True,loop=loop) @tg.message_handler() async def handle(message: types.Message): # You can check and edit the message at here print("Message:\n",message.md_text) await dc.forward_message(message.md_text) def main(): print("-"*40) # This part is a combined verison of `dc.run()`(from `discord.py`) and `excutor.start_polling`(from `aiogram`) # Running them sepratly will cause blocking tg_exec._prepare_polling() try: loop.run_until_complete(dc.login(DC_TOKEN))
def setup(executor: Executor): executor.on_startup(on_startup)
def setup(executor: Executor): executor.on_startup(on_startup, webhook=True, polling=False)
def scheduler_setup(executor: Executor): executor.on_startup(on_startup) executor.on_shutdown(on_shutdown)
from pathlib import Path from aiogram import Bot, Dispatcher from aiogram.types import ParseMode from aiogram.utils.executor import Executor from app.utils.misc.config import load_config proj_path = Path(__name__).parent.parent config = load_config(proj_path) bot = Bot(config['config']['bot']['TOKEN'], parse_mode=ParseMode.HTML) bot['config'] = config dp = Dispatcher(bot) e = Executor(dp)
def setup(executor: Executor): executor.on_startup(on_startup) executor.on_shutdown(on_shutdown)
from aiogram.utils.executor import Executor from app.misc import dp from app.models import db from aiogram import Dispatcher from loguru import logger runner = Executor(dp) def setup(): logger.info("Configure executor...") db.setup(runner) runner.start_polling(dp)
def setup(executor: Executor, db_config: DBConfig): executor.on_startup(partial(on_startup, db_config=db_config)) executor.on_shutdown(on_shutdown)