Beispiel #1
0
def launch():
    start_webhook(dispatcher=dp,
                  webhook_path=WEBHOOK_PATH,
                  on_startup=on_startup,
                  on_shutdown=on_shutdown,
                  host=WEBAPP_HOST,
                  port=WEBAPP_PORT)
Beispiel #2
0
def main():
    """Start bot in webhook mode.

    Bot's main entry point.
    """
    url_token = secrets.token_urlsafe()
    webhook_path = config.WEBHOOK_PATH + "/" + url_token

    bot.setup()
    executor.start_webhook(
        dispatcher=dp,
        webhook_path=webhook_path,
        on_startup=lambda *args: on_startup(webhook_path, *args),
        on_shutdown=lambda *args: close_blockchains(),
        host=config.INTERNAL_HOST,
        port=config.SERVER_PORT,
    )
    print()  # noqa: T001  Executor stopped with ^C

    # Stop all background tasks
    loop = asyncio.get_event_loop()
    for task in asyncio.all_tasks(loop):
        task.cancel()
        try:
            loop.run_until_complete(task)
        except asyncio.CancelledError:
            pass
Beispiel #3
0
 def run(self):
     logging.basicConfig(level=logging.DEBUG)
     start_webhook(dispatcher=self.dispatcher,
                   webhook_path=self.webhook_path,
                   on_startup=self.__on_startup,
                   on_shutdown=self.__on_shutdown,
                   skip_updates=True,
                   host=self.host,
                   port=self.port)
Beispiel #4
0
def main(): 
    start_webhook(
        dispatcher=dp,
        webhook_path=WEBHOOK_PATH,
        skip_updates=True,
        on_startup=on_startup,    
        host=WEBAPP_HOST,
        port=WEBAPP_PORT,
    )
Beispiel #5
0
def main():
    executor.start_polling(dp, skip_updates=True)
    logging.basicConfig(level=logging.INFO)
    start_webhook(
        dispatcher=dp,
        webhook_path=WEBHOOK_PATH,
        skip_updates=True,
        host=WEBAPP_HOST,
        #port=WEBAPP_PORT
    )
def main():
    logging.basicConfig(level=logging.INFO)
    start_webhook(
        dispatcher=dp,
        webhook_path=WEBHOOK_PATH,
        skip_updates=True,
        on_startup=on_startup,
        host=WEBAPP_HOST,
        port=WEBAPP_PORT,
    )
Beispiel #7
0
 def polling(self):
     # executor.start_polling(dispatcher=self.dp,
     #                        skip_updates=True,
     #                        loop=loop,
     #                        on_shutdown=self.shutdown)
     executor.start_webhook(dispatcher=self.dp,
                            webhook_path=self.WEBHOOK_PATH,
                            on_startup=self.on_startup,
                            on_shutdown=self.on_shutdown,
                            host=self.WEBAPP_HOST,
                            port=self.WEBAPP_PORT)
Beispiel #8
0
def webhook():
    ''' Webhook connection. '''
    from run_py_bot.config import WEBHOOK_PATH, WEBAPP_PORT, WEBAPP_HOST
    start_webhook(
        dispatcher=dp,
        webhook_path=WEBHOOK_PATH,
        on_startup=on_startup,
        on_shutdown=on_shutdown,
        skip_updates=True,
        host=WEBAPP_HOST,
        port=WEBAPP_PORT,
    )
Beispiel #9
0
 def start_webhook(self, webhook_path: str, webapp_host: str,
                   webapp_port: int, webhook_url: str):
     self.webhook_url = webhook_url
     start_webhook(
         dispatcher=self.dispatcher,
         webhook_path=webhook_path,
         on_startup=self.on_startup,
         on_shutdown=self.on_shutdown,
         skip_updates=True,
         host=webapp_host,
         port=webapp_port,
     )
Beispiel #10
0
def use_webhook():
    start_webhook(
        dispatcher=dp,
        on_startup=on_startup_for_webhook,
        on_shutdown=on_shutdown_for_webhook,
        skip_updates=bot_section.APP_BOT_SKIP_UPDATES,
        host=bot_section.APP_BOT_WEBHOOK_HOST,
        port=bot_section.APP_BOT_WEBHOOK_PORT,
        webhook_path=bot_section.APP_BOT_WEBHOOK_PATH,
        check_ip=bot_section.APP_BOT_CHECK_IP,
        retry_after=bot_section.APP_BOT_RETRY_AFTER
    )
Beispiel #11
0
def main():
    logging.basicConfig(level=logging.INFO)
    try:
        start_webhook(
            dispatcher=dp,
            webhook_path=WEBHOOK_PATH,
            skip_updates=True,
            on_startup=on_startup,
            host=WEBAPP_HOST,
            port=WEBAPP_PORT,
        )
    except Exception as e:
        logging.error("Error:" + str(e))
Beispiel #12
0
def main():
    thread.start()

    logging.basicConfig(level=logging.INFO)
    start_webhook(
        dispatcher=dp,
        webhook_path=WEBHOOK_PATH,
        loop=loop,
        skip_updates=True,
        on_startup=on_startup,
        on_shutdown=on_shutdown,
        host=WEBAPP_HOST,
        port=WEBAPP_PORT,
    )
Beispiel #13
0
def main():
    if os.environ.get("DATABASE_URL"):
        logging.basicConfig(level=logging.INFO)
        start_webhook(
            dispatcher=dp,
            webhook_path=WEBHOOK_PATH,
            skip_updates=True,
            on_startup=on_startup,
            host=WEBAPP_HOST,
            port=WEBAPP_PORT,
        )
    else:
        try:
            executor.start_polling(dp)
        except KeyboardInterrupt:
            exit(0)
Beispiel #14
0
def main():
    setup_logging()

    if LOCAL_DEV:
        executor.start_polling(dp, skip_updates=True)
    else:
        print('Non local run')
        print(WEBHOOK_URL)
        print(WEBHOOK_PATH)
        print(WEBAPP_HOST)
        print(WEBAPP_PORT)
        start_webhook(dispatcher=dp,
                      webhook_path=WEBHOOK_PATH,
                      skip_updates=True,
                      on_startup=on_startup,
                      host=WEBAPP_HOST,
                      port=WEBAPP_PORT)
def main(arguments):
    args = parser.parse_args(arguments)
    token = args.token
    sock = args.sock
    host = args.host
    port = args.port
    cert = args.cert
    pkey = args.pkey
    host_name = args.host_name or host
    webhook_port = args.webhook_port or port
    webhook_path = args.webhook_path

    # Fi webhook path
    if not webhook_path.startswith('/'):
        webhook_path = '/' + webhook_path

    # Generate webhook URL
    webhook_url = f"https://{host_name}:{webhook_port}{webhook_path}"

    # Create bot & dispatcher instances.
    bot = Bot(token)
    dispatcher = Dispatcher(bot)

    if (sock or host) and host_name:
        if cert and pkey:
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            ssl_context.load_cert_chain(cert, pkey)
        else:
            ssl_context = None

        start_webhook(dispatcher,
                      webhook_path,
                      on_startup=functools.partial(on_startup,
                                                   url=webhook_url,
                                                   cert=cert),
                      on_shutdown=on_shutdown,
                      host=host,
                      port=port,
                      path=sock,
                      ssl_context=ssl_context)
    else:
        start_polling(dispatcher,
                      on_startup=on_startup,
                      on_shutdown=on_shutdown)
Beispiel #16
0
def start_bot(mode, config):

    api = config["general"]["api"]

    token = api["token"]
    webhook_url = URL(api["webhook"]["url"]) if api["webhook"]["url"] else None
    cert = api["webhook"]["cert"]
    pkey = api["webhook"]["pkey"]
    proxy_url = api["proxy"]["url"]

    if not api["proxy"]["login"] or not api["proxy"]["password"]:
        proxy_auth = None
    else:
        proxy_auth = BasicAuth(login=api["proxy"]["login"],
                               password=api["proxy"]["password"])

    # Create bot & dispatcher instances.
    bot = Bot(token, proxy=proxy_url, proxy_auth=proxy_auth)
    dispatcher = Dispatcher(bot)
    dispatcher["config"] = config
    logger.info(f"Initialize dispatcher: {dispatcher}")

    if mode == "webhook":
        if cert and pkey:
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            ssl_context.load_cert_chain(cert, pkey)
        else:
            ssl_context = None

        start_webhook(dispatcher,
                      webhook_url.path,
                      on_startup=on_startup,
                      url=str(webhook_url),
                      cert=cert,
                      on_shutdown=on_shutdown,
                      host=webhook_url.host,
                      port=webhook_url.port,
                      ssl_context=ssl_context)
    else:
        start_polling(dispatcher,
                      on_startup=on_startup,
                      on_shutdown=on_shutdown)
Beispiel #17
0
def start(socket_name=None):
    if socket_name:
        path = str(config.ROOT_PATH / 'socks' / socket_name)
        host = None
        port = None
    else:
        path = None
        host = config.WEBAPP_HOST
        port = config.WEBAPP_PORT

    webhook_path = f'/callback/{config.BOT_API_TOKEN}/'
    start_webhook(
        dispatcher=dispatcher,
        webhook_path=webhook_path,
        on_startup=_on_startup,
        on_shutdown=_on_shutdown,
        skip_updates=True,
        host=host,
        port=port,
        path=path,
    )
Beispiel #18
0
def main():
    try:
        db.create_pool()
        with db.get_connection() as conn:
            db.create_schema(conn)

        if settings.WEBHOOK_ENABLED:
            start_webhook(
                dispatcher=dp,
                webhook_path=settings.WEBHOOK_PATH,
                skip_updates=True,
                on_startup=bot_startup,
                host=settings.WEBAPP_HOST,
                port=settings.WEBAPP_PORT,
            )
        else:
            executor.start_polling(dp,
                                   on_startup=bot_startup,
                                   on_shutdown=bot_shutdown)
    finally:
        db.close_pool()
Beispiel #19
0
            pass
        else:
            external_url = parse.quote(match_result.group())
            text = parse.quote(message.text.split('|')[1])
            try:
                await bot.send_message(
                    message.chat.id,
                    'Вот ссылка для кнопки \"Поделиться\" (просто скопируйте следующее сообщение):'
                )
                await bot.send_message(
                    message.chat.id,
                    '{!s}{!s}&text={!s}'.format(config.output_base,
                                                external_url, text))
            except Exception as ex:
                print(type(ex), ex)

    return


async def on_startup(app):
    await bot.set_webhook("https://example.com/your_webhook")


if __name__ == '__main__':
    # use skip_updates=True to... well... skip updates :D
    start_webhook(dispatcher=dp,
                  host="127.0.0.1",
                  port=9999,
                  on_startup=on_startup,
                  webhook_path="")
loop = asyncio.get_event_loop()
bot = Bot(token=BOT_TOKEN, loop=loop)
dp = Dispatcher(bot)


@dp.message_handler()
async def echo(message: types.Message):
    await bot.send_message(message.chat.id, message.text)


async def on_startup(dp):
    await bot.set_webhook('')


async def on_shutdown(dp):
    await bot.delete_webhook()


if __name__ == '__main__':
    try:
        start_webhook(dispatcher=dp,
                      webhook_path="/",
                      on_startup=on_startup,
                      on_shutdown=on_shutdown,
                      skip_updates=True,
                      host=const.HOST,
                      port=const.PORT)
    except Exception as error:
        print(error)
Beispiel #21
0

async def on_startup(dp):
    await bot.set_webhook(WEBHOOK_URL)
    # insert code here to run it after start


async def on_shutdown(dp):
    logging.warning('Shutting down..')

    # insert code here to run it before shutdown

    # Remove webhook (not acceptable in some cases)
    await bot.delete_webhook()

    # Close DB connection (if used)
    await dp.storage.close()
    await dp.storage.wait_closed()

    logging.warning('Bye!')


if __name__ == '__main__':
    start_webhook(dispatcher=dp,
                  webhook_path=WEBHOOK_PATH,
                  on_startup=on_startup,
                  on_shutdown=on_shutdown,
                  skip_updates=True,
                  host=WEBAPP_HOST,
                  port=WEBAPP_PORT)
Beispiel #22
0
        await db.insert_one(convert(message))


@dp.edited_message_handler()
async def edit_msg(message: types.Message):
    if message.chat.username == settings.chat:
        await db.insert_one(convert(message))


async def on_startup(dp):
    await bot.set_webhook(settings.webhook_url + settings.webhook_path)


async def on_shutdown(dp):
    await bot.delete_webhook()


logging.basicConfig(level=logging.DEBUG)

if __name__ == "__main__":
    start_webhook(
        dispatcher=dp,
        webhook_path=settings.webhook_path,
        on_startup=on_startup,
        on_shutdown=on_shutdown,
        skip_updates=True,
        host=settings.host,
        port=settings.port,
        loop=loop,
    )
Beispiel #23
0
            sticker=await get_random_sticker("honka_animated"),
            chat_id=message.chat.id
        )
        return

    if get_with_probability(1):
        # Translate to UK
        translated = translate(message.html_text)
        await bot.send_message(
            reply_to_message_id=message.message_id,
            chat_id=message.chat.id,
            text=translated
        )
    await state.reset_state()


async def startup(dp):
    await bot.set_webhook(WEBHOOK_URL)
    await get_stikers()


if __name__ == '__main__':
    start_webhook(
        dispatcher=telegram_api_dispatcher,
        webhook_path=f"/{BOT_TOKEN}",
        on_startup=startup,
        skip_updates=True,
        host=HOST,
        port=PORT
    )
    # insert code here to run it before shutdown

    # Remove webhook (not acceptable in some cases)
    await bot.delete_webhook()

    # Close DB connection (if used)
    await dp.storage.close()
    await dp.storage.wait_closed()

    logging.warning('Bye!')


if __name__ == '__main__':

    context = ssl.SSLContext()
    context.load_cert_chain(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV)

    logging.info(f"start_webhook: {WEBAPP_HOST}:{WEBAPP_PORT}{WEBHOOK_PATH}")

    start_webhook(
        dispatcher=dp,
        webhook_path=WEBHOOK_PATH,
        on_startup=on_startup,
        on_shutdown=on_shutdown,
        skip_updates=False,
        host=WEBAPP_HOST,
        port=WEBAPP_PORT,
        ssl_context=context,
    )
Beispiel #25
0
@dp.message_handler(commands=[update_command])
@dp.async_task
async def send_update(message: types.Message):
    await bot.send_update(message)


@dp.message_handler(commands=[retraction_command])
@dp.async_task
async def send_retraction(message: types.Message):
    await bot.send_retraction(message)


async def on_startup(dp):
    webhook_url = f"{get_ngrok_url()}/{secret}"
    await bot.set_webhook(webhook_url)


if __name__ == "__main__":
    webapp_host = "localhost"
    webapp_port = get_port()

    start_webhook(
        dispatcher=dp,
        webhook_path=f"/{secret}",
        on_startup=on_startup,
        skip_updates=True,
        host=webapp_host,
        port=webapp_port,
    )
Beispiel #26
0
from zmanim_bot.handlers import register_handlers
from zmanim_bot.middlewares import setup_middlewares
from zmanim_bot.misc import dp, logger
from zmanim_bot.utils import ensure_mongo_index

sentry_sdk.init(dsn=config.SENTRY_KEY, integrations=[AioHttpIntegration()])


async def on_start(_):
    setup_middlewares()
    register_handlers()

    await ensure_mongo_index()

    if config.METRICS_DSN:
        await aiogram_metrics.register(config.METRICS_DSN,
                                       config.METRICS_TABLE_NAME)

    logger.info('Starting zmanim_api bot...')


async def on_close(_):
    await aiogram_metrics.close()


if __name__ == '__main__':
    if config.IS_PROD:
        start_webhook(dp, config.WEBHOOK_PATH, on_startup=on_start)
    else:
        start_polling(dp, on_startup=on_start, skip_updates=True)
            await callback_query.message.delete()
        except MessageToDeleteNotFound:
            pass
        await send_start_message(callback_query.from_user.id)

    elif query == 'select':
        # код при выборе поставщика
        pass


async def on_startup(*args, **kwargs):
    await bot.delete_webhook()
    await bot.set_webhook(WEBHOOK_URL)


if __name__ == '__main__':
    logger.info('Starting..')

    if CONNECTION_TYPE == 'polling':
        logger.info('Connection mode: polling.')
        executor.start_polling(dispatcher, skip_updates=True)

    elif CONNECTION_TYPE == 'webhook':
        logger.info('Connection mode: webhook.')
        executor.start_webhook(dispatcher=dispatcher,
                               webhook_path=WEBHOOK_PATH,
                               on_startup=on_startup,
                               skip_updates=True,
                               host='0.0.0.0',
                               port=int(os.getenv('PORT', 5000)))
Beispiel #28
0
    admins = await db_mng.get_bot_admins()
    for admin in admins:
        await bot.send_message(admin, text, disable_notification=True)


async def on_startup_webhook(dp):
    await notify_admins("I'm alive!")
    await bot.set_webhook(WEBHOOK_URL)


async def on_startup_polling(dp):
    await notify_admins("I'm alive!")


async def on_shutdown(dp):
    await bot.delete_webhook()


if __name__ == '__main__':
    if script_args.debugging:
        executor.start_polling(dp,
                               reset_webhook=True,
                               on_startup=on_startup_polling)
    else:
        start_webhook(dispatcher=dp,
                      webhook_path=WEBHOOK_URL_PATH,
                      on_startup=on_startup_webhook,
                      on_shutdown=on_shutdown,
                      host=WEBHOOK_HOST,
                      port=WEBHOOK_PORT)
Beispiel #29
0
import aiopg
from aiogram import Dispatcher
from aiogram.utils.executor import start_polling, start_webhook

import zmanim_bot.handlers
from zmanim_bot.config import DSN, IS_PROD, WEBHOOK_PATH
from zmanim_bot.misc import dp
from better_exceptions.logger import logger


def fix_imports():
    _ = zmanim_bot.handlers


async def on_start(dispatcher: Dispatcher):
    db_conn = await aiopg.create_pool(DSN)
    dispatcher['db_pool'] = db_conn
    logger.info('Starting zmanim bot...')


if __name__ == '__main__':
    if IS_PROD:
        start_webhook(dp, WEBHOOK_PATH, on_startup=on_start)
    else:
        start_polling(dp, on_startup=on_start, skip_updates=True)

Beispiel #30
0
def send_to_all(message):
    """
    Sends given message to all users
    """
    if message.chat.id not in config.ADMINS:
        return

    text = message.text.replace('/sendToAll ', '')
    users = models.get_all_users()

    for user in users:
        bot.send_message(user.chat_id, text)


async def on_startup(app):
    """
    Simple hook for aiohttp application which manages webhook
    """
    await bot.delete_webhook()
    await bot.set_webhook(WEBHOOK_URL)

if __name__ == '__main__':
    start_webhook(
        dispatcher=dp,
        webhook_path=WEBHOOK_URL_PATH,
        on_startup=on_startup,
        skip_updates=True,
        host='0.0.0.0',
        port=os.getenv('PORT'),
    )