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
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. Для этого зарегистрируйтесь на сайте и нажмите ..."

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


[![Развернуть на 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

## Локализация

Если вы хотите изменить тексты в боте, ознакомьтесь с информацией в
[Wiki](https://github.com/MasterGroosha/telegram-feedback-bot/wiki). В настоящий момент поддерживается только
изменение текстов сообщений, но не описаний в меню команд

Папку `bot/locales` в случае с развертыванием бота в Docker можно переопределить, подсунув её снаружи как volume.
Папку `bot/locales` в случае с развертыванием бота в Docker можно переопределить, подсунув её снаружи как volume.
10 changes: 5 additions & 5 deletions bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from pathlib import Path

from bot.config_reader import config

from bot.util import urljoin

async def main():
# Настройка логирования в stdout
Expand Down Expand Up @@ -44,7 +44,7 @@ async def main():

try:
if not config.webhook_domain:
await bot.delete_webhook()
await bot.delete_webhook(drop_pending_updates=config.drop_pending_updates)
await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())
else:
# Выключаем логи от aiohttp
Expand All @@ -53,14 +53,14 @@ async def main():

# Установка вебхука
await bot.set_webhook(
url=config.webhook_domain + config.webhook_path,
drop_pending_updates=True,
url=f"https://{urljoin(config.webhook_domain, config.webhook_path)}",
drop_pending_updates=config.drop_pending_updates,
allowed_updates=dp.resolve_used_update_types()
)

# Создание запуска aiohttp
app = web.Application()
SimpleRequestHandler(dispatcher=dp, bot=bot).register(app, path=config.webhook_path)
SimpleRequestHandler(dispatcher=dp, bot=bot).register(app, path=urljoin("/", config.webhook_path))
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host=config.app_host, port=config.app_port)
Expand Down
22 changes: 17 additions & 5 deletions bot/config_reader.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
from typing import Optional
from secrets import token_urlsafe

from pydantic import BaseSettings, SecretStr
from pydantic import BaseSettings, Field, SecretStr


class Settings(BaseSettings):
Expand All @@ -12,11 +14,21 @@ class Settings(BaseSettings):
app_host: Optional[str] = "0.0.0.0"
app_port: Optional[int] = 9000
custom_bot_api: Optional[str]
drop_pending_updates: Optional[bool]

class Config:
env_file = '.env'
env_file_encoding = 'utf-8'
env_nested_delimiter = '__'
env_file = ".env"
env_file_encoding = "utf-8"
env_nested_delimiter = "__"


config = Settings()
class RenderSettings(Settings):
app_port: int = Field(..., env="PORT")
webhook_domain: str = Field(..., env="RENDER_EXTERNAL_HOSTNAME")
webhook_path: str = Field(default_factory=token_urlsafe)


if "RENDER" in os.environ:
config = RenderSettings()
else:
config = Settings()
2 changes: 2 additions & 0 deletions bot/util.py
Original file line number Diff line number Diff line change
@@ -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.

return "/".join(map(lambda x: str(x).strip("/"), args))
6 changes: 5 additions & 1 deletion env_example
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,8 @@ REMOVE_SENT_CONFIRMATION=yes

# Адрес собственного сервера Bot API (необязательно)
# Непустое значение является признаком включения локального режима
# CUSTOM_BOT_API = http://127.0.0.1:8081
# CUSTOM_BOT_API = http://127.0.0.1:8081

# Очищать или нет список обновлений при установке вебхука
# Чтобы очищать, укажите "yes", "1" или "true" (без кавычек)
# DROP_PENDING_UPDATES=yes
23 changes: 23 additions & 0 deletions render.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Schema documented at https://render.com/docs/yaml-spec
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.

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

branch: add-renderoku
Comment on lines +5 to +6
Copy link
Contributor Author

Choose a reason for hiding this comment

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

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

runtime: python # valid values: https://render.com/docs/blueprint-spec#runtime
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 и юзать здесь его? Тем самым ускорится запуск проекта и пользователь получит возможность погонять приложенку

startCommand: "python -m bot"
numInstances: 1
envVars:
- key: BOT_TOKEN
sync: false
- key: ADMIN_CHAT_ID
sync: false
- key: REMOVE_SENT_CONFIRMATION
sync: false
- key: DROP_PENDING_UPDATES
value: no
- key: PYTHON_VERSION # https://render.com/docs/python-version
value: 3.9.13