Skip to content

Commit

Permalink
fixed merge conflicts with dev
Browse files Browse the repository at this point in the history
  • Loading branch information
yishain11 committed Aug 2, 2024
2 parents 05e6c13 + 1df647b commit fa0b08e
Show file tree
Hide file tree
Showing 7 changed files with 132 additions and 65 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,15 @@ celerybeat.pid
*.sage.py

# Environments
.env
.env_dev
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

.env_prod
.env
# Spyder project settings
.spyderproject
.spyproject
Expand Down
102 changes: 59 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,64 @@
# code-genie-bot
telegram bot for code genie

=======
# Environment Variables (Explanation)
# code-genie-bot
telegram bot for code genie

=======
# Environment Variables (Explanation)
In `.env_dev` file save the following vars:
- `BOT_TOKEN_DEV`: The telegram bot token for full control. Example: **123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi_jklmnopqrstuvwx
**
- `SERVER_URL_DEV`: The backend server url for making requests. Example: **http://localhost:8000/"**

- `BOT_TOKEN`: The telegram bot token for full control. Example: **123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi_jklmnopqrstuvwx
**
- `SERVER_URL`: The backend server url for making requests. Example: **http://localhost:8000/"**
In `.env_prod` file save the following vars:
- `BOT_TOKEN_PROD`: The telegram bot token for full control. Example: **123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi_jklmnopqrstuvwx
**
- `SERVER_URL_PROD`: The backend server url for making requests. Example: **http://localhost:8000/"**
# Environment Variables (Usage)
To load environment variables from a `.env` file in Python, you can use the `python-dotenv` package. Here’s how you can do it:

1. Save an `.env` file in your project. **WARNING**: make sure it is found in `.gitignore`. Save the above [Variables](#environment-variables-explanation) in the `.env` file using the exact provided names.
2. **Install the `python-dotenv` package** (if you haven’t already):
```sh
pip install python-dotenv
```
3. A brief example on how to load a specific environment variable:
```python
import os
from dotenv import load_dotenv
load_dotenv('.env')
bot_token = os.getenv('BOT_TOKEN')
```
Run command for genie_bot :
1. To run in dev env:
```sh
python genie_bot.py dev
#or
python genie_bot.py
```
2. To run in production env:

# Environment Variables (Usage)
```sh
python genie_bot.py prod
```

To load environment variables from a `.env` file in Python, you can use the `python-dotenv` package. Here’s how you can do it:

1. Save an `.env` file in your project. **WARNING**: make sure it is found in `.gitignore`. Save the above [Variables](#environment-variables-explanation) in the `.env` file using the exact provided names.

2. **Install the `python-dotenv` package** (if you haven’t already):
```sh
pip install python-dotenv

3. A brief example on how to load a specific environment variable:
```python
import os
from dotenv import load_dotenv
load_dotenv()
bot_token = os.getenv('BOT_TOKEN')
```
## the structure of the bot
├── code-genie-bot \
# Package initia lization \
# Main bot entry point \
│ ├── handlers \
│ │ # Handlers package initialization \
│ │ # Handle bot commands \
│ ├── utils \
│ │ # Utils package initialization \
│ │ # Helper functions \
│ │ # Input validation \
├── tests \
# Tests package initialization \
# Handlers tests \
# Utils tests \
# Environment variables \
# Git ignore file \
# requermint list \
# readme
├── code-genie-bot \
# Package initialization \
# Main bot entry point \
│ ├── config\
│ │ # managing and loading configuration settings
│ ├── handlers \
│ │ # Handlers package initialization \
│ │ # Handle bot commands \
│ ├── utils \
│ │ # Utils package initialization \
│ │ # Helper functions \
│ │ # Input validation \
├── tests \
# Tests package initialization \
# Handlers tests \
# Utils tests \
# Environment variables \
# Git ignore file \
# requermint list \
# readme
1 change: 1 addition & 0 deletions config/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .config_env import *
37 changes: 37 additions & 0 deletions config/config_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import os

from dotenv import load_dotenv


def create_config_env(env_name):
try:
if env_name in ['dev', 'prod']:
env_file = f'.env_{env_name}'
print('env_file: ', env_file)
suffix = env_name.upper()
if load_dotenv(env_file):
try:
bot_token = os.getenv(f'BOT_TOKEN_{suffix}')
server_url = os.getenv(f'SERVER_URL_{suffix}')
except Exception as e:
print(e)
raise KeyError(f"error in loading env vars: {e}")
else:
raise FileNotFoundError(f"Error: Ensure that the .env_dev or .env_prod file exists.")
else:
raise ValueError(f"Unknown environment: {env_name}")

if not bot_token or not server_url:
raise ValueError(f"Missing environment variables for {env_name}")

with open('.env', 'w') as f:
f.write(f"BOT_TOKEN={bot_token}\n")
f.write(f"SERVER_URL={server_url}\n")

except FileNotFoundError as fnf_error:
raise fnf_error
except ValueError as val_error:
raise val_error
except Exception as e:
raise e

44 changes: 31 additions & 13 deletions genie_bot.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,40 @@
import argparse
from config.config_env import create_config_env
from handlers.handlers import *
from telegram.ext import ApplicationBuilder, CommandHandler
import os
from dotenv import load_dotenv

def main():
# Create the Application and pass it your bot's token.
application = ApplicationBuilder().token(os.getenv('BOT_TOKEN')).build()

# Register command handlers
application.add_handler(CommandHandler("start", start_command))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("ip", get_public_ip_command))
application.add_handler(CommandHandler('question', question_command))
application.add_handler(CommandHandler('api', api_command))
def setup_and_load_env():
parser = argparse.ArgumentParser()
parser.add_argument('env', choices=['dev', 'prod'], nargs='?', default='dev')
args = parser.parse_args()
try:
create_config_env(args.env)
except Exception as e:
raise e


def main():
try:
setup_and_load_env()
load_dotenv('.env')
# Create the Application and pass it your bot's token.
application = ApplicationBuilder().token(os.getenv("BOT_TOKEN")).build()

# Start the Bot
application.run_polling()
# Register command handlers
application.add_handler(CommandHandler("start", start_command))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("ip", get_public_ip_command))
application.add_handler(CommandHandler('question', question_command))
application.add_handler(CommandHandler('api', api_command))

# Start the Bot
application.run_polling()
except Exception as e:
print('e: ', e)
exit(1)

if __name__ == '__main__':
load_dotenv()
main()
main()
5 changes: 0 additions & 5 deletions handlers/handlers.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import os
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import ContextTypes, CallbackContext
import requests
from dotenv import load_dotenv
from config import CONSTANTS

load_dotenv()


SERVER_URL = os.getenv("SERVER_URL")

async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
Expand Down
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,5 @@ typer==0.12.3
typing_extensions==4.12.2
urllib3==2.2.2
uvicorn==0.30.3
uvloop==0.19.0
watchfiles==0.22.0
websockets==12.0
websockets==12.0

0 comments on commit fa0b08e

Please sign in to comment.