Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Установка бота на render.com #8

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

Mehavoid
Copy link
Contributor

Привет. Так как heroku перекрыли кислород с бесплатным тиром (где бот успешно работал всё это время), перекатился на его аналог. С этой новостью, решил попробовать добавить изменения в апстрим.

Comment on lines +5 to +6
repo: https://github.com/Mehavoid/telegram-feedback-bot.git
branch: add-renderoku
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не забудьте заменить. :)

Copy link
Owner

@MasterGroosha MasterGroosha left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Привет! Спасибо за Pull Request. Даже не знаю, как к нему относиться :)

Я не юзал ни heroku, ни render.com, и не особо понимаю в них прикола, когда есть обычные VPS, но, видимо, надо попробовать.

И хочется некоторых пояснений, что с этим делать и куда. Будет ли работать для пользователей из РФ?

@@ -0,0 +1,2 @@
def urljoin(*args):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем? Тем более, что, возможно, на Windows это сломается

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Защита от дураков. Эта утилита не для путей, а для URL. Честно говоря, не нашел способа лучше для построения URL.


class Config:
env_file = '.env'
env_file_encoding = 'utf-8'
env_nested_delimiter = '__'
fields = {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если коротко, то для упрощения установки. Достаточно нажать на кнопку, которая указана в README, чтобы получить готовый проект. На странице нужно заполнить только переменные ADMIN_CHAT_ID и BOT_TOKEN, всё остальное подтянется из окружения.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так а fields зачем? Я не докапываюсь, хочу понять суть :)
Вроде как и без fields подтянется из окружения

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Подтянется, только придется их указывать при установке. А с этим могут быть проблемы у новичков, так как описание полей нет, как у heroku, например:
https://github.com/Mehavoid/telegram-feedback-bot/blob/684495cd5e79dda2e11ee66b932abb25e0250491/app.json#L10-L35
Можно переделать таким образом:

diff --git a/bot/config_reader.py b/bot/config_reader.py
index 572a4a5..9aeef6d 100644
--- a/bot/config_reader.py
+++ b/bot/config_reader.py
@@ -1,3 +1,5 @@
+import os
+
 from typing import Optional
 from secrets import token_urlsafe

@@ -19,17 +21,13 @@ class Settings(BaseSettings):
         env_file = '.env'
         env_file_encoding = 'utf-8'
         env_nested_delimiter = '__'
-        fields = {
-            "app_port": {
-                "env": "port",
-            },
-            "webhook_domain": {
-                "env": "render_external_hostname",
-            },
-            "webhook_path": {
-                "default_factory": token_urlsafe,
-            },
-        }


-config = Settings()
+if os.environ.get("RENDER"):
+    config = Settings(
+       app_port=os.environ.get("PORT"),
+       webhook_domain=os.environ.get("RENDER_EXTERNAL_HOSTNAME"),
+       webhook_path=token_urlsafe(32)
+    )
+else:
+    config = Settings()
(END)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Этот вариант мне нравится побольше 🤔

@Mehavoid
Copy link
Contributor Author

Работает для РФ. Привязки банковской карты не требует. 750 часов в месяц бесплатного использования для аккаунта. После 15 минутного простоя, приложение засыпает. С использованием вебхука очень экономично получается для нескольких ботов на аккаунте + RSS Bridge.

@MasterGroosha
Copy link
Owner

@Mehavoid прикольно, надо будет пощупать. Спасибо за PR, не обещаю смёржить прямо сейчас, но буду точно иметь в виду

@zlocate
Copy link

zlocate commented Oct 1, 2023

Поддержу автора PR. Heroku и Render это максимально простой и удобный способ отдеплоить бот на тест и пощупать и понять надо ли оно (вплоть до получения результата одной кнопкой)

Это крайне полезная фича ибо не требует даже git pull && сd && docker compose up && ngrok

Render действительно из оставшихся для россиян вариантов самый либеральный, хотя для новорегнутых гитхабов может и не дать создать инстансы.
Лично по моему скромному мнению - проект и пользователи только выйграют от возможности быстро потестить проект в реальном окружении парой кликов мышкой

### Render.com

[![Развернуть на Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Было бы круто запилить еще баттоны для DigitalOcean и пары других мейнстримных хостеров, но это уже явно за рамками этого PR

services:
- type: web # valid values: https://render.com/docs/yaml-spec#type
name: telegram-feedback-bot
repo: https://github.com/Mehavoid/telegram-feedback-bot.git
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Также заменить репо

env: python # valid values: https://render.com/docs/yaml-spec#environment
plan: free # optional; defaults to starter
region: frankfurt # https://render.com/docs/regions
buildCommand: "pip install -r requirements.txt"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А не лучше ли положить образ проекта к Github Container Registry и юзать здесь его? Тем самым ускорится запуск проекта и пользователь получит возможность погонять приложенку

@@ -62,10 +62,14 @@
3. Запустите бота: `docker compose up -d` (или `docker-compose up -d` на старых версиях Docker);
4. Проверьте, что контейнер поднялся: `docker compose ps`

### Render.com
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется было бы круто добросить коротко разъяснение вроде - "Самый простой способ увидеть приложение в "бою" - воспользоваться платформой render.com. Для этого зарегистрируйтесь на сайте и нажмите ..."

В отличие от хероку, рендер мало кто знает да и вообще для не слишком опытных пользователей оно будет полезно

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants