Versão Final do Lives do Cellbit#5
Open
victorblino wants to merge 51 commits into
Open
Conversation
This reverts commit d6e2a02.
This reverts commit a69230f.
- Update tweepy 4.10.1 -> 4.14.0 and other deps - Remove unused Twitter env vars (BEARER, KEY, SECRET, BOT_NICKNAME) - Fix wrong env var names (TWITCH_APP_KEY, TWITCH_TWITCH_BEARER, TWITCH_STREAMER_NICKNAME) - Remove broken postReply function - Update .env.example to match actual var names
- Migrate imports to twitchAPI.twitch.Twitch and EventSubWebhook - Convert all Twitch functions to async/await - Replace dict access with typed object attributes (data.event.*) - Replace threading.Event with asyncio.Event in bot.py - Fix get_games call to pass list and use async for - Capitalize streamer_nickname via .capitalize()
Add BotConfig (config.py) with load_from_env() to fetch required environment variables and raise on missing values. Introduce StreamState (core/stream_state.py) dataclass tracking online/current_game/stream_title with reset_for_offline() and update_from_update() helpers. Add unit tests (tests/unit/test_stream_state.py) covering default state, updates, and offline reset behavior.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Plano de Refatoração para Versão Final
Objetivo
Criar uma versão final mais limpa, organizada e fácil de manter usando:
1. Diagnóstico inicial
Atualmente, o bot está distribuído em:
bot.py— lógica principal, configuração e webhooksfunctions/botFunctions.py— utilitários misturadosfunctions/twitchFunctions.py— lógica de Twitch e EventSubfunctions/twitterFunctions.py— lógica de Twitterutils/variables.py— configuração e estado globalProblemas observados:
online,currentGame,gamesPlayed, etc.)2. Arquitetura proposta
2.1. Camadas sugeridas
Config/Settingsapp_id,app_secret,twitter_token,webhook_urlDomain/StateStreamState,ChannelStatus,GameHistoryService/ClientTwitchClient/EventSubServiceTwitterClient/TwitterServiceImageService/AssetServiceHandlerson_stream_online,on_stream_offline,on_channel_updateApplication/BotManagermain()ourun()2.2. Classes principais sugeridas
ConfigouBotConfigBotStateouStreamStateTwitchServiceTwitterServiceGameImageServiceEventSubManagerBotApplication3. Plano de etapas detalhado
Etapa 1 — Organização do projeto
Criar arquivos/classes separadas:
config.pyouutils/config.pyservices/twitch_service.pyservices/twitter_service.pyservices/image_service.pyhandlers/stream_handlers.pybot.pysomente como ponto de entradaMover leitura de
.enve variáveis de ambiente para uma classeConfig.Mover constantes e listas fixas para um local único (ex.:
constants.py).Etapa 2 — Definir estado e domínio
Criar
StreamState:online: boolcurrent_game: str | Nonecurrent_title: str | Nonestream_id: str | Nonegames_played: list[str]Criar
GameHistoryouGameTrackerse precisar de regras extras.Evitar usar variáveis globais em módulos. Todas as funções devem receber instâncias.
Etapa 3 — Criar serviços responsáveis
TwitterServicepost_status(text: str)post_status_with_image(text: str, image_path: str)TwitchServiceEventSubManagerGameImageServiceEtapa 4 — Implementar handlers limpos
StreamHandlersdeve receberConfig,StreamState,TwitterService,TwitchService,GameImageService.Cada handler deve:
StreamStateExemplo de fluxo:
on_stream_online(data)twitter_service.post_status(...)on_channel_update(data)Etapa 5 — Refatoração incremental
ConfigeStreamState.bot.pye em todos os módulos.twitterFunctions.pypara serTwitterService.twitchFunctions.pyparaTwitchService+EventSubManager.botFunctions.pypara métodos de serviço ou funções puras.Etapa 6 — Testes e validação
Escrever testes unitários para:
TwitterService(mock de API)GameImageServiceStreamState/GameHistorychannel_update,stream_offline,stream_onlineTestar manualmente com um ambiente local ou sandbox Twitch/Twitter.
Validar que
bot.pynão executa nada ao importar o módulo; apenas executa viaif __name__ == '__main__':.Etapa 7 — Polimento final
Atualizar
README.mdcom instruções de uso, variáveis de ambiente e deploy.Incluir
Procfile/requirements.txtcorretos e possivelmenteruntime.txtse usar Heroku.Adicionar logs estruturados em vez de
print()quando possível.Revisar nomes de variáveis para clareza, por exemplo:
current_gameem vez decurrentGamestream_titleem vez decurrentTitlegame_blacklistRemover código comentado e imports não usados.
4. Melhorias específicas para versão final
try/exceptgenéricos sem tratamento (except:)time.sleep()outhreading.Event()fora da aplicação principaltypinge docstrings simples5. Exemplo de fluxo de implementação
config.py->BotConfigstate.py->StreamStateservices/twitter_service.py,services/twitch_service.py,services/image_service.pyhandlers/stream_handlers.pybot.py->BotApplication(run)tests/ousrc/tests/6. Resultado esperado
Ao final, a aplicação deve ter: