Skip to content

Commit

Permalink
Merge pull request #16 from F33RNI/next
Browse files Browse the repository at this point in the history
Next
  • Loading branch information
F33RNI authored Feb 28, 2023
2 parents a20e9f3 + 2b4a965 commit 43b368c
Show file tree
Hide file tree
Showing 9 changed files with 245 additions and 98 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,6 @@ jobs:
tags: |
ghcr.io/${{ steps.lowercaseRepo.outputs.lowercase }}:${{ env.SHORT_SHA }}
ghcr.io/${{ steps.lowercaseRepo.outputs.lowercase }}:${{ env.TAG }}
platforms: linux/amd64,linux/arm64
platforms: linux/amd64
cache-from: type=gha
cache-to: type=gha,mode=max
1 change: 0 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ jobs:
matrix:
platform:
- amd64
- arm64

runs-on: ubuntu-latest

Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/.idea/
/*.zip
/test.py
/logs/
34 changes: 32 additions & 2 deletions Authenticator.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ def __init__(self, settings):
self.proxy_list = []
self.check_loop_running = False

def start_check_loop(self):
def start_chatbot(self):
"""
Starts background thread
Initializes chatbot and starts background proxy checker thread if needed
:return:
"""
# Official API
Expand Down Expand Up @@ -145,6 +145,27 @@ def start_check_loop(self):
logging.error('Wrong chatgpt_api_type!')
raise Exception('Wrong chatgpt_api_type')

def stop_chatbot(self):
"""
Stops background handler and removes chatbot
:return:
"""
logging.info('Stopping chatbot...')
# Clear loop flag
self.check_loop_running = False
self.chatbot_working = False

# Sleep some time
time.sleep(10)

# Remove old chatbot
try:
if self.chatbot is not None:
del self.chatbot
self.chatbot = None
except Exception as e:
logging.warning('Error clearing chatbot! ' + str(e))

def proxy_get(self):
"""
Retrieves proxy from auto_proxy_from url into self.proxy_list
Expand Down Expand Up @@ -260,6 +281,10 @@ def proxy_checker_loop(self):
break
time.sleep(1)

# Exit if thread stopped
if not self.check_loop_running:
break

# Check is not successful
else:
# Get proxy
Expand Down Expand Up @@ -288,6 +313,11 @@ def proxy_checker_loop(self):
default_config = self.get_chatbot_config()

while True:
# Exit if thread stopped
if not self.check_loop_running:
kill_all_processes(processes_and_times)
break

# Create and start processes
while len(self.proxy_list) > 0 \
and len(processes_and_times) \
Expand Down
256 changes: 172 additions & 84 deletions BotHandler.py

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ Note: make shure you don't delete argumensts `{0}` in message and please restart

## Running in Docker

**WARNING: not tested and not recommended**

1. Install Docker
2. Clone repo
3. Build container
Expand Down Expand Up @@ -216,6 +218,7 @@ If you have proxy that definitely works you can specify it in `manual_proxy` in
- `/queue` - Shows requests queue
- `/gpt YOUR REQUEST` - Request to ChatGPT
- `/draw YOUR REQUEST` - Request to DALLE
- `/restart` - Restart chatGPT and Telegram Bot (not tested properly)
- Or just type your request as message without `/gpt` command

----------
Expand Down
40 changes: 32 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,35 +16,59 @@
"""

import argparse
import datetime
import json
import logging
import os
import signal
import sys

import psutil

import AIHandler
import Authenticator
import BotHandler

TELEGRAMUS_VERSION = 'beta_1.7.2'
TELEGRAMUS_VERSION = 'beta_1.8.0'

# Logging level (INFO for debug, WARN for release)
LOGGING_LEVEL = logging.INFO

# JSON Files
# Files and directories
SETTINGS_FILE = 'settings.json'
MESSAGES_FILE = 'messages.json'
LOGS_DIR = 'logs'


def logging_setup():
"""
Sets up logging format and level
:return:
"""
logging.basicConfig(encoding='utf-8', format='%(asctime)s %(levelname)-8s %(message)s',
level=LOGGING_LEVEL,
datefmt='%Y-%m-%d %H:%M:%S')
# Create logs directory
if not os.path.exists(LOGS_DIR):
os.makedirs(LOGS_DIR)

# Create logs formatter
log_formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

# Setup logging into file
file_handler = logging.FileHandler(os.path.join(LOGS_DIR,
datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S') + '.log'),
encoding='utf-8')
file_handler.setFormatter(log_formatter)

# Setup logging into console
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(log_formatter)

# Add all handlers and setup level
root_logger = logging.getLogger()
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)
root_logger.setLevel(LOGGING_LEVEL)

# Log test message
logging.info('logging setup is complete')


Expand Down Expand Up @@ -106,7 +130,7 @@ def main():
logging_setup()

# Connect interrupt signal
signal.signal(signal.SIGINT, exit_)
#signal.signal(signal.SIGINT, exit_)

# Parse arguments and load settings and messages
args = parse_args()
Expand All @@ -121,8 +145,8 @@ def main():
# Set requests_queue to ai_handler
ai_handler.requests_queue = bot_handler.requests_queue

# Start checker loop
authenticator.start_check_loop()
# Initialize chatbot and start checker loop
authenticator.start_chatbot()

# Start AIHandler
ai_handler.thread_start()
Expand Down
4 changes: 3 additions & 1 deletion messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@
"queue_stats": "Queue:\\n\\n{0}",
"queue_accepted": "Added to the queue. Position: {0}/{1}",
"gpt_error": "Error: {0}\\n\\nMake another request or try again later =(",
"reset": "Reset command sent"
"reset": "Reset command sent",
"restarting": "Restarting in progress...\\nPlease wait",
"restarting_done": "The restart is completed"
}
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
psutil>=5.9.1
telegram~=0.0.1
python-telegram-bot~=20.0
python-telegram-bot~=20.1
revChatGPT>=2.3.14
openai>=0.26.4
tiktoken>=0.2.0
Expand Down

0 comments on commit 43b368c

Please sign in to comment.