Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

----------------------- start mjlistener.py import sys import json import time import…

  1. User

    start mj_listener.py

    import sys import json import time import requests import websocket import redis import os

    status = "online"

    custom_status = "" #If you don't need a custom status on your profile, just put "" instead of "youtube.com/@SealedSaucer"

    usertoken = "MTA5MTU0NzI0NDI5OTI4ODY2Ng.GMaoTA.5KH_NZeSoLC-9hy1Owa7VgljEboJ0ZtV3u90cg"

    headers = {"Authorization": usertoken, "Content-Type": "application/json"}

    validate = requests.get('https://discordapp.com/api/v9/users/@me', headers=headers) if validate.status_code != 200: print("[ERROR] Your token might be invalid. Please check it again.") sys.exit()

    userinfo = requests.get('https://discordapp.com/api/v9/users/@me', headers=headers).json() username = userinfo["username"] discriminator = userinfo["discriminator"] userid = userinfo["id"]

    r = redis.Redis( host='0.0.0.0', port=6379, password="123", decode_responses=True )

    def connect(ws, token): print('============ПЕРЕЗАПУСК=============')

    ws.connect("wss://gateway.discord.gg/?v=9&encoding=json")
    start = json.loads(ws.recv())
    heartbeat = start["d"]["heartbeat_interval"]
    auth = {
        "op": 2,
        "d": {
            "token": token,
            "properties": {
                "$os": "Windows 10",
                "$browser": "Google Chrome",
                "$device": "Windows",
            },
            "presence": {"status": status, "afk": False},
        },
        "s": None,
        "t": None,
    }
    ws.send(json.dumps(auth))
    

    def onliner(token, status): ws = websocket.WebSocket() connect(ws, token) cstatus = { "op": 3, "d": { "since": 0, "activities": [ { "type": 4, "state": custom_status, "name": "Custom Status", "id": "custom", #Uncomment the below lines if you want an emoji in the status #"emoji": { #"name": "emoji name", #"id": "emoji id", #"animated": False, #}, } ], "status": status, "afk": False, }, } ws.send(json.dumps(cstatus)) online = {"op": 1, "d": "None"} while True: try: message = json.loads(ws.recv()) # print(message) try: if message["t"] in ["MESSAGE_CREATE", "MESSAGE_UPDATE"]: print(message['d']['content']) except: ... r.publish("mj-response", ws.recv()) except websocket.WebSocketConnectionClosedException: connect(ws, token) except: ...

    def run_onliner(): # os.system("clear") print(f"Logged in as {username}#{discriminator} ({userid}).") while True: onliner(usertoken, status) time.sleep(10)

    if name == 'main': run_onliner()

    #end mj_listener.py

    start listener.py

    import redis import asyncio import json from handlers import img_mj_handlers

    r = redis.Redis( host='0.0.0.0', port=6379, password="123", decode_responses=True )

    listener = r.pubsub() listener.subscribe('mj-response')

    def proccess_message(message): prompt, msg, status = '', '', '' if message['t'] == 'MESSAGE_CREATE': print('19', message['d']['content']) # запрос принят if '(Waiting to start)' in message['d']['content']: prompt = message['d']['content'].split('')[1] msg = '✅ Запрос принят!' status = 'request sent'

        # изображение сгенерировано
        elif '(relaxed)' in message['d']['content'] or '(fast)' in message['d']['content']:
            prompt = message['d']['content'].split('')[1]
            img_link = message['d']['attachments'][0]['url']
            ds_msg_id = message['d']['id']
            msg = f'{img_link} | {ds_msg_id}'
            status = 'response got'
        
        elif 'Image #' in message['d']['content']:
            prompt = message['d']['content'].split('')[1]
            img_link = message['d']['attachments'][0]['url']
            ds_msg_id = message['d']['id']
            msg = f'{img_link} | {ds_msg_id}'
            status = 'response got upscaled'
    
    
        # блок обработки изображения
        # elif 'Image #' in message['d']['content']:
    
    
        else:
            # блок ошибок
            try:
                error_title = message['d']['embeds'][0]['title']
                prompt = message['d']['embeds'][0]['footer']['text'].replace('/imagine ', '')
    
                # использованы запрещенные слова
                if error_title == 'Banned prompt':
                    error_description = message['d']['embeds'][0]['description']
                    banned_word = error_description.split('`')[1]
                    with open('static/stop_word_list.txt', 'a') as f:
                        f.write('\n', banned_word)
    
                    msg = f'Нарушение правил Midjourney.\nУдалите в запросе слово: {banned_word}'
                    
                
                # запрос попал в очередь
                elif error_title == 'Job queued':
                    error_description = message['d']['embeds'][0]['description']
                    msg = 'Ваш запрос находится в очереди'
    
                # слишком много запросов в очереди, необходимо повторить позже
                elif error_title == 'Queue full':
                    error_description = message['d']['embeds'][0]['description']
    
                # ошибка
                else:
                    error_description = message['d']['embeds'][0]['description']
                    msg = 'Возникла непредвиденная ошибка на стороне Midjourney.\nНапишите нам в поддержку @neural_help. И пришлите, пожалуйста, скриншот.'
                    if ':::::' in error_description:
                        exit()
                if msg == '':
                    msg = f'{error_title}\n{error_description}'
                status = 'error'
            
            except:
                ...
    
    
    # прогресс генерации изображения
    elif message['t'] == 'MESSAGE_UPDATE':    
        print('58', message['d']['content'])
    
        if '%' in message['d']['content']:
            percentage = message['d']['content'].split('%)')[0].split('(')[-1]
            msg = f"{int(percentage) // 10 * '🟢' + (10 - int(percentage) // 10) * '⚪️'} {percentage}%"
            prompt = message['d']['content'].split('')[1]
            status = 'loading'
    
    else:
        return '', '', ''
    
    return prompt, msg, status
    

    end listener.py


    Задача Ответы от midjourney бывают разных типов, одним из таких является переполнение очереди в дискорд сервере (максимальное кол-во = 12). В таком случае необходимо создать очередь, и добавить запросы с таким ответом в нее. По мере возможности отправлять запросы из очереди в бот.

  2. Assistant

    Для реализации данной задачи можно воспользоваться следующим алгоритмом:

    1. Создать структуру данных очереди, например, используя встроенный модуль queue в Python.
    2. Отслеживать ответы от сервера Midjourney и проверять, является ли ответ переполнение очереди.
    3. Если ответ является переполнением очереди, то добавить запрос в нашу очередь.
    4. В отдельном потоке производить проверку своей очереди и состояние сервера Midjourney (кол-во запросов в очереди). Если на сервере Midjourney есть свободное место и в нашей очереди есть запросы, то отправить запрос из очереди на сервер Midjourney и удалить запрос из нашей очереди.

    Реализация алгоритма на Python:

    1. Импортируем нужные модули и создаем очередь:
    import queue
    import threading
    import time
    
    my_queue = queue.Queue()
    
    1. Изменяем функцию proccess_message так, чтобы добавлять запросы с переполненной очередью на сервере Midjourney в нашу очередь:
    def proccess_message(message):
        # ... (прочий код)
    
        # слишком много запросов в очереди, необходимо повторить позже
        elif error_title == 'Queue full':
            error_description = message['d']['embeds'][0]['description']
            my_queue.put(prompt)  # добавляем запрос в нашу очередь
    
        # ... (прочий код)
    
    1. Создадим функцию, которая будет проверять сервер Midjourney и отправлять запросы из нашей очереди, если это возможно:
    def check_queue_and_send():
        while True:
            if not my_queue.empty():  # если в нашей очереди есть запросы
                # проверяем количество запросов на сервере Midjourney
                server_queue_length = check_midjourney_queue_length()  # функцию проверки нужно реализовать
    
                if server_queue_length < 12:  # если на сервере есть свободное место
                    prompt = my_queue.get()
                    send_request_to_midjourney(prompt)  # функцию отправки запроса нужно реализовать
    
            time.sleep(5)  # проверяем каждые 5 секунд
    
    1. Запускаем функцию check_queue_and_send в отдельном потоке:
    queue_handler_thread = threading.Thread(target=check_queue_and_send)
    queue_handler_thread.start()
    

    Таким образом, при получении ответа о переполнении очереди на сервере Midjourney, запросы будут добавляться в нашу очередь. Когда на сервере Midjourney освободится место, запросы из нашей очереди будут отправляться на сервер Midjourney.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.